binding_generator.py 92 KB

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