binding_generator.py 111 KB

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