binding_generator.py 114 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975
  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) or class_name == "Array":
  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. if class_name == "Array":
  505. result.append("")
  506. result.append("\tconst Variant *ptr() const;")
  507. result.append("\tVariant *ptrw();")
  508. result.append("")
  509. result.append("public:")
  510. result.append(
  511. f"\t_FORCE_INLINE_ GDExtensionTypePtr _native_ptr() const {{ return const_cast<uint8_t(*)[{snake_class_name}_SIZE]>(&opaque); }}"
  512. )
  513. copy_constructor_index = -1
  514. if "constructors" in builtin_api:
  515. for constructor in builtin_api["constructors"]:
  516. method_signature = f"\t{class_name}("
  517. if "arguments" in constructor:
  518. method_signature += make_function_parameters(
  519. constructor["arguments"], include_default=True, for_builtin=True
  520. )
  521. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  522. copy_constructor_index = constructor["index"]
  523. method_signature += ");"
  524. result.append(method_signature)
  525. # Move constructor.
  526. result.append(f"\t{class_name}({class_name} &&p_other);")
  527. # Special cases.
  528. if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
  529. if class_name == "StringName":
  530. result.append(f"\t{class_name}(const char *p_from, bool p_static = false);")
  531. else:
  532. result.append(f"\t{class_name}(const char *p_from);")
  533. result.append(f"\t{class_name}(const wchar_t *p_from);")
  534. result.append(f"\t{class_name}(const char16_t *p_from);")
  535. result.append(f"\t{class_name}(const char32_t *p_from);")
  536. if class_name == "Callable":
  537. result.append("\tCallable(CallableCustom *p_custom);")
  538. result.append("\tCallableCustom *get_custom() const;")
  539. if "constants" in builtin_api:
  540. axis_constants_count = 0
  541. for constant in builtin_api["constants"]:
  542. # Special case: Vector3.Axis is the only enum in the bindings.
  543. # It's technically not supported by Variant but works for direct access.
  544. if class_name == "Vector3" and constant["name"].startswith("AXIS"):
  545. if axis_constants_count == 0:
  546. result.append("\tenum Axis {")
  547. result.append(f"\t\t{constant['name']} = {constant['value']},")
  548. axis_constants_count += 1
  549. if axis_constants_count == 3:
  550. result.append("\t};")
  551. else:
  552. result.append(f"\tstatic const {correct_type(constant['type'])} {constant['name']};")
  553. if builtin_api["has_destructor"]:
  554. result.append(f"\t~{class_name}();")
  555. method_list = []
  556. if "methods" in builtin_api:
  557. for method in builtin_api["methods"]:
  558. method_list.append(method["name"])
  559. vararg = method["is_vararg"]
  560. if vararg:
  561. result.append("\ttemplate <typename... Args>")
  562. method_signature = "\t"
  563. if "is_static" in method and method["is_static"]:
  564. method_signature += "static "
  565. if "return_type" in method:
  566. method_signature += f"{correct_type(method['return_type'])}"
  567. if not method_signature.endswith("*"):
  568. method_signature += " "
  569. else:
  570. method_signature += "void "
  571. method_signature += f"{method['name']}("
  572. method_arguments = []
  573. if "arguments" in method:
  574. method_arguments = method["arguments"]
  575. method_signature += make_function_parameters(
  576. method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
  577. )
  578. method_signature += ")"
  579. if method["is_const"]:
  580. method_signature += " const"
  581. method_signature += ";"
  582. result.append(method_signature)
  583. # Special cases.
  584. if class_name == "String":
  585. result.append("\tstatic String utf8(const char *p_from, int64_t p_len = -1);")
  586. result.append("\tError parse_utf8(const char *p_from, int64_t p_len = -1);")
  587. result.append("\tstatic String utf16(const char16_t *p_from, int64_t p_len = -1);")
  588. result.append(
  589. "\tError parse_utf16(const char16_t *p_from, int64_t p_len = -1, bool p_default_little_endian = true);"
  590. )
  591. result.append("\tCharString utf8() const;")
  592. result.append("\tCharString ascii() const;")
  593. result.append("\tChar16String utf16() const;")
  594. result.append("\tChar32String utf32() const;")
  595. result.append("\tCharWideString wide_string() const;")
  596. result.append("\tstatic String num_real(double p_num, bool p_trailing = true);")
  597. result.append("\tError resize(int64_t p_size);")
  598. if "members" in builtin_api:
  599. for member in builtin_api["members"]:
  600. if f"get_{member['name']}" not in method_list:
  601. result.append(f"\t{correct_type(member['type'])} get_{member['name']}() const;")
  602. if f"set_{member['name']}" not in method_list:
  603. result.append(f"\tvoid set_{member['name']}({type_for_parameter(member['type'])}value);")
  604. if "operators" in builtin_api:
  605. for operator in builtin_api["operators"]:
  606. if is_valid_cpp_operator(operator["name"]):
  607. if "right_type" in operator:
  608. result.append(
  609. f"\t{correct_type(operator['return_type'])} operator{get_operator_cpp_name(operator['name'])}({type_for_parameter(operator['right_type'])}p_other) const;"
  610. )
  611. else:
  612. result.append(
  613. f"\t{correct_type(operator['return_type'])} operator{get_operator_cpp_name(operator['name'])}() const;"
  614. )
  615. # Copy assignment.
  616. if copy_constructor_index >= 0:
  617. result.append(f"\t{class_name} &operator=(const {class_name} &p_other);")
  618. # Move assignment.
  619. result.append(f"\t{class_name} &operator=({class_name} &&p_other);")
  620. # Special cases.
  621. if class_name == "String":
  622. result.append("\tString &operator=(const char *p_str);")
  623. result.append("\tString &operator=(const wchar_t *p_str);")
  624. result.append("\tString &operator=(const char16_t *p_str);")
  625. result.append("\tString &operator=(const char32_t *p_str);")
  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("\tbool operator!=(const char *p_str) const;")
  631. result.append("\tbool operator!=(const wchar_t *p_str) const;")
  632. result.append("\tbool operator!=(const char16_t *p_str) const;")
  633. result.append("\tbool operator!=(const char32_t *p_str) const;")
  634. result.append("\tString operator+(const char *p_str);")
  635. result.append("\tString operator+(const wchar_t *p_str);")
  636. result.append("\tString operator+(const char16_t *p_str);")
  637. result.append("\tString operator+(const char32_t *p_str);")
  638. result.append("\tString operator+(char32_t p_char);")
  639. result.append("\tString &operator+=(const String &p_str);")
  640. result.append("\tString &operator+=(char32_t p_char);")
  641. result.append("\tString &operator+=(const char *p_str);")
  642. result.append("\tString &operator+=(const wchar_t *p_str);")
  643. result.append("\tString &operator+=(const char32_t *p_str);")
  644. result.append("\tconst char32_t &operator[](int64_t p_index) const;")
  645. result.append("\tchar32_t &operator[](int64_t p_index);")
  646. result.append("\tconst char32_t *ptr() const;")
  647. result.append("\tchar32_t *ptrw();")
  648. if class_name == "Array":
  649. result.append("\ttemplate <typename... Args>")
  650. result.append("\tstatic Array make(Args... p_args) {")
  651. result.append("\t\treturn helpers::append_all(Array(), p_args...);")
  652. result.append("\t}")
  653. if is_packed_array(class_name):
  654. return_type = correct_type(builtin_api["indexing_return_type"])
  655. if class_name == "PackedByteArray":
  656. return_type = "uint8_t"
  657. elif class_name == "PackedInt32Array":
  658. return_type = "int32_t"
  659. elif class_name == "PackedFloat32Array":
  660. return_type = "float"
  661. result.append(f"\tconst {return_type} &operator[](int64_t p_index) const;")
  662. result.append(f"\t{return_type} &operator[](int64_t p_index);")
  663. result.append(f"\tconst {return_type} *ptr() const;")
  664. result.append(f"\t{return_type} *ptrw();")
  665. iterators = """
  666. struct Iterator {
  667. _FORCE_INLINE_ $TYPE &operator*() const {
  668. return *elem_ptr;
  669. }
  670. _FORCE_INLINE_ $TYPE *operator->() const { return elem_ptr; }
  671. _FORCE_INLINE_ Iterator &operator++() {
  672. elem_ptr++;
  673. return *this;
  674. }
  675. _FORCE_INLINE_ Iterator &operator--() {
  676. elem_ptr--;
  677. return *this;
  678. }
  679. _FORCE_INLINE_ bool operator==(const Iterator &b) const { return elem_ptr == b.elem_ptr; }
  680. _FORCE_INLINE_ bool operator!=(const Iterator &b) const { return elem_ptr != b.elem_ptr; }
  681. Iterator($TYPE *p_ptr) { elem_ptr = p_ptr; }
  682. Iterator() {}
  683. Iterator(const Iterator &p_it) { elem_ptr = p_it.elem_ptr; }
  684. private:
  685. $TYPE *elem_ptr = nullptr;
  686. };
  687. struct ConstIterator {
  688. _FORCE_INLINE_ const $TYPE &operator*() const {
  689. return *elem_ptr;
  690. }
  691. _FORCE_INLINE_ const $TYPE *operator->() const { return elem_ptr; }
  692. _FORCE_INLINE_ ConstIterator &operator++() {
  693. elem_ptr++;
  694. return *this;
  695. }
  696. _FORCE_INLINE_ ConstIterator &operator--() {
  697. elem_ptr--;
  698. return *this;
  699. }
  700. _FORCE_INLINE_ bool operator==(const ConstIterator &b) const { return elem_ptr == b.elem_ptr; }
  701. _FORCE_INLINE_ bool operator!=(const ConstIterator &b) const { return elem_ptr != b.elem_ptr; }
  702. ConstIterator(const $TYPE *p_ptr) { elem_ptr = p_ptr; }
  703. ConstIterator() {}
  704. ConstIterator(const ConstIterator &p_it) { elem_ptr = p_it.elem_ptr; }
  705. private:
  706. const $TYPE *elem_ptr = nullptr;
  707. };
  708. _FORCE_INLINE_ Iterator begin() {
  709. return Iterator(ptrw());
  710. }
  711. _FORCE_INLINE_ Iterator end() {
  712. return Iterator(ptrw() + size());
  713. }
  714. _FORCE_INLINE_ ConstIterator begin() const {
  715. return ConstIterator(ptr());
  716. }
  717. _FORCE_INLINE_ ConstIterator end() const {
  718. return ConstIterator(ptr() + size());
  719. }"""
  720. result.append(iterators.replace("$TYPE", return_type))
  721. init_list = """
  722. _FORCE_INLINE_ $CLASS(std::initializer_list<$TYPE> p_init) {
  723. ERR_FAIL_COND(resize(p_init.size()) != 0);
  724. size_t i = 0;
  725. for (const $TYPE &element : p_init) {
  726. set(i++, element);
  727. }
  728. }"""
  729. result.append(init_list.replace("$TYPE", return_type).replace("$CLASS", class_name))
  730. if class_name == "Array":
  731. result.append("\tconst Variant &operator[](int64_t p_index) const;")
  732. result.append("\tVariant &operator[](int64_t p_index);")
  733. result.append("\tvoid set_typed(uint32_t p_type, const StringName &p_class_name, const Variant &p_script);")
  734. result.append("""
  735. struct Iterator {
  736. _FORCE_INLINE_ Variant &operator*() const;
  737. _FORCE_INLINE_ Variant *operator->() const;
  738. _FORCE_INLINE_ Iterator &operator++();
  739. _FORCE_INLINE_ Iterator &operator--();
  740. _FORCE_INLINE_ bool operator==(const Iterator &b) const { return elem_ptr == b.elem_ptr; }
  741. _FORCE_INLINE_ bool operator!=(const Iterator &b) const { return elem_ptr != b.elem_ptr; }
  742. Iterator(Variant *p_ptr) { elem_ptr = p_ptr; }
  743. Iterator() {}
  744. Iterator(const Iterator &p_it) { elem_ptr = p_it.elem_ptr; }
  745. private:
  746. Variant *elem_ptr = nullptr;
  747. };
  748. struct ConstIterator {
  749. _FORCE_INLINE_ const Variant &operator*() const;
  750. _FORCE_INLINE_ const Variant *operator->() const;
  751. _FORCE_INLINE_ ConstIterator &operator++();
  752. _FORCE_INLINE_ ConstIterator &operator--();
  753. _FORCE_INLINE_ bool operator==(const ConstIterator &b) const { return elem_ptr == b.elem_ptr; }
  754. _FORCE_INLINE_ bool operator!=(const ConstIterator &b) const { return elem_ptr != b.elem_ptr; }
  755. ConstIterator(const Variant *p_ptr) { elem_ptr = p_ptr; }
  756. ConstIterator() {}
  757. ConstIterator(const ConstIterator &p_it) { elem_ptr = p_it.elem_ptr; }
  758. private:
  759. const Variant *elem_ptr = nullptr;
  760. };
  761. _FORCE_INLINE_ Iterator begin();
  762. _FORCE_INLINE_ Iterator end();
  763. _FORCE_INLINE_ ConstIterator begin() const;
  764. _FORCE_INLINE_ ConstIterator end() const;
  765. """)
  766. result.append("\t_FORCE_INLINE_ Array(std::initializer_list<Variant> p_init);")
  767. if class_name == "Dictionary":
  768. result.append("\tconst Variant &operator[](const Variant &p_key) const;")
  769. result.append("\tVariant &operator[](const Variant &p_key);")
  770. result.append(
  771. "\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);"
  772. )
  773. result.append("};")
  774. if class_name == "String":
  775. result.append("")
  776. result.append("bool operator==(const char *p_chr, const String &p_str);")
  777. result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
  778. result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
  779. result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
  780. result.append("bool operator!=(const char *p_chr, const String &p_str);")
  781. result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
  782. result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
  783. result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
  784. result.append("String operator+(const char *p_chr, const String &p_str);")
  785. result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
  786. result.append("String operator+(const char16_t *p_chr, const String &p_str);")
  787. result.append("String operator+(const char32_t *p_chr, const String &p_str);")
  788. result.append("String operator+(char32_t p_char, const String &p_str);")
  789. result.append("String itos(int64_t p_val);")
  790. result.append("String uitos(uint64_t p_val);")
  791. result.append("String rtos(double p_val);")
  792. result.append("String rtoss(double p_val);")
  793. result.append("")
  794. result.append("} // namespace godot")
  795. result.append("")
  796. return "\n".join(result)
  797. def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
  798. result = []
  799. class_name = builtin_api["name"]
  800. snake_class_name = camel_to_snake(class_name)
  801. enum_type_name = f"GDEXTENSION_VARIANT_TYPE_{snake_class_name.upper()}"
  802. add_header(f"{snake_class_name}.cpp", result)
  803. result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
  804. result.append("")
  805. result.append("#include <godot_cpp/core/binder_common.hpp>")
  806. result.append("")
  807. result.append("#include <godot_cpp/godot.hpp>")
  808. result.append("")
  809. # Only used since the "fully used" is included in header already.
  810. if len(used_classes) > 0:
  811. includes = []
  812. for included in used_classes:
  813. includes.append(f"godot_cpp/{get_include_path(included)}")
  814. includes.sort()
  815. for included in includes:
  816. result.append(f"#include <{included}>")
  817. result.append("")
  818. result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
  819. result.append("")
  820. result.append("#include <utility>")
  821. result.append("")
  822. result.append("namespace godot {")
  823. result.append("")
  824. result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
  825. result.append("")
  826. result.append(f"void {class_name}::_init_bindings_constructors_destructor() {{")
  827. result.append(
  828. f"\t_method_bindings.from_variant_constructor = internal::gdextension_interface_get_variant_to_type_constructor({enum_type_name});"
  829. )
  830. if "constructors" in builtin_api:
  831. for constructor in builtin_api["constructors"]:
  832. result.append(
  833. f"\t_method_bindings.constructor_{constructor['index']} = internal::gdextension_interface_variant_get_ptr_constructor({enum_type_name}, {constructor['index']});"
  834. )
  835. if builtin_api["has_destructor"]:
  836. result.append(
  837. f"\t_method_bindings.destructor = internal::gdextension_interface_variant_get_ptr_destructor({enum_type_name});"
  838. )
  839. result.append("}")
  840. result.append(f"void {class_name}::init_bindings() {{")
  841. # StringName's constructor internally uses String, so it constructor must be ready !
  842. if class_name == "StringName":
  843. result.append("\tString::_init_bindings_constructors_destructor();")
  844. result.append(f"\t{class_name}::_init_bindings_constructors_destructor();")
  845. result.append("\tStringName _gde_name;")
  846. if "methods" in builtin_api:
  847. for method in builtin_api["methods"]:
  848. # TODO: Add error check for hash mismatch.
  849. result.append(f'\t_gde_name = StringName("{method["name"]}");')
  850. result.append(
  851. f"\t_method_bindings.method_{method['name']} = internal::gdextension_interface_variant_get_ptr_builtin_method({enum_type_name}, _gde_name._native_ptr(), {method['hash']});"
  852. )
  853. if "members" in builtin_api:
  854. for member in builtin_api["members"]:
  855. result.append(f'\t_gde_name = StringName("{member["name"]}");')
  856. result.append(
  857. f"\t_method_bindings.member_{member['name']}_setter = internal::gdextension_interface_variant_get_ptr_setter({enum_type_name}, _gde_name._native_ptr());"
  858. )
  859. result.append(
  860. f"\t_method_bindings.member_{member['name']}_getter = internal::gdextension_interface_variant_get_ptr_getter({enum_type_name}, _gde_name._native_ptr());"
  861. )
  862. if "indexing_return_type" in builtin_api:
  863. result.append(
  864. f"\t_method_bindings.indexed_setter = internal::gdextension_interface_variant_get_ptr_indexed_setter({enum_type_name});"
  865. )
  866. result.append(
  867. f"\t_method_bindings.indexed_getter = internal::gdextension_interface_variant_get_ptr_indexed_getter({enum_type_name});"
  868. )
  869. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  870. result.append(
  871. f"\t_method_bindings.keyed_setter = internal::gdextension_interface_variant_get_ptr_keyed_setter({enum_type_name});"
  872. )
  873. result.append(
  874. f"\t_method_bindings.keyed_getter = internal::gdextension_interface_variant_get_ptr_keyed_getter({enum_type_name});"
  875. )
  876. result.append(
  877. f"\t_method_bindings.keyed_checker = internal::gdextension_interface_variant_get_ptr_keyed_checker({enum_type_name});"
  878. )
  879. if "operators" in builtin_api:
  880. for operator in builtin_api["operators"]:
  881. if "right_type" in operator:
  882. if operator["right_type"] == "Variant":
  883. right_type_variant_type = "GDEXTENSION_VARIANT_TYPE_NIL"
  884. else:
  885. right_type_variant_type = (
  886. f"GDEXTENSION_VARIANT_TYPE_{camel_to_snake(operator['right_type']).upper()}"
  887. )
  888. result.append(
  889. 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});"
  890. )
  891. else:
  892. result.append(
  893. 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);"
  894. )
  895. result.append("}")
  896. result.append("")
  897. copy_constructor_index = -1
  898. result.append(f"{class_name}::{class_name}(const Variant *p_variant) {{")
  899. result.append("\t_method_bindings.from_variant_constructor(&opaque, p_variant->_native_ptr());")
  900. result.append("}")
  901. result.append("")
  902. if "constructors" in builtin_api:
  903. for constructor in builtin_api["constructors"]:
  904. method_signature = f"{class_name}::{class_name}("
  905. if "arguments" in constructor:
  906. method_signature += make_function_parameters(
  907. constructor["arguments"], include_default=False, for_builtin=True
  908. )
  909. method_signature += ") {"
  910. result.append(method_signature)
  911. method_call = (
  912. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor['index']}, &opaque"
  913. )
  914. if "arguments" in constructor:
  915. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  916. copy_constructor_index = constructor["index"]
  917. method_call += ", "
  918. arguments = []
  919. for argument in constructor["arguments"]:
  920. (encode, arg_name) = get_encoded_arg(
  921. argument["name"],
  922. argument["type"],
  923. argument["meta"] if "meta" in argument else None,
  924. )
  925. result += encode
  926. arguments.append(arg_name)
  927. method_call += ", ".join(arguments)
  928. method_call += ");"
  929. result.append(method_call)
  930. result.append("}")
  931. result.append("")
  932. # Move constructor.
  933. result.append(f"{class_name}::{class_name}({class_name} &&p_other) {{")
  934. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  935. result.append(
  936. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &p_other);"
  937. )
  938. else:
  939. result.append("\tstd::swap(opaque, p_other.opaque);")
  940. result.append("}")
  941. result.append("")
  942. if builtin_api["has_destructor"]:
  943. result.append(f"{class_name}::~{class_name}() {{")
  944. result.append("\t_method_bindings.destructor(&opaque);")
  945. result.append("}")
  946. result.append("")
  947. method_list = []
  948. if "methods" in builtin_api:
  949. for method in builtin_api["methods"]:
  950. method_list.append(method["name"])
  951. if "is_vararg" in method and method["is_vararg"]:
  952. # Done in the header because of the template.
  953. continue
  954. method_signature = make_signature(class_name, method, for_builtin=True)
  955. result.append(method_signature + " {")
  956. method_call = "\t"
  957. is_ref = False
  958. if "return_type" in method:
  959. return_type = method["return_type"]
  960. if is_enum(return_type):
  961. method_call += f"return ({get_gdextension_type(correct_type(return_type))})internal::_call_builtin_method_ptr_ret<int64_t>("
  962. elif is_pod_type(return_type) or is_variant(return_type):
  963. method_call += f"return internal::_call_builtin_method_ptr_ret<{get_gdextension_type(correct_type(return_type))}>("
  964. elif is_refcounted(return_type):
  965. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_builtin_method_ptr_ret_obj<{return_type}>("
  966. is_ref = True
  967. else:
  968. method_call += f"return internal::_call_builtin_method_ptr_ret_obj<{return_type}>("
  969. else:
  970. method_call += "internal::_call_builtin_method_ptr_no_ret("
  971. method_call += f"_method_bindings.method_{method['name']}, "
  972. if "is_static" in method and method["is_static"]:
  973. method_call += "nullptr"
  974. else:
  975. method_call += "(GDExtensionTypePtr)&opaque"
  976. if "arguments" in method:
  977. arguments = []
  978. method_call += ", "
  979. for argument in method["arguments"]:
  980. (encode, arg_name) = get_encoded_arg(
  981. argument["name"],
  982. argument["type"],
  983. argument["meta"] if "meta" in argument else None,
  984. )
  985. result += encode
  986. arguments.append(arg_name)
  987. method_call += ", ".join(arguments)
  988. if is_ref:
  989. method_call += ")" # Close Ref<> constructor.
  990. method_call += ");"
  991. result.append(method_call)
  992. result.append("}")
  993. result.append("")
  994. if "members" in builtin_api:
  995. for member in builtin_api["members"]:
  996. if f"get_{member['name']}" not in method_list:
  997. result.append(f"{correct_type(member['type'])} {class_name}::get_{member['name']}() const {{")
  998. result.append(
  999. f"\treturn internal::_call_builtin_ptr_getter<{correct_type(member['type'])}>(_method_bindings.member_{member['name']}_getter, (GDExtensionConstTypePtr)&opaque);"
  1000. )
  1001. result.append("}")
  1002. if f"set_{member['name']}" not in method_list:
  1003. result.append(f"void {class_name}::set_{member['name']}({type_for_parameter(member['type'])}value) {{")
  1004. (encode, arg_name) = get_encoded_arg("value", member["type"], None)
  1005. result += encode
  1006. result.append(
  1007. f"\t_method_bindings.member_{member['name']}_setter((GDExtensionConstTypePtr)&opaque, (GDExtensionConstTypePtr){arg_name});"
  1008. )
  1009. result.append("}")
  1010. result.append("")
  1011. if "operators" in builtin_api:
  1012. for operator in builtin_api["operators"]:
  1013. if is_valid_cpp_operator(operator["name"]):
  1014. if "right_type" in operator:
  1015. result.append(
  1016. f"{correct_type(operator['return_type'])} {class_name}::operator{get_operator_cpp_name(operator['name'])}({type_for_parameter(operator['right_type'])}p_other) const {{"
  1017. )
  1018. (encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
  1019. result += encode
  1020. result.append(
  1021. 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});"
  1022. )
  1023. result.append("}")
  1024. else:
  1025. result.append(
  1026. f"{correct_type(operator['return_type'])} {class_name}::operator{get_operator_cpp_name(operator['name'])}() const {{"
  1027. )
  1028. result.append(
  1029. 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);"
  1030. )
  1031. result.append("}")
  1032. result.append("")
  1033. # Copy assignment.
  1034. if copy_constructor_index >= 0:
  1035. result.append(f"{class_name} &{class_name}::operator=(const {class_name} &p_other) {{")
  1036. if builtin_api["has_destructor"]:
  1037. result.append("\t_method_bindings.destructor(&opaque);")
  1038. (encode, arg_name) = get_encoded_arg(
  1039. "other",
  1040. class_name,
  1041. None,
  1042. )
  1043. result += encode
  1044. result.append(
  1045. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
  1046. )
  1047. result.append("\treturn *this;")
  1048. result.append("}")
  1049. result.append("")
  1050. # Move assignment.
  1051. result.append(f"{class_name} &{class_name}::operator=({class_name} &&p_other) {{")
  1052. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  1053. result.append(
  1054. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &p_other);"
  1055. )
  1056. else:
  1057. result.append("\tstd::swap(opaque, p_other.opaque);")
  1058. result.append("\treturn *this;")
  1059. result.append("}")
  1060. result.append("")
  1061. result.append("} //namespace godot")
  1062. result.append("")
  1063. return "\n".join(result)
  1064. def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
  1065. global engine_classes
  1066. global singletons
  1067. global native_structures
  1068. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1069. source_gen_folder = Path(output_dir) / "src" / "classes"
  1070. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1071. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1072. # First create map of classes and singletons.
  1073. for class_api in api["classes"]:
  1074. # Generate code for the ClassDB singleton under a different name.
  1075. if class_api["name"] in CLASS_ALIASES:
  1076. class_api["alias_for"] = class_api["name"]
  1077. class_api["name"] = CLASS_ALIASES[class_api["alias_for"]]
  1078. engine_classes[class_api["name"]] = class_api["is_refcounted"]
  1079. for native_struct in api["native_structures"]:
  1080. if native_struct["name"] == "ObjectID":
  1081. continue
  1082. engine_classes[native_struct["name"]] = False
  1083. native_structures.append(native_struct["name"])
  1084. for singleton in api["singletons"]:
  1085. # Generate code for the ClassDB singleton under a different name.
  1086. if singleton["name"] in CLASS_ALIASES:
  1087. singleton["alias_for"] = singleton["name"]
  1088. singleton["name"] = CLASS_ALIASES[singleton["name"]]
  1089. singletons.append(singleton["name"])
  1090. for class_api in api["classes"]:
  1091. # Check used classes for header include.
  1092. used_classes = set()
  1093. fully_used_classes = set()
  1094. class_name = class_api["name"]
  1095. header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
  1096. source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
  1097. if "methods" in class_api:
  1098. for method in class_api["methods"]:
  1099. if "arguments" in method:
  1100. for argument in method["arguments"]:
  1101. type_name = argument["type"]
  1102. if type_name.startswith("const "):
  1103. type_name = type_name[6:]
  1104. if type_name.endswith("*"):
  1105. type_name = type_name[:-1]
  1106. if is_included(type_name, class_name):
  1107. if type_name.startswith("typedarray::"):
  1108. fully_used_classes.add("TypedArray")
  1109. array_type_name = type_name.replace("typedarray::", "")
  1110. if array_type_name.startswith("const "):
  1111. array_type_name = array_type_name[6:]
  1112. if array_type_name.endswith("*"):
  1113. array_type_name = array_type_name[:-1]
  1114. if is_included(array_type_name, class_name):
  1115. if is_enum(array_type_name):
  1116. fully_used_classes.add(get_enum_class(array_type_name))
  1117. elif "default_value" in argument:
  1118. fully_used_classes.add(array_type_name)
  1119. else:
  1120. used_classes.add(array_type_name)
  1121. elif type_name.startswith("typeddictionary::"):
  1122. fully_used_classes.add("TypedDictionary")
  1123. dict_type_name = type_name.replace("typeddictionary::", "")
  1124. if dict_type_name.startswith("const "):
  1125. dict_type_name = dict_type_name[6:]
  1126. dict_type_names = dict_type_name.split(";")
  1127. dict_type_name = dict_type_names[0]
  1128. if dict_type_name.endswith("*"):
  1129. dict_type_name = dict_type_name[:-1]
  1130. if is_included(dict_type_name, class_name):
  1131. if is_enum(dict_type_name):
  1132. fully_used_classes.add(get_enum_class(dict_type_name))
  1133. elif "default_value" in argument:
  1134. fully_used_classes.add(dict_type_name)
  1135. else:
  1136. used_classes.add(dict_type_name)
  1137. dict_type_name = dict_type_names[1]
  1138. if dict_type_name.endswith("*"):
  1139. dict_type_name = dict_type_name[:-1]
  1140. if is_included(dict_type_name, class_name):
  1141. if is_enum(dict_type_name):
  1142. fully_used_classes.add(get_enum_class(dict_type_name))
  1143. elif "default_value" in argument:
  1144. fully_used_classes.add(dict_type_name)
  1145. else:
  1146. used_classes.add(dict_type_name)
  1147. elif is_enum(type_name):
  1148. fully_used_classes.add(get_enum_class(type_name))
  1149. elif "default_value" in argument:
  1150. fully_used_classes.add(type_name)
  1151. else:
  1152. used_classes.add(type_name)
  1153. if is_refcounted(type_name):
  1154. fully_used_classes.add("Ref")
  1155. if "return_value" in method:
  1156. type_name = method["return_value"]["type"]
  1157. if type_name.startswith("const "):
  1158. type_name = type_name[6:]
  1159. if type_name.endswith("*"):
  1160. type_name = type_name[:-1]
  1161. if is_included(type_name, class_name):
  1162. if type_name.startswith("typedarray::"):
  1163. fully_used_classes.add("TypedArray")
  1164. array_type_name = type_name.replace("typedarray::", "")
  1165. if array_type_name.startswith("const "):
  1166. array_type_name = array_type_name[6:]
  1167. if array_type_name.endswith("*"):
  1168. array_type_name = array_type_name[:-1]
  1169. if is_included(array_type_name, class_name):
  1170. if is_enum(array_type_name):
  1171. fully_used_classes.add(get_enum_class(array_type_name))
  1172. elif is_variant(array_type_name):
  1173. fully_used_classes.add(array_type_name)
  1174. else:
  1175. used_classes.add(array_type_name)
  1176. elif type_name.startswith("typeddictionary::"):
  1177. fully_used_classes.add("TypedDictionary")
  1178. dict_type_name = type_name.replace("typeddictionary::", "")
  1179. if dict_type_name.startswith("const "):
  1180. dict_type_name = dict_type_name[6:]
  1181. dict_type_names = dict_type_name.split(";")
  1182. dict_type_name = dict_type_names[0]
  1183. if dict_type_name.endswith("*"):
  1184. dict_type_name = dict_type_name[:-1]
  1185. if is_included(dict_type_name, class_name):
  1186. if is_enum(dict_type_name):
  1187. fully_used_classes.add(get_enum_class(dict_type_name))
  1188. elif is_variant(dict_type_name):
  1189. fully_used_classes.add(dict_type_name)
  1190. else:
  1191. used_classes.add(dict_type_name)
  1192. dict_type_name = dict_type_names[1]
  1193. if dict_type_name.endswith("*"):
  1194. dict_type_name = dict_type_name[:-1]
  1195. if is_included(dict_type_name, class_name):
  1196. if is_enum(dict_type_name):
  1197. fully_used_classes.add(get_enum_class(dict_type_name))
  1198. elif is_variant(dict_type_name):
  1199. fully_used_classes.add(dict_type_name)
  1200. else:
  1201. used_classes.add(dict_type_name)
  1202. elif is_enum(type_name):
  1203. fully_used_classes.add(get_enum_class(type_name))
  1204. elif is_variant(type_name):
  1205. fully_used_classes.add(type_name)
  1206. else:
  1207. used_classes.add(type_name)
  1208. if is_refcounted(type_name):
  1209. fully_used_classes.add("Ref")
  1210. if "members" in class_api:
  1211. for member in class_api["members"]:
  1212. if is_included(member["type"], class_name):
  1213. if is_enum(member["type"]):
  1214. fully_used_classes.add(get_enum_class(member["type"]))
  1215. else:
  1216. used_classes.add(member["type"])
  1217. if is_refcounted(member["type"]):
  1218. fully_used_classes.add("Ref")
  1219. if "inherits" in class_api:
  1220. if is_included(class_api["inherits"], class_name):
  1221. fully_used_classes.add(class_api["inherits"])
  1222. if is_refcounted(class_api["name"]):
  1223. fully_used_classes.add("Ref")
  1224. else:
  1225. fully_used_classes.add("Wrapped")
  1226. # In order to ensure that PtrToArg specializations for native structs are
  1227. # always used, let's move any of them into 'fully_used_classes'.
  1228. for type_name in used_classes:
  1229. if is_struct_type(type_name) and not is_included_struct_type(type_name):
  1230. fully_used_classes.add(type_name)
  1231. for type_name in fully_used_classes:
  1232. if type_name in used_classes:
  1233. used_classes.remove(type_name)
  1234. used_classes = list(used_classes)
  1235. used_classes.sort()
  1236. fully_used_classes = list(fully_used_classes)
  1237. fully_used_classes.sort()
  1238. with header_filename.open("w+", encoding="utf-8") as header_file:
  1239. header_file.write(
  1240. generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
  1241. )
  1242. with source_filename.open("w+", encoding="utf-8") as source_file:
  1243. source_file.write(
  1244. generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
  1245. )
  1246. for native_struct in api["native_structures"]:
  1247. struct_name = native_struct["name"]
  1248. if struct_name == "ObjectID":
  1249. continue
  1250. snake_struct_name = camel_to_snake(struct_name)
  1251. header_filename = include_gen_folder / (snake_struct_name + ".hpp")
  1252. result = []
  1253. add_header(f"{snake_struct_name}.hpp", result)
  1254. result.append("#pragma once")
  1255. used_classes = []
  1256. expanded_format = native_struct["format"].replace("(", " ").replace(")", ";").replace(",", ";")
  1257. for field in expanded_format.split(";"):
  1258. field_type = field.strip().split(" ")[0].split("::")[0]
  1259. if field_type != "" and not is_included_type(field_type) and not is_pod_type(field_type):
  1260. if field_type not in used_classes:
  1261. used_classes.append(field_type)
  1262. result.append("")
  1263. if len(used_classes) > 0:
  1264. includes = []
  1265. for included in used_classes:
  1266. includes.append(f"godot_cpp/{get_include_path(included)}")
  1267. includes.sort()
  1268. for include in includes:
  1269. result.append(f"#include <{include}>")
  1270. else:
  1271. result.append("#include <godot_cpp/core/method_ptrcall.hpp>")
  1272. result.append("")
  1273. result.append("namespace godot {")
  1274. result.append("")
  1275. result.append(f"struct {struct_name} {{")
  1276. for field in native_struct["format"].split(";"):
  1277. if field != "":
  1278. result.append(f"\t{field};")
  1279. result.append("};")
  1280. result.append("")
  1281. result.append(f"GDVIRTUAL_NATIVE_PTR({struct_name});")
  1282. result.append("")
  1283. result.append("} // namespace godot")
  1284. result.append("")
  1285. with header_filename.open("w+", encoding="utf-8") as header_file:
  1286. header_file.write("\n".join(result))
  1287. def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
  1288. global singletons
  1289. result = []
  1290. class_name = class_api["name"]
  1291. snake_class_name = camel_to_snake(class_name).upper()
  1292. is_singleton = class_name in singletons
  1293. add_header(f"{snake_class_name.lower()}.hpp", result)
  1294. result.append("#pragma once")
  1295. result.append("")
  1296. if len(fully_used_classes) > 0:
  1297. includes = []
  1298. for included in fully_used_classes:
  1299. if included == "TypedArray":
  1300. includes.append("godot_cpp/variant/typed_array.hpp")
  1301. elif included == "TypedDictionary":
  1302. includes.append("godot_cpp/variant/typed_dictionary.hpp")
  1303. else:
  1304. includes.append(f"godot_cpp/{get_include_path(included)}")
  1305. includes.sort()
  1306. for include in includes:
  1307. result.append(f"#include <{include}>")
  1308. result.append("")
  1309. if class_name == "EditorPlugin":
  1310. result.append("#include <godot_cpp/classes/editor_plugin_registration.hpp>")
  1311. result.append("")
  1312. if class_name != "Object" and class_name != "ClassDBSingleton":
  1313. result.append("#include <godot_cpp/core/class_db.hpp>")
  1314. result.append("")
  1315. result.append("#include <type_traits>")
  1316. result.append("")
  1317. if class_name == "ClassDBSingleton":
  1318. result.append("#include <godot_cpp/core/binder_common.hpp>")
  1319. result.append("")
  1320. result.append("namespace godot {")
  1321. result.append("")
  1322. for type_name in used_classes:
  1323. if is_struct_type(type_name):
  1324. result.append(f"struct {type_name};")
  1325. else:
  1326. result.append(f"class {type_name};")
  1327. if len(used_classes) > 0:
  1328. result.append("")
  1329. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  1330. result.append(f"class {class_name} : public {inherits} {{")
  1331. if "alias_for" in class_api:
  1332. result.append(f"\tGDEXTENSION_CLASS_ALIAS({class_name}, {class_api['alias_for']}, {inherits})")
  1333. else:
  1334. result.append(f"\tGDEXTENSION_CLASS({class_name}, {inherits})")
  1335. result.append("")
  1336. if is_singleton:
  1337. result.append(f"\tstatic {class_name} *singleton;")
  1338. result.append("")
  1339. result.append("public:")
  1340. if "enums" in class_api:
  1341. for enum_api in class_api["enums"]:
  1342. if enum_api["is_bitfield"]:
  1343. result.append(f"\tenum {enum_api['name']} : uint64_t {{")
  1344. else:
  1345. result.append(f"\tenum {enum_api['name']} {{")
  1346. for value in enum_api["values"]:
  1347. result.append(f"\t\t{value['name']} = {value['value']},")
  1348. result.append("\t};")
  1349. result.append("")
  1350. if "constants" in class_api:
  1351. for value in class_api["constants"]:
  1352. if "type" not in value:
  1353. value["type"] = "int"
  1354. result.append(f"\tstatic const {value['type']} {value['name']} = {value['value']};")
  1355. result.append("")
  1356. if is_singleton:
  1357. result.append(f"\tstatic {class_name} *get_singleton();")
  1358. result.append("")
  1359. if "methods" in class_api:
  1360. for method in class_api["methods"]:
  1361. if method["is_virtual"]:
  1362. # Will be done later.
  1363. continue
  1364. vararg = "is_vararg" in method and method["is_vararg"]
  1365. if vararg:
  1366. result.append("")
  1367. result.append("private:")
  1368. method_signature = "\t"
  1369. method_signature += make_signature(
  1370. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  1371. )
  1372. result.append(method_signature + ";")
  1373. if vararg:
  1374. result.append("")
  1375. result.append("public:")
  1376. # Add templated version.
  1377. result += make_varargs_template(method)
  1378. # Virtuals now.
  1379. for method in class_api["methods"]:
  1380. if not method["is_virtual"]:
  1381. continue
  1382. method_signature = "\t"
  1383. method_signature += make_signature(
  1384. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  1385. )
  1386. result.append(method_signature + ";")
  1387. result.append("")
  1388. result.append("protected:")
  1389. # T is the custom class we want to register (from which the call initiates, going up the inheritance chain),
  1390. # B is its base class (can be a custom class too, that's why we pass it).
  1391. result.append("\ttemplate <typename T, typename B>")
  1392. result.append("\tstatic void register_virtuals() {")
  1393. if class_name != "Object":
  1394. result.append(f"\t\t{inherits}::register_virtuals<T, B>();")
  1395. if "methods" in class_api:
  1396. for method in class_api["methods"]:
  1397. if not method["is_virtual"]:
  1398. continue
  1399. method_name = escape_identifier(method["name"])
  1400. result.append(
  1401. # If the method is different from the base class, it means T overrides it, so it needs to be bound.
  1402. # Note that with an `if constexpr`, the code inside the `if` will not even be compiled if the
  1403. # condition returns false (in such cases it can't compile due to ambiguity).
  1404. f"\t\tif constexpr (!std::is_same_v<decltype(&B::{method_name}), decltype(&T::{method_name})>) {{"
  1405. )
  1406. result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name}, {method['hash']});")
  1407. result.append("\t\t}")
  1408. result.append("\t}")
  1409. result.append("")
  1410. if is_singleton:
  1411. result.append(f"\t~{class_name}();")
  1412. result.append("")
  1413. if class_name == "Object":
  1414. result.append('\tString _to_string() const { return "<" + get_class() + "#" + itos(get_instance_id()) + ">"; }')
  1415. result.append("")
  1416. if class_name == "Node":
  1417. result.append(
  1418. '\tString _to_string() const { return (!get_name().is_empty() ? String(get_name()) + ":" : "") + Object::_to_string(); }'
  1419. )
  1420. result.append("")
  1421. result.append("public:")
  1422. # Special cases.
  1423. if class_name == "XMLParser":
  1424. result.append("\tError _open_buffer(const uint8_t *p_buffer, size_t p_size);")
  1425. if class_name == "Image":
  1426. result.append("\tuint8_t *ptrw();")
  1427. result.append("\tconst uint8_t *ptr();")
  1428. if class_name == "FileAccess":
  1429. result.append("\tuint64_t get_buffer(uint8_t *p_dst, uint64_t p_length) const;")
  1430. result.append("\tvoid store_buffer(const uint8_t *p_src, uint64_t p_length);")
  1431. if class_name == "WorkerThreadPool":
  1432. result.append("\tenum {")
  1433. result.append("\t\tINVALID_TASK_ID = -1")
  1434. result.append("\t};")
  1435. result.append("\ttypedef int64_t TaskID;")
  1436. result.append("\ttypedef int64_t GroupID;")
  1437. result.append(
  1438. "\tTaskID add_native_task(void (*p_func)(void *), void *p_userdata, bool p_high_priority = false, const String &p_description = String());"
  1439. )
  1440. result.append(
  1441. "\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());"
  1442. )
  1443. if class_name == "Object":
  1444. result.append("\ttemplate <typename T>")
  1445. result.append("\tstatic T *cast_to(Object *p_object);")
  1446. result.append("\ttemplate <typename T>")
  1447. result.append("\tstatic const T *cast_to(const Object *p_object);")
  1448. result.append("\tvirtual ~Object() = default;")
  1449. elif use_template_get_node and class_name == "Node":
  1450. result.append("\ttemplate <typename T>")
  1451. result.append(
  1452. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  1453. )
  1454. result.append("};")
  1455. result.append("")
  1456. result.append("} // namespace godot")
  1457. result.append("")
  1458. if "enums" in class_api and class_name != "Object":
  1459. for enum_api in class_api["enums"]:
  1460. if enum_api["is_bitfield"]:
  1461. result.append(f"VARIANT_BITFIELD_CAST({class_name}::{enum_api['name']});")
  1462. else:
  1463. result.append(f"VARIANT_ENUM_CAST({class_name}::{enum_api['name']});")
  1464. result.append("")
  1465. if class_name == "ClassDBSingleton":
  1466. result.append("#define CLASSDB_SINGLETON_FORWARD_METHODS \\")
  1467. if "enums" in class_api:
  1468. for enum_api in class_api["enums"]:
  1469. if enum_api["is_bitfield"]:
  1470. result.append(f"\tenum {enum_api['name']} : uint64_t {{ \\")
  1471. else:
  1472. result.append(f"\tenum {enum_api['name']} {{ \\")
  1473. for value in enum_api["values"]:
  1474. result.append(f"\t\t{value['name']} = {value['value']}, \\")
  1475. result.append("\t}; \\")
  1476. result.append("\t \\")
  1477. for method in class_api["methods"]:
  1478. # ClassDBSingleton shouldn't have any static methods, but if some appear later, lets skip them.
  1479. if "is_static" in method and method["is_static"]:
  1480. continue
  1481. vararg = "is_vararg" in method and method["is_vararg"]
  1482. if vararg:
  1483. method_signature = "\ttemplate <typename... Args> static "
  1484. else:
  1485. method_signature = "\tstatic "
  1486. return_type = None
  1487. if "return_type" in method:
  1488. return_type = correct_type(method["return_type"].replace("ClassDBSingleton", "ClassDB"), None, False)
  1489. elif "return_value" in method:
  1490. return_type = correct_type(
  1491. method["return_value"]["type"].replace("ClassDBSingleton", "ClassDB"),
  1492. method["return_value"].get("meta", None),
  1493. False,
  1494. )
  1495. if return_type is not None:
  1496. method_signature += return_type
  1497. if not method_signature.endswith("*"):
  1498. method_signature += " "
  1499. else:
  1500. method_signature += "void "
  1501. method_signature += f"{method['name']}("
  1502. method_arguments = []
  1503. if "arguments" in method:
  1504. method_arguments = method["arguments"]
  1505. method_signature += make_function_parameters(
  1506. method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
  1507. )
  1508. method_signature += ") { \\"
  1509. result.append(method_signature)
  1510. method_body = "\t\t"
  1511. if return_type is not None:
  1512. method_body += "return "
  1513. if "alias_for" in class_api and return_type.startswith(class_api["alias_for"] + "::"):
  1514. method_body += f"({return_type})"
  1515. method_body += f"ClassDBSingleton::get_singleton()->{method['name']}("
  1516. method_body += ", ".join(map(lambda x: escape_argument(x["name"]), method_arguments))
  1517. if vararg:
  1518. method_body += ", p_args..."
  1519. method_body += "); \\"
  1520. result.append(method_body)
  1521. result.append("\t} \\")
  1522. result.append("\t")
  1523. result.append("")
  1524. result.append("#define CLASSDB_SINGLETON_VARIANT_CAST \\")
  1525. if "enums" in class_api:
  1526. for enum_api in class_api["enums"]:
  1527. if enum_api["is_bitfield"]:
  1528. result.append(f"\tVARIANT_BITFIELD_CAST({class_api['alias_for']}::{enum_api['name']}); \\")
  1529. else:
  1530. result.append(f"\tVARIANT_ENUM_CAST({class_api['alias_for']}::{enum_api['name']}); \\")
  1531. result.append("\t")
  1532. result.append("")
  1533. result.append("")
  1534. return "\n".join(result)
  1535. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  1536. global singletons
  1537. result = []
  1538. class_name = class_api["name"]
  1539. snake_class_name = camel_to_snake(class_name)
  1540. is_singleton = class_name in singletons
  1541. add_header(f"{snake_class_name}.cpp", result)
  1542. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  1543. result.append("")
  1544. result.append("#include <godot_cpp/core/class_db.hpp>")
  1545. result.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1546. result.append("#include <godot_cpp/core/error_macros.hpp>")
  1547. result.append("")
  1548. if len(used_classes) > 0:
  1549. includes = []
  1550. for included in used_classes:
  1551. includes.append(f"godot_cpp/{get_include_path(included)}")
  1552. includes.sort()
  1553. for included in includes:
  1554. result.append(f"#include <{included}>")
  1555. result.append("")
  1556. result.append("namespace godot {")
  1557. result.append("")
  1558. if is_singleton:
  1559. result.append(f"{class_name} *{class_name}::singleton = nullptr;")
  1560. result.append("")
  1561. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  1562. # We assume multi-threaded access is OK because each assignment will assign the same value every time
  1563. result.append("\tif (unlikely(singleton == nullptr)) {")
  1564. result.append(
  1565. f"\t\tGDExtensionObjectPtr singleton_obj = internal::gdextension_interface_global_get_singleton({class_name}::get_class_static()._native_ptr());"
  1566. )
  1567. result.append("#ifdef DEBUG_ENABLED")
  1568. result.append("\t\tERR_FAIL_NULL_V(singleton_obj, nullptr);")
  1569. result.append("#endif // DEBUG_ENABLED")
  1570. result.append(
  1571. f"\t\tsingleton = reinterpret_cast<{class_name} *>(internal::gdextension_interface_object_get_instance_binding(singleton_obj, internal::token, &{class_name}::_gde_binding_callbacks));"
  1572. )
  1573. result.append("#ifdef DEBUG_ENABLED")
  1574. result.append("\t\tERR_FAIL_NULL_V(singleton, nullptr);")
  1575. result.append("#endif // DEBUG_ENABLED")
  1576. result.append("\t\tif (likely(singleton)) {")
  1577. result.append(f"\t\t\tClassDB::_register_engine_singleton({class_name}::get_class_static(), singleton);")
  1578. result.append("\t\t}")
  1579. result.append("\t}")
  1580. result.append("\treturn singleton;")
  1581. result.append("}")
  1582. result.append("")
  1583. result.append(f"{class_name}::~{class_name}() {{")
  1584. result.append("\tif (singleton == this) {")
  1585. result.append(f"\t\tClassDB::_unregister_engine_singleton({class_name}::get_class_static());")
  1586. result.append("\t\tsingleton = nullptr;")
  1587. result.append("\t}")
  1588. result.append("}")
  1589. result.append("")
  1590. if "methods" in class_api:
  1591. for method in class_api["methods"]:
  1592. if method["is_virtual"]:
  1593. # Will be done later
  1594. continue
  1595. vararg = "is_vararg" in method and method["is_vararg"]
  1596. # Method signature.
  1597. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1598. result.append(method_signature + " {")
  1599. # Method body.
  1600. result.append(
  1601. 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"]});'
  1602. )
  1603. method_call = "\t"
  1604. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  1605. if has_return:
  1606. result.append(
  1607. f"\tCHECK_METHOD_BIND_RET(_gde_method_bind, ({get_default_value_for_type(method['return_value']['type'])}));"
  1608. )
  1609. else:
  1610. result.append("\tCHECK_METHOD_BIND(_gde_method_bind);")
  1611. is_ref = False
  1612. if not vararg:
  1613. if has_return:
  1614. return_type = method["return_value"]["type"]
  1615. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  1616. if is_enum(return_type):
  1617. if method["is_static"]:
  1618. method_call += f"return ({get_gdextension_type(correct_type(return_type, meta_type))})internal::_call_native_mb_ret<int64_t>(_gde_method_bind, nullptr"
  1619. else:
  1620. method_call += f"return ({get_gdextension_type(correct_type(return_type, meta_type))})internal::_call_native_mb_ret<int64_t>(_gde_method_bind, _owner"
  1621. elif is_pod_type(return_type) or is_variant(return_type):
  1622. if method["is_static"]:
  1623. method_call += f"return internal::_call_native_mb_ret<{get_gdextension_type(correct_type(return_type, meta_type))}>(_gde_method_bind, nullptr"
  1624. else:
  1625. method_call += f"return internal::_call_native_mb_ret<{get_gdextension_type(correct_type(return_type, meta_type))}>(_gde_method_bind, _owner"
  1626. elif is_refcounted(return_type):
  1627. if method["is_static"]:
  1628. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, nullptr"
  1629. else:
  1630. method_call += f"return Ref<{return_type}>::_gde_internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, _owner"
  1631. is_ref = True
  1632. else:
  1633. if method["is_static"]:
  1634. method_call += (
  1635. f"return internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, nullptr"
  1636. )
  1637. else:
  1638. method_call += (
  1639. f"return internal::_call_native_mb_ret_obj<{return_type}>(_gde_method_bind, _owner"
  1640. )
  1641. else:
  1642. if method["is_static"]:
  1643. method_call += "internal::_call_native_mb_no_ret(_gde_method_bind, nullptr"
  1644. else:
  1645. method_call += "internal::_call_native_mb_no_ret(_gde_method_bind, _owner"
  1646. if "arguments" in method:
  1647. method_call += ", "
  1648. arguments = []
  1649. for argument in method["arguments"]:
  1650. (encode, arg_name) = get_encoded_arg(
  1651. argument["name"],
  1652. argument["type"],
  1653. argument["meta"] if "meta" in argument else None,
  1654. )
  1655. result += encode
  1656. arguments.append(arg_name)
  1657. method_call += ", ".join(arguments)
  1658. else: # vararg.
  1659. result.append("\tGDExtensionCallError error;")
  1660. result.append("\tVariant ret;")
  1661. method_call += "internal::gdextension_interface_object_method_bind_call(_gde_method_bind, _owner, reinterpret_cast<GDExtensionConstVariantPtr *>(p_args), p_arg_count, &ret, &error"
  1662. if is_ref:
  1663. method_call += ")" # Close Ref<> constructor.
  1664. method_call += ");"
  1665. result.append(method_call)
  1666. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  1667. return_type = get_enum_fullname(method["return_value"]["type"])
  1668. if return_type != "Variant":
  1669. result.append(f"\treturn VariantCaster<{return_type}>::cast(ret);")
  1670. else:
  1671. result.append("\treturn ret;")
  1672. result.append("}")
  1673. result.append("")
  1674. # Virtuals now.
  1675. for method in class_api["methods"]:
  1676. if not method["is_virtual"]:
  1677. continue
  1678. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  1679. method_signature += " {"
  1680. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  1681. result.append(method_signature)
  1682. result.append(f"\treturn {get_default_value_for_type(method['return_value']['type'])};")
  1683. result.append("}")
  1684. else:
  1685. method_signature += "}"
  1686. result.append(method_signature)
  1687. result.append("")
  1688. result.append("} // namespace godot")
  1689. result.append("")
  1690. return "\n".join(result)
  1691. def generate_global_constants(api, output_dir):
  1692. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1693. source_gen_folder = Path(output_dir) / "src" / "classes"
  1694. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1695. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1696. # Generate header
  1697. header = []
  1698. add_header("global_constants.hpp", header)
  1699. header_filename = include_gen_folder / "global_constants.hpp"
  1700. header.append("#pragma once")
  1701. header.append("")
  1702. header.append("#include <cstdint>")
  1703. header.append("")
  1704. header.append("namespace godot {")
  1705. header.append("")
  1706. if len(api["global_constants"]) > 0:
  1707. for constant in api["global_constants"]:
  1708. header.append(f"const int64_t {escape_identifier(constant['name'])} = {constant['value']};")
  1709. header.append("")
  1710. for enum_def in api["global_enums"]:
  1711. if enum_def["name"].startswith("Variant."):
  1712. continue
  1713. if enum_def["is_bitfield"]:
  1714. header.append(f"enum {enum_def['name']} : uint64_t {{")
  1715. else:
  1716. header.append(f"enum {enum_def['name']} {{")
  1717. for value in enum_def["values"]:
  1718. header.append(f"\t{value['name']} = {value['value']},")
  1719. header.append("};")
  1720. header.append("")
  1721. header.append("} // namespace godot")
  1722. header.append("")
  1723. with header_filename.open("w+", encoding="utf-8") as header_file:
  1724. header_file.write("\n".join(header))
  1725. def generate_version_header(api, output_dir):
  1726. header = []
  1727. header_filename = "version.hpp"
  1728. add_header(header_filename, header)
  1729. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "core"
  1730. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1731. header_file_path = include_gen_folder / header_filename
  1732. header.append("#pragma once")
  1733. header.append("")
  1734. header.append(f"#define GODOT_VERSION_MAJOR {api['header']['version_major']}")
  1735. header.append(f"#define GODOT_VERSION_MINOR {api['header']['version_minor']}")
  1736. header.append(f"#define GODOT_VERSION_PATCH {api['header']['version_patch']}")
  1737. header.append(f'#define GODOT_VERSION_STATUS "{api["header"]["version_status"]}"')
  1738. header.append(f'#define GODOT_VERSION_BUILD "{api["header"]["version_build"]}"')
  1739. header.append("")
  1740. with header_file_path.open("w+", encoding="utf-8") as header_file:
  1741. header_file.write("\n".join(header))
  1742. def generate_global_constant_binds(api, output_dir):
  1743. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  1744. source_gen_folder = Path(output_dir) / "src" / "classes"
  1745. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1746. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1747. # Generate header
  1748. header = []
  1749. add_header("global_constants_binds.hpp", header)
  1750. header_filename = include_gen_folder / "global_constants_binds.hpp"
  1751. header.append("#pragma once")
  1752. header.append("")
  1753. header.append("#include <godot_cpp/classes/global_constants.hpp>")
  1754. header.append("")
  1755. for enum_def in api["global_enums"]:
  1756. if enum_def["name"].startswith("Variant."):
  1757. continue
  1758. if enum_def["is_bitfield"]:
  1759. header.append(f"VARIANT_BITFIELD_CAST({enum_def['name']});")
  1760. else:
  1761. header.append(f"VARIANT_ENUM_CAST({enum_def['name']});")
  1762. # Variant::Type is not a global enum, but only one line, it is worth to place in this file instead of creating new file.
  1763. header.append("VARIANT_ENUM_CAST(godot::Variant::Type);")
  1764. header.append("")
  1765. with header_filename.open("w+", encoding="utf-8") as header_file:
  1766. header_file.write("\n".join(header))
  1767. def generate_utility_functions(api, output_dir):
  1768. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  1769. source_gen_folder = Path(output_dir) / "src" / "variant"
  1770. include_gen_folder.mkdir(parents=True, exist_ok=True)
  1771. source_gen_folder.mkdir(parents=True, exist_ok=True)
  1772. # Generate header.
  1773. header = []
  1774. add_header("utility_functions.hpp", header)
  1775. header_filename = include_gen_folder / "utility_functions.hpp"
  1776. header.append("#pragma once")
  1777. header.append("")
  1778. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  1779. header.append("#include <godot_cpp/variant/variant.hpp>")
  1780. header.append("")
  1781. header.append("#include <array>")
  1782. header.append("")
  1783. header.append("namespace godot {")
  1784. header.append("")
  1785. header.append("class UtilityFunctions {")
  1786. header.append("public:")
  1787. for function in api["utility_functions"]:
  1788. if function["name"] == "is_instance_valid":
  1789. # The `is_instance_valid()` function doesn't work as developers expect, and unless used very
  1790. # carefully will cause crashes. Instead, developers should use `ObjectDB::get_instance()`
  1791. # with object ids to ensure that an instance is still valid.
  1792. continue
  1793. vararg = "is_vararg" in function and function["is_vararg"]
  1794. if vararg:
  1795. header.append("")
  1796. header.append("private:")
  1797. function_signature = "\t"
  1798. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  1799. header.append(function_signature + ";")
  1800. if vararg:
  1801. header.append("")
  1802. header.append("public:")
  1803. # Add templated version.
  1804. header += make_varargs_template(function, static=True)
  1805. header.append("};")
  1806. header.append("")
  1807. header.append("} // namespace godot")
  1808. header.append("")
  1809. with header_filename.open("w+", encoding="utf-8") as header_file:
  1810. header_file.write("\n".join(header))
  1811. # Generate source.
  1812. source = []
  1813. add_header("utility_functions.cpp", source)
  1814. source_filename = source_gen_folder / "utility_functions.cpp"
  1815. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  1816. source.append("")
  1817. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1818. source.append("#include <godot_cpp/core/error_macros.hpp>")
  1819. source.append("")
  1820. source.append("namespace godot {")
  1821. source.append("")
  1822. for function in api["utility_functions"]:
  1823. if function["name"] == "is_instance_valid":
  1824. continue
  1825. vararg = "is_vararg" in function and function["is_vararg"]
  1826. function_signature = make_signature("UtilityFunctions", function)
  1827. source.append(function_signature + " {")
  1828. # Function body.
  1829. source.append(
  1830. f'\tstatic GDExtensionPtrUtilityFunction _gde_function = internal::gdextension_interface_variant_get_ptr_utility_function(StringName("{function["name"]}")._native_ptr(), {function["hash"]});'
  1831. )
  1832. has_return = "return_type" in function and function["return_type"] != "void"
  1833. if has_return:
  1834. source.append(
  1835. f"\tCHECK_METHOD_BIND_RET(_gde_function, ({get_default_value_for_type(function['return_type'])}));"
  1836. )
  1837. else:
  1838. source.append("\tCHECK_METHOD_BIND(_gde_function);")
  1839. function_call = "\t"
  1840. if not vararg:
  1841. if has_return:
  1842. function_call += "return "
  1843. if function["return_type"] == "Object":
  1844. function_call += "internal::_call_utility_ret_obj(_gde_function"
  1845. else:
  1846. function_call += f"internal::_call_utility_ret<{get_gdextension_type(correct_type(function['return_type']))}>(_gde_function"
  1847. else:
  1848. function_call += "internal::_call_utility_no_ret(_gde_function"
  1849. if "arguments" in function:
  1850. function_call += ", "
  1851. arguments = []
  1852. for argument in function["arguments"]:
  1853. (encode, arg_name) = get_encoded_arg(
  1854. argument["name"],
  1855. argument["type"],
  1856. argument["meta"] if "meta" in argument else None,
  1857. )
  1858. source += encode
  1859. arguments.append(arg_name)
  1860. function_call += ", ".join(arguments)
  1861. else:
  1862. if has_return:
  1863. source.append(f"\t{get_gdextension_type(correct_type(function['return_type']))} ret;")
  1864. else:
  1865. source.append("\tVariant ret;")
  1866. function_call += "_gde_function(&ret, reinterpret_cast<GDExtensionConstVariantPtr *>(p_args), p_arg_count"
  1867. function_call += ");"
  1868. source.append(function_call)
  1869. if vararg and has_return:
  1870. source.append("\treturn ret;")
  1871. source.append("}")
  1872. source.append("")
  1873. source.append("} // namespace godot")
  1874. with source_filename.open("w+", encoding="utf-8") as source_file:
  1875. source_file.write("\n".join(source))
  1876. # Helper functions.
  1877. def camel_to_snake(name):
  1878. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1879. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1880. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1881. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1882. signature = []
  1883. for index, par in enumerate(parameters):
  1884. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1885. parameter_name = escape_argument(par["name"])
  1886. if len(parameter_name) == 0:
  1887. parameter_name = "p_arg_" + str(index + 1)
  1888. parameter += parameter_name
  1889. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1890. parameter += " = "
  1891. if is_enum(par["type"]):
  1892. parameter_type = correct_type(par["type"])
  1893. if parameter_type == "void":
  1894. parameter_type = "Variant"
  1895. parameter += f"({parameter_type})"
  1896. parameter += correct_default_value(par["default_value"], par["type"])
  1897. signature.append(parameter)
  1898. if is_vararg:
  1899. signature.append("const Args &...p_args")
  1900. return ", ".join(signature)
  1901. def type_for_parameter(type_name, meta=None):
  1902. if type_name == "void":
  1903. return "Variant "
  1904. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1905. return f"{correct_type(type_name, meta)} "
  1906. elif is_variant(type_name) or is_refcounted(type_name):
  1907. return f"const {correct_type(type_name)} &"
  1908. else:
  1909. return f"{correct_type(type_name)}"
  1910. def get_include_path(type_name):
  1911. base_dir = ""
  1912. if type_name == "Object":
  1913. base_dir = "core"
  1914. elif is_variant(type_name):
  1915. base_dir = "variant"
  1916. else:
  1917. base_dir = "classes"
  1918. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1919. def get_encoded_arg(arg_name, type_name, type_meta):
  1920. result = []
  1921. name = escape_argument(arg_name)
  1922. arg_type = correct_type(type_name)
  1923. if is_pod_type(arg_type):
  1924. result.append(f"\t{get_gdextension_type(arg_type)} {name}_encoded;")
  1925. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1926. name = f"&{name}_encoded"
  1927. elif is_enum(type_name) and not is_bitfield(type_name):
  1928. result.append(f"\tint64_t {name}_encoded;")
  1929. result.append(f"\tPtrToArg<int64_t>::encode({name}, &{name}_encoded);")
  1930. name = f"&{name}_encoded"
  1931. elif is_engine_class(type_name):
  1932. # `{name}` is a C++ wrapper, it contains a field which is the object's pointer Godot expects.
  1933. # We have to check `nullptr` because when the caller sends `nullptr`, the wrapper itself will be null.
  1934. name = f"({name} != nullptr ? &{name}->_owner : nullptr)"
  1935. else:
  1936. name = f"&{name}"
  1937. return (result, name)
  1938. def make_signature(
  1939. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1940. ):
  1941. function_signature = ""
  1942. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1943. if for_header:
  1944. if "is_virtual" in function_data and function_data["is_virtual"]:
  1945. function_signature += "virtual "
  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 not for_header:
  1962. function_signature += f"{class_name}::"
  1963. function_signature += escape_identifier(function_data["name"])
  1964. if is_vararg or (
  1965. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1966. ):
  1967. function_signature += "_internal"
  1968. function_signature += "("
  1969. arguments = function_data["arguments"] if "arguments" in function_data else []
  1970. if not is_vararg:
  1971. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1972. else:
  1973. function_signature += "const Variant **p_args, GDExtensionInt p_arg_count"
  1974. function_signature += ")"
  1975. if "is_static" in function_data and function_data["is_static"] and for_header:
  1976. function_signature = "static " + function_signature
  1977. elif "is_const" in function_data and function_data["is_const"]:
  1978. function_signature += " const"
  1979. return function_signature
  1980. def make_varargs_template(
  1981. function_data,
  1982. static=False,
  1983. class_befor_signature="",
  1984. with_indent=True,
  1985. for_builtin_classes=False,
  1986. ):
  1987. result = []
  1988. function_signature = ""
  1989. result.append("template <typename... Args>")
  1990. if static:
  1991. function_signature += "static "
  1992. return_type = "void"
  1993. return_meta = None
  1994. if "return_type" in function_data:
  1995. return_type = correct_type(function_data["return_type"])
  1996. elif "return_value" in function_data:
  1997. return_type = function_data["return_value"]["type"]
  1998. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1999. function_signature += correct_type(
  2000. return_type,
  2001. return_meta,
  2002. )
  2003. if not function_signature.endswith("*"):
  2004. function_signature += " "
  2005. if len(class_befor_signature) > 0:
  2006. function_signature += class_befor_signature + "::"
  2007. function_signature += f"{escape_identifier(function_data['name'])}"
  2008. method_arguments = []
  2009. if "arguments" in function_data:
  2010. method_arguments = function_data["arguments"]
  2011. function_signature += "("
  2012. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  2013. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  2014. function_signature += ")"
  2015. if "is_const" in function_data and function_data["is_const"]:
  2016. function_signature += " const"
  2017. function_signature += " {"
  2018. result.append(function_signature)
  2019. args_array = f"\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args{{{{ "
  2020. for argument in method_arguments:
  2021. if argument["type"] == "Variant":
  2022. args_array += escape_argument(argument["name"])
  2023. else:
  2024. args_array += f"Variant({escape_argument(argument['name'])})"
  2025. args_array += ", "
  2026. args_array += "Variant(p_args)... }};"
  2027. result.append(args_array)
  2028. result.append(f"\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  2029. result.append("\tfor (size_t i = 0; i < variant_args.size(); i++) {")
  2030. result.append("\t\tcall_args[i] = &variant_args[i];")
  2031. result.append("\t}")
  2032. call_line = "\t"
  2033. if not for_builtin_classes:
  2034. if return_type != "void":
  2035. call_line += "return "
  2036. call_line += f"{escape_identifier(function_data['name'])}_internal(call_args.data(), variant_args.size());"
  2037. result.append(call_line)
  2038. else:
  2039. base = "(GDExtensionTypePtr)&opaque"
  2040. if static:
  2041. base = "nullptr"
  2042. ret = "nullptr"
  2043. if return_type != "void":
  2044. ret = "&ret"
  2045. result.append(f"\t{correct_type(function_data['return_type'])} ret;")
  2046. function_name = function_data["name"]
  2047. result.append(
  2048. f"\t_method_bindings.method_{function_name}({base}, reinterpret_cast<GDExtensionConstTypePtr *>(call_args.data()), {ret}, {len(method_arguments)} + sizeof...(Args));"
  2049. )
  2050. if return_type != "void":
  2051. result.append("\treturn ret;")
  2052. result.append("}")
  2053. if with_indent:
  2054. for i in range(len(result)):
  2055. result[i] = "\t" + result[i]
  2056. return result
  2057. # Engine idiosyncrasies.
  2058. def is_pod_type(type_name):
  2059. """
  2060. Those are types for which no class should be generated.
  2061. """
  2062. return type_name in [
  2063. "Nil",
  2064. "void",
  2065. "bool",
  2066. "real_t",
  2067. "float",
  2068. "double",
  2069. "int",
  2070. "int8_t",
  2071. "uint8_t",
  2072. "int16_t",
  2073. "uint16_t",
  2074. "int32_t",
  2075. "int64_t",
  2076. "uint32_t",
  2077. "uint64_t",
  2078. ]
  2079. def is_included_type(type_name):
  2080. # Types which we already have implemented.
  2081. return is_included_struct_type(type_name) or type_name in ["ObjectID"]
  2082. def is_included_struct_type(type_name):
  2083. # Struct types which we already have implemented.
  2084. return type_name in [
  2085. "AABB",
  2086. "Basis",
  2087. "Color",
  2088. "Plane",
  2089. "Projection",
  2090. "Quaternion",
  2091. "Rect2",
  2092. "Rect2i",
  2093. "Transform2D",
  2094. "Transform3D",
  2095. "Vector2",
  2096. "Vector2i",
  2097. "Vector3",
  2098. "Vector3i",
  2099. "Vector4",
  2100. "Vector4i",
  2101. ]
  2102. def is_packed_array(type_name):
  2103. """
  2104. Those are types for which we add our extra packed array functions.
  2105. """
  2106. return type_name in [
  2107. "PackedByteArray",
  2108. "PackedColorArray",
  2109. "PackedFloat32Array",
  2110. "PackedFloat64Array",
  2111. "PackedInt32Array",
  2112. "PackedInt64Array",
  2113. "PackedStringArray",
  2114. "PackedVector2Array",
  2115. "PackedVector3Array",
  2116. "PackedVector4Array",
  2117. ]
  2118. def needs_copy_instead_of_move(type_name):
  2119. """
  2120. Those are types which need initialized data or we'll get warning spam so need a copy instead of move.
  2121. """
  2122. return type_name in [
  2123. "Dictionary",
  2124. ]
  2125. def is_enum(type_name):
  2126. return type_name.startswith("enum::") or type_name.startswith("bitfield::")
  2127. def is_bitfield(type_name):
  2128. return type_name.startswith("bitfield::")
  2129. def get_enum_class(enum_name: str):
  2130. if "." in enum_name:
  2131. if is_bitfield(enum_name):
  2132. return enum_name.replace("bitfield::", "").split(".")[0]
  2133. else:
  2134. return enum_name.replace("enum::", "").split(".")[0]
  2135. else:
  2136. return "GlobalConstants"
  2137. def get_enum_fullname(enum_name: str):
  2138. if is_bitfield(enum_name):
  2139. return enum_name.replace("bitfield::", "BitField<") + ">"
  2140. else:
  2141. return enum_name.replace("enum::", "")
  2142. def get_enum_name(enum_name: str):
  2143. if is_bitfield(enum_name):
  2144. return enum_name.replace("bitfield::", "").split(".")[-1]
  2145. else:
  2146. return enum_name.replace("enum::", "").split(".")[-1]
  2147. def is_variant(type_name):
  2148. return (
  2149. type_name == "Variant"
  2150. or type_name in builtin_classes
  2151. or type_name == "Nil"
  2152. or type_name.startswith("typedarray::")
  2153. or type_name.startswith("typeddictionary::")
  2154. )
  2155. def is_engine_class(type_name):
  2156. global engine_classes
  2157. return type_name == "Object" or type_name in engine_classes
  2158. def is_struct_type(type_name):
  2159. # This is used to determine which keyword to use for forward declarations.
  2160. global native_structures
  2161. return is_included_struct_type(type_name) or type_name in native_structures
  2162. def is_refcounted(type_name):
  2163. return type_name in engine_classes and engine_classes[type_name]
  2164. def is_included(type_name, current_type):
  2165. """
  2166. Check if a builtin type should be included.
  2167. This removes Variant and POD types from inclusion, and the current type.
  2168. """
  2169. if type_name.startswith("typedarray::"):
  2170. return True
  2171. if type_name.startswith("typeddictionary::"):
  2172. return True
  2173. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  2174. if to_include == current_type or is_pod_type(to_include):
  2175. return False
  2176. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  2177. return True
  2178. return is_engine_class(to_include) or is_variant(to_include)
  2179. def correct_default_value(value, type_name):
  2180. value_map = {
  2181. "null": "nullptr",
  2182. '""': "String()",
  2183. '&""': "StringName()",
  2184. '^""': "NodePath()",
  2185. "[]": "Array()",
  2186. "{}": "Dictionary()",
  2187. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  2188. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  2189. }
  2190. if value in value_map:
  2191. return value_map[value]
  2192. if value == "":
  2193. return f"{type_name}()"
  2194. if value.startswith("Array["):
  2195. return "{}"
  2196. if value.startswith("&"):
  2197. return value[1::]
  2198. if value.startswith("^"):
  2199. return value[1::]
  2200. return value
  2201. def correct_typed_array(type_name):
  2202. if type_name.startswith("typedarray::"):
  2203. return type_name.replace("typedarray::", "TypedArray<") + ">"
  2204. return type_name
  2205. def correct_typed_dictionary(type_name):
  2206. if type_name.startswith("typeddictionary::"):
  2207. return type_name.replace("typeddictionary::", "TypedDictionary<").replace(";", ", ") + ">"
  2208. return type_name
  2209. def correct_type(type_name, meta=None, use_alias=True):
  2210. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  2211. if meta is not None:
  2212. if "int" in meta:
  2213. return f"{meta}_t"
  2214. elif "char" in meta:
  2215. return f"{meta}_t"
  2216. else:
  2217. return meta
  2218. if type_name in type_conversion:
  2219. return type_conversion[type_name]
  2220. if type_name.startswith("typedarray::"):
  2221. arr_type_name = type_name.replace("typedarray::", "")
  2222. if is_refcounted(arr_type_name):
  2223. arr_type_name = "Ref<" + arr_type_name + ">"
  2224. return "TypedArray<" + arr_type_name + ">"
  2225. if type_name.startswith("typeddictionary::"):
  2226. dict_type_name = type_name.replace("typeddictionary::", "")
  2227. dict_type_names = dict_type_name.split(";")
  2228. if is_refcounted(dict_type_names[0]):
  2229. key_name = "Ref<" + dict_type_names[0] + ">"
  2230. else:
  2231. key_name = dict_type_names[0]
  2232. if is_refcounted(dict_type_names[1]):
  2233. val_name = "Ref<" + dict_type_names[1] + ">"
  2234. else:
  2235. val_name = dict_type_names[1]
  2236. return "TypedDictionary<" + key_name + ", " + val_name + ">"
  2237. if is_enum(type_name):
  2238. if is_bitfield(type_name):
  2239. base_class = get_enum_class(type_name)
  2240. if use_alias and base_class in CLASS_ALIASES:
  2241. base_class = CLASS_ALIASES[base_class]
  2242. if base_class == "GlobalConstants":
  2243. return f"BitField<{get_enum_name(type_name)}>"
  2244. return f"BitField<{base_class}::{get_enum_name(type_name)}>"
  2245. else:
  2246. base_class = get_enum_class(type_name)
  2247. if use_alias and base_class in CLASS_ALIASES:
  2248. base_class = CLASS_ALIASES[base_class]
  2249. if base_class == "GlobalConstants":
  2250. return f"{get_enum_name(type_name)}"
  2251. return f"{base_class}::{get_enum_name(type_name)}"
  2252. if is_refcounted(type_name):
  2253. return f"Ref<{type_name}>"
  2254. if type_name == "Object" or is_engine_class(type_name):
  2255. return f"{type_name} *"
  2256. if type_name.endswith("*") and not type_name.endswith("**") and not type_name.endswith(" *"):
  2257. return f"{type_name[:-1]} *"
  2258. return type_name
  2259. def get_gdextension_type(type_name):
  2260. type_conversion_map = {
  2261. "bool": "int8_t",
  2262. "uint8_t": "int64_t",
  2263. "int8_t": "int64_t",
  2264. "uint16_t": "int64_t",
  2265. "int16_t": "int64_t",
  2266. "uint32_t": "int64_t",
  2267. "int32_t": "int64_t",
  2268. "int": "int64_t",
  2269. "float": "double",
  2270. }
  2271. if type_name.startswith("BitField<"):
  2272. return "int64_t"
  2273. if type_name in type_conversion_map:
  2274. return type_conversion_map[type_name]
  2275. return type_name
  2276. def escape_identifier(id):
  2277. cpp_keywords_map = {
  2278. "class": "_class",
  2279. "char": "_char",
  2280. "short": "_short",
  2281. "bool": "_bool",
  2282. "int": "_int",
  2283. "default": "_default",
  2284. "case": "_case",
  2285. "switch": "_switch",
  2286. "export": "_export",
  2287. "template": "_template",
  2288. "new": "new_",
  2289. "operator": "_operator",
  2290. "typeof": "type_of",
  2291. "typename": "type_name",
  2292. "enum": "_enum",
  2293. }
  2294. if id in cpp_keywords_map:
  2295. return cpp_keywords_map[id]
  2296. return id
  2297. def escape_argument(id):
  2298. if id.startswith("p_") or id.startswith("r_"):
  2299. return id
  2300. return "p_" + id
  2301. def get_operator_id_name(op):
  2302. op_id_map = {
  2303. "==": "equal",
  2304. "!=": "not_equal",
  2305. "<": "less",
  2306. "<=": "less_equal",
  2307. ">": "greater",
  2308. ">=": "greater_equal",
  2309. "+": "add",
  2310. "-": "subtract",
  2311. "*": "multiply",
  2312. "/": "divide",
  2313. "unary-": "negate",
  2314. "unary+": "positive",
  2315. "%": "module",
  2316. "**": "power",
  2317. "<<": "shift_left",
  2318. ">>": "shift_right",
  2319. "&": "bit_and",
  2320. "|": "bit_or",
  2321. "^": "bit_xor",
  2322. "~": "bit_negate",
  2323. "and": "and",
  2324. "or": "or",
  2325. "xor": "xor",
  2326. "not": "not",
  2327. "in": "in",
  2328. }
  2329. return op_id_map[op]
  2330. def get_operator_cpp_name(op):
  2331. op_cpp_map = {
  2332. "==": "==",
  2333. "!=": "!=",
  2334. "<": "<",
  2335. "<=": "<=",
  2336. ">": ">",
  2337. ">=": ">=",
  2338. "+": "+",
  2339. "-": "-",
  2340. "*": "*",
  2341. "/": "/",
  2342. "unary-": "-",
  2343. "unary+": "+",
  2344. "%": "%",
  2345. "<<": "<<",
  2346. ">>": ">>",
  2347. "&": "&",
  2348. "|": "|",
  2349. "^": "^",
  2350. "~": "~",
  2351. "and": "&&",
  2352. "or": "||",
  2353. "not": "!",
  2354. }
  2355. return op_cpp_map[op]
  2356. def is_valid_cpp_operator(op):
  2357. return op not in ["**", "xor", "in"]
  2358. def get_default_value_for_type(type_name):
  2359. if type_name == "int":
  2360. return "0"
  2361. if type_name == "float":
  2362. return "0.0"
  2363. if type_name == "bool":
  2364. return "false"
  2365. if type_name.startswith("typedarray::"):
  2366. return f"{correct_type(type_name)}()"
  2367. if type_name.startswith("typeddictionary::"):
  2368. return f"{correct_type(type_name)}()"
  2369. if is_enum(type_name):
  2370. return f"{correct_type(type_name)}(0)"
  2371. if is_variant(type_name):
  2372. return f"{type_name}()"
  2373. if is_refcounted(type_name):
  2374. return f"Ref<{type_name}>()"
  2375. return "nullptr"
  2376. header = """\
  2377. /**************************************************************************/
  2378. /* $filename */
  2379. /**************************************************************************/
  2380. /* This file is part of: */
  2381. /* GODOT ENGINE */
  2382. /* https://godotengine.org */
  2383. /**************************************************************************/
  2384. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  2385. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  2386. /* */
  2387. /* Permission is hereby granted, free of charge, to any person obtaining */
  2388. /* a copy of this software and associated documentation files (the */
  2389. /* "Software"), to deal in the Software without restriction, including */
  2390. /* without limitation the rights to use, copy, modify, merge, publish, */
  2391. /* distribute, sublicense, and/or sell copies of the Software, and to */
  2392. /* permit persons to whom the Software is furnished to do so, subject to */
  2393. /* the following conditions: */
  2394. /* */
  2395. /* The above copyright notice and this permission notice shall be */
  2396. /* included in all copies or substantial portions of the Software. */
  2397. /* */
  2398. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  2399. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  2400. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  2401. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  2402. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  2403. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  2404. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  2405. /**************************************************************************/
  2406. """
  2407. def add_header(filename, lines):
  2408. desired_length = len(header.split("\n")[0])
  2409. pad_spaces = desired_length - 6 - len(filename)
  2410. for num, line in enumerate(header.split("\n")):
  2411. if num == 1:
  2412. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  2413. lines.append(new_line)
  2414. else:
  2415. lines.append(line)
  2416. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  2417. lines.append("")