2
0

binding_generator.py 113 KB

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