binding_generator.py 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858
  1. #!/usr/bin/env python
  2. import json
  3. import re
  4. import shutil
  5. from pathlib import Path
  6. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  7. api = {}
  8. end = ";"
  9. with open(api_filepath) as api_file:
  10. api = json.load(api_file)
  11. include_gen_folder = Path(output_dir) / "gen" / "include" / "godot_cpp"
  12. source_gen_folder = Path(output_dir) / "gen" / "src"
  13. for builtin_class in api["builtin_classes"]:
  14. if is_pod_type(builtin_class["name"]):
  15. continue
  16. if is_included_type(builtin_class["name"]):
  17. continue
  18. header_filename = include_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".hpp")
  19. source_filename = source_gen_folder / "variant" / (camel_to_snake(builtin_class["name"]) + ".cpp")
  20. if headers:
  21. print(str(header_filename.as_posix()), end=end)
  22. if sources:
  23. print(str(source_filename.as_posix()), end=end)
  24. for engine_class in api["classes"]:
  25. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  26. if engine_class["name"] == "ClassDB":
  27. continue
  28. header_filename = include_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".hpp")
  29. source_filename = source_gen_folder / "classes" / (camel_to_snake(engine_class["name"]) + ".cpp")
  30. if headers:
  31. print(str(header_filename.as_posix()), end=end)
  32. if sources:
  33. print(str(source_filename.as_posix()), end=end)
  34. utility_functions_header_path = include_gen_folder / "variant" / "utility_functions.hpp"
  35. utility_functions_source_path = source_gen_folder / "variant" / "utility_functions.cpp"
  36. global_constants_header_path = include_gen_folder / "classes" / "global_constants.hpp"
  37. if headers:
  38. print(str(utility_functions_header_path.as_posix()), end=end)
  39. print(str(global_constants_header_path.as_posix()), end=end)
  40. if sources:
  41. print(str(utility_functions_source_path.as_posix()), end=end)
  42. def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
  43. api = None
  44. target_dir = Path(output_dir) / "gen"
  45. with open(api_filepath) as api_file:
  46. api = json.load(api_file)
  47. shutil.rmtree(target_dir, ignore_errors=True)
  48. target_dir.mkdir(parents=True)
  49. generate_global_constants(api, target_dir)
  50. generate_global_constant_binds(api, target_dir)
  51. generate_builtin_bindings(api, target_dir, "float_64")
  52. generate_engine_classes_bindings(api, target_dir, use_template_get_node)
  53. generate_utility_functions(api, target_dir)
  54. builtin_classes = []
  55. # Key is class name, value is boolean where True means the class is refcounted.
  56. engine_classes = {}
  57. singletons = []
  58. def generate_builtin_bindings(api, output_dir, build_config):
  59. global builtin_classes
  60. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  61. source_gen_folder = Path(output_dir) / "src" / "variant"
  62. include_gen_folder.mkdir(parents=True, exist_ok=True)
  63. source_gen_folder.mkdir(parents=True, exist_ok=True)
  64. # Store types beforehand.
  65. for builtin_api in api["builtin_classes"]:
  66. if is_pod_type(builtin_api["name"]):
  67. continue
  68. builtin_classes.append(builtin_api["name"])
  69. builtin_sizes = {}
  70. for size_list in api["builtin_class_sizes"]:
  71. if size_list["build_configuration"] == build_config:
  72. for size in size_list["sizes"]:
  73. builtin_sizes[size["name"]] = size["size"]
  74. break
  75. # Create a file for Variant size, since that class isn't generated.
  76. variant_size_filename = include_gen_folder / "variant_size.hpp"
  77. with variant_size_filename.open("+w") as variant_size_file:
  78. variant_size_source = []
  79. add_header("variant_size.hpp", variant_size_source)
  80. header_guard = "GODOT_CPP_VARIANT_SIZE_HPP"
  81. variant_size_source.append(f"#ifndef {header_guard}")
  82. variant_size_source.append(f"#define {header_guard}")
  83. variant_size_source.append(f'#define GODOT_CPP_VARIANT_SIZE {builtin_sizes["Variant"]}')
  84. variant_size_source.append(f"#endif // ! {header_guard}")
  85. variant_size_file.write("\n".join(variant_size_source))
  86. for builtin_api in api["builtin_classes"]:
  87. if is_pod_type(builtin_api["name"]):
  88. continue
  89. if is_included_type(builtin_api["name"]):
  90. continue
  91. size = builtin_sizes[builtin_api["name"]]
  92. header_filename = include_gen_folder / (camel_to_snake(builtin_api["name"]) + ".hpp")
  93. source_filename = source_gen_folder / (camel_to_snake(builtin_api["name"]) + ".cpp")
  94. # Check used classes for header include
  95. used_classes = set()
  96. fully_used_classes = set()
  97. class_name = builtin_api["name"]
  98. if "constructors" in builtin_api:
  99. for constructor in builtin_api["constructors"]:
  100. if "arguments" in constructor:
  101. for argument in constructor["arguments"]:
  102. if is_included(argument["type"], class_name):
  103. if "default_value" in argument and argument["type"] != "Variant":
  104. fully_used_classes.add(argument["type"])
  105. else:
  106. used_classes.add(argument["type"])
  107. if "methods" in builtin_api:
  108. for method in builtin_api["methods"]:
  109. if "arguments" in method:
  110. for argument in method["arguments"]:
  111. if is_included(argument["type"], class_name):
  112. if "default_value" in argument and argument["type"] != "Variant":
  113. fully_used_classes.add(argument["type"])
  114. else:
  115. used_classes.add(argument["type"])
  116. if "return_type" in method:
  117. if is_included(method["return_type"], class_name):
  118. used_classes.add(method["return_type"])
  119. if "members" in builtin_api:
  120. for member in builtin_api["members"]:
  121. if is_included(member["type"], class_name):
  122. used_classes.add(member["type"])
  123. if "indexing_return_type" in builtin_api:
  124. if is_included(builtin_api["indexing_return_type"], class_name):
  125. used_classes.add(builtin_api["indexing_return_type"])
  126. if "operators" in builtin_api:
  127. for operator in builtin_api["operators"]:
  128. if "right_type" in operator:
  129. # FIXME Temporary workaround for incorrect JSON
  130. if operator["right_type"] == "Nil":
  131. used_classes.add("Variant")
  132. elif is_included(operator["right_type"], class_name):
  133. used_classes.add(operator["right_type"])
  134. for type_name in fully_used_classes:
  135. if type_name in used_classes:
  136. used_classes.remove(type_name)
  137. with header_filename.open("w+") as header_file:
  138. header_file.write(generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes))
  139. with source_filename.open("w+") as source_file:
  140. source_file.write(generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes))
  141. # Create a header with all builtin types for convenience.
  142. builtin_header_filename = include_gen_folder / "builtin_types.hpp"
  143. with builtin_header_filename.open("w+") as builtin_header_file:
  144. builtin_header = []
  145. add_header("builtin_types.hpp", builtin_header)
  146. builtin_header.append("#ifndef GODOT_CPP_BUILTIN_TYPES_HPP")
  147. builtin_header.append("#define GODOT_CPP_BUILTIN_TYPES_HPP")
  148. builtin_header.append("")
  149. for builtin in builtin_classes:
  150. builtin_header.append(f"#include <godot_cpp/variant/{camel_to_snake(builtin)}.hpp>")
  151. builtin_header.append("")
  152. builtin_header.append("#endif // ! GODOT_CPP_BUILTIN_TYPES_HPP")
  153. builtin_header_file.write("\n".join(builtin_header))
  154. def generate_builtin_class_header(builtin_api, size, used_classes, fully_used_classes):
  155. result = []
  156. class_name = builtin_api["name"]
  157. snake_class_name = camel_to_snake(class_name).upper()
  158. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  159. add_header(f"{snake_class_name.lower()}.hpp", result)
  160. result.append(f"#ifndef {header_guard}")
  161. result.append(f"#define {header_guard}")
  162. result.append("")
  163. result.append("#include <godot_cpp/core/defs.hpp>")
  164. result.append("")
  165. # Special cases.
  166. if class_name == "String":
  167. result.append("#include <godot_cpp/variant/char_string.hpp>")
  168. result.append("#include <godot_cpp/variant/char_utils.hpp>")
  169. result.append("#include <godot_cpp/variant/ucaps.hpp>")
  170. if class_name == "Array":
  171. result.append("#include <godot_cpp/variant/array_helpers.hpp>")
  172. for include in fully_used_classes:
  173. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  174. if len(fully_used_classes) > 0:
  175. result.append("")
  176. result.append(f"#include <godot/gdnative_interface.h>")
  177. result.append("")
  178. result.append("namespace godot {")
  179. result.append("")
  180. for type_name in used_classes:
  181. result.append(f"class {type_name};")
  182. if len(used_classes) > 0:
  183. result.append("")
  184. result.append(f"class {class_name} {{")
  185. result.append(f"\tstatic constexpr size_t {snake_class_name}_SIZE = {size};")
  186. result.append(f"\tuint8_t opaque[{snake_class_name}_SIZE] = {{}};")
  187. result.append(
  188. f"\t_FORCE_INLINE_ GDNativeTypePtr _native_ptr() const {{ return const_cast<uint8_t (*)[{snake_class_name}_SIZE]>(&opaque); }}"
  189. )
  190. result.append("")
  191. result.append("\tfriend class Variant;")
  192. result.append("")
  193. result.append("\tstatic struct _MethodBindings {")
  194. if "constructors" in builtin_api:
  195. for constructor in builtin_api["constructors"]:
  196. result.append(f'\t\tGDNativePtrConstructor constructor_{constructor["index"]};')
  197. if builtin_api["has_destructor"]:
  198. result.append("\t\tGDNativePtrDestructor destructor;")
  199. if "methods" in builtin_api:
  200. for method in builtin_api["methods"]:
  201. result.append(f'\t\tGDNativePtrBuiltInMethod method_{method["name"]};')
  202. if "members" in builtin_api:
  203. for member in builtin_api["members"]:
  204. result.append(f'\t\tGDNativePtrSetter member_{member["name"]}_setter;')
  205. result.append(f'\t\tGDNativePtrGetter member_{member["name"]}_getter;')
  206. if "indexing_return_type" in builtin_api:
  207. result.append(f"\t\tGDNativePtrIndexedSetter indexed_setter;")
  208. result.append(f"\t\tGDNativePtrIndexedGetter indexed_getter;")
  209. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  210. result.append(f"\t\tGDNativePtrKeyedSetter keyed_setter;")
  211. result.append(f"\t\tGDNativePtrKeyedGetter keyed_getter;")
  212. result.append(f"\t\tGDNativePtrKeyedChecker keyed_checker;")
  213. if "operators" in builtin_api:
  214. for operator in builtin_api["operators"]:
  215. if "right_type" in operator:
  216. result.append(
  217. f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]};'
  218. )
  219. else:
  220. result.append(f'\t\tGDNativePtrOperatorEvaluator operator_{get_operator_id_name(operator["name"])};')
  221. result.append("\t} _method_bindings;")
  222. result.append("")
  223. result.append("\tstatic void init_bindings();")
  224. result.append("")
  225. result.append("public:")
  226. copy_constructor_index = -1
  227. if "constructors" in builtin_api:
  228. for constructor in builtin_api["constructors"]:
  229. method_signature = f"\t{class_name}("
  230. if "arguments" in constructor:
  231. method_signature += make_function_parameters(
  232. constructor["arguments"], include_default=True, for_builtin=True
  233. )
  234. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  235. copy_constructor_index = constructor["index"]
  236. method_signature += ");"
  237. result.append(method_signature)
  238. # Move constructor.
  239. result.append(f"\t{class_name}({class_name} &&other);")
  240. # Special cases.
  241. if class_name == "String" or class_name == "StringName" or class_name == "NodePath":
  242. result.append(f"\t{class_name}(const char *from);")
  243. result.append(f"\t{class_name}(const wchar_t *from);")
  244. result.append(f"\t{class_name}(const char16_t *from);")
  245. result.append(f"\t{class_name}(const char32_t *from);")
  246. if "constants" in builtin_api:
  247. axis_constants_count = 0
  248. for constant in builtin_api["constants"]:
  249. # Special case: Vector3.Axis is the only enum in the bindings.
  250. # It's technically not supported by Variant but works for direct access.
  251. if class_name == "Vector3" and constant["name"].startswith("AXIS"):
  252. if axis_constants_count == 0:
  253. result.append("\tenum Axis {")
  254. result.append(f'\t\t{constant["name"]} = {constant["value"]},')
  255. axis_constants_count += 1
  256. if axis_constants_count == 3:
  257. result.append("\t};")
  258. else:
  259. result.append(f'\tstatic const {correct_type(constant["type"])} {constant["name"]};')
  260. if builtin_api["has_destructor"]:
  261. result.append(f"\t~{class_name}();")
  262. method_list = []
  263. if "methods" in builtin_api:
  264. for method in builtin_api["methods"]:
  265. method_list.append(method["name"])
  266. vararg = method["is_vararg"]
  267. if vararg:
  268. result.append("\ttemplate<class... Args>")
  269. method_signature = "\t"
  270. if "is_static" in method and method["is_static"]:
  271. method_signature += "static "
  272. if "return_type" in method:
  273. method_signature += f'{correct_type(method["return_type"])} '
  274. else:
  275. method_signature += "void "
  276. method_signature += f'{method["name"]}('
  277. method_arguments = []
  278. if "arguments" in method:
  279. method_arguments = method["arguments"]
  280. method_signature += make_function_parameters(
  281. method_arguments, include_default=True, for_builtin=True, is_vararg=vararg
  282. )
  283. method_signature += ")"
  284. if method["is_const"]:
  285. method_signature += " const"
  286. method_signature += ";"
  287. result.append(method_signature)
  288. # Special cases.
  289. if class_name == "String":
  290. result.append("\tstatic String utf8(const char *from, int len = -1);")
  291. result.append("\tvoid parse_utf8(const char *from, int len = -1);")
  292. result.append("\tstatic String utf16(const char16_t *from, int len = -1);")
  293. result.append("\tvoid parse_utf16(const char16_t *from, int len = -1);")
  294. result.append("\tCharString utf8() const;")
  295. result.append("\tCharString ascii() const;")
  296. result.append("\tChar16String utf16() const;")
  297. result.append("\tChar32String utf32() const;")
  298. result.append("\tCharWideString wide_string() const;")
  299. if "members" in builtin_api:
  300. for member in builtin_api["members"]:
  301. if f'get_{member["name"]}' not in method_list:
  302. result.append(f'\t{correct_type(member["type"])} get_{member["name"]}() const;')
  303. if f'set_{member["name"]}' not in method_list:
  304. result.append(f'\tvoid set_{member["name"]}({type_for_parameter(member["type"])}value);')
  305. if "operators" in builtin_api:
  306. for operator in builtin_api["operators"]:
  307. if operator["name"] not in ["in", "xor"]:
  308. if "right_type" in operator:
  309. result.append(
  310. f'\t{correct_type(operator["return_type"])} operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const;'
  311. )
  312. else:
  313. result.append(
  314. f'\t{correct_type(operator["return_type"])} operator{operator["name"].replace("unary", "")}() const;'
  315. )
  316. # Copy assignment.
  317. if copy_constructor_index >= 0:
  318. result.append(f"\t{class_name} &operator=(const {class_name} &other);")
  319. # Move assignment.
  320. result.append(f"\t{class_name} &operator=({class_name} &&other);")
  321. # Special cases.
  322. if class_name == "String":
  323. result.append("String &operator=(const char *p_str);")
  324. result.append("String &operator=(const wchar_t *p_str);")
  325. result.append("String &operator=(const char16_t *p_str);")
  326. result.append("String &operator=(const char32_t *p_str);")
  327. result.append("bool operator==(const char *p_str) const;")
  328. result.append("bool operator==(const wchar_t *p_str) const;")
  329. result.append("bool operator==(const char16_t *p_str) const;")
  330. result.append("bool operator==(const char32_t *p_str) const;")
  331. result.append("bool operator!=(const char *p_str) const;")
  332. result.append("bool operator!=(const wchar_t *p_str) const;")
  333. result.append("bool operator!=(const char16_t *p_str) const;")
  334. result.append("bool operator!=(const char32_t *p_str) const;")
  335. result.append(f"\tconst char32_t &operator[](int p_index) const;")
  336. result.append(f"\tchar32_t &operator[](int p_index);")
  337. result.append(f"\tconst char32_t *ptr() const;")
  338. result.append(f"\tchar32_t *ptrw();")
  339. if class_name == "Array":
  340. result.append("\ttemplate <class... Args>")
  341. result.append("\tstatic Array make(Args... args) {")
  342. result.append("\t\treturn helpers::append_all(Array(), args...);")
  343. result.append("\t}")
  344. if is_packed_array(class_name):
  345. return_type = correct_type(builtin_api["indexing_return_type"])
  346. if class_name == "PackedByteArray":
  347. return_type = "uint8_t"
  348. elif class_name == "PackedInt32Array":
  349. return_type = "int32_t"
  350. elif class_name == "PackedFloat32Array":
  351. return_type = "float"
  352. result.append(f"\tconst " + return_type + f" &operator[](int p_index) const;")
  353. result.append(f"\t" + return_type + f" &operator[](int p_index);")
  354. result.append(f"\tconst " + return_type + f" *ptr() const;")
  355. result.append(f"\t" + return_type + f" *ptrw();")
  356. if class_name == "Array":
  357. result.append(f"\tconst Variant &operator[](int p_index) const;")
  358. result.append(f"\tVariant &operator[](int p_index);")
  359. if class_name == "Dictionary":
  360. result.append(f"\tconst Variant &operator[](const Variant &p_key) const;")
  361. result.append(f"\tVariant &operator[](const Variant &p_key);")
  362. result.append("};")
  363. if class_name == "String":
  364. result.append("")
  365. result.append("bool operator==(const char *p_chr, const String &p_str);")
  366. result.append("bool operator==(const wchar_t *p_chr, const String &p_str);")
  367. result.append("bool operator==(const char16_t *p_chr, const String &p_str);")
  368. result.append("bool operator==(const char32_t *p_chr, const String &p_str);")
  369. result.append("bool operator!=(const char *p_chr, const String &p_str);")
  370. result.append("bool operator!=(const wchar_t *p_chr, const String &p_str);")
  371. result.append("bool operator!=(const char16_t *p_chr, const String &p_str);")
  372. result.append("bool operator!=(const char32_t *p_chr, const String &p_str);")
  373. result.append("String operator+(const char *p_chr, const String &p_str);")
  374. result.append("String operator+(const wchar_t *p_chr, const String &p_str);")
  375. result.append("String operator+(const char16_t *p_chr, const String &p_str);")
  376. result.append("String operator+(const char32_t *p_chr, const String &p_str);")
  377. result.append("")
  378. result.append("} // namespace godot")
  379. result.append(f"#endif // ! {header_guard}")
  380. return "\n".join(result)
  381. def generate_builtin_class_source(builtin_api, size, used_classes, fully_used_classes):
  382. result = []
  383. class_name = builtin_api["name"]
  384. snake_class_name = camel_to_snake(class_name)
  385. enum_type_name = f"GDNATIVE_VARIANT_TYPE_{snake_class_name.upper()}"
  386. add_header(f"{snake_class_name}.cpp", result)
  387. result.append("")
  388. result.append(f"#include <godot_cpp/variant/{snake_class_name}.hpp>")
  389. result.append("")
  390. result.append("#include <godot_cpp/core/binder_common.hpp>")
  391. result.append("")
  392. result.append("#include <godot_cpp/godot.hpp>")
  393. result.append("")
  394. # Only used since the "fully used" is included in header already.
  395. for include in used_classes:
  396. result.append(f"#include <godot_cpp/{get_include_path(include)}>")
  397. if len(used_classes) > 0:
  398. result.append("")
  399. result.append("#include <godot_cpp/core/builtin_ptrcall.hpp>")
  400. result.append("")
  401. result.append("#include <utility>")
  402. result.append("")
  403. result.append("namespace godot {")
  404. result.append("")
  405. result.append(f"{class_name}::_MethodBindings {class_name}::_method_bindings;")
  406. result.append("")
  407. result.append(f"void {class_name}::init_bindings() {{")
  408. if "constructors" in builtin_api:
  409. for constructor in builtin_api["constructors"]:
  410. result.append(
  411. f'\t_method_bindings.constructor_{constructor["index"]} = internal::gdn_interface->variant_get_ptr_constructor({enum_type_name}, {constructor["index"]});'
  412. )
  413. if builtin_api["has_destructor"]:
  414. result.append(
  415. f"\t_method_bindings.destructor = internal::gdn_interface->variant_get_ptr_destructor({enum_type_name});"
  416. )
  417. if "methods" in builtin_api:
  418. for method in builtin_api["methods"]:
  419. # TODO: Add error check for hash mismatch.
  420. result.append(
  421. f'\t_method_bindings.method_{method["name"]} = internal::gdn_interface->variant_get_ptr_builtin_method({enum_type_name}, "{method["name"]}", {method["hash"]});'
  422. )
  423. if "members" in builtin_api:
  424. for member in builtin_api["members"]:
  425. result.append(
  426. f'\t_method_bindings.member_{member["name"]}_setter = internal::gdn_interface->variant_get_ptr_setter({enum_type_name}, "{member["name"]}");'
  427. )
  428. result.append(
  429. f'\t_method_bindings.member_{member["name"]}_getter = internal::gdn_interface->variant_get_ptr_getter({enum_type_name}, "{member["name"]}");'
  430. )
  431. if "indexing_return_type" in builtin_api:
  432. result.append(
  433. f"\t_method_bindings.indexed_setter = internal::gdn_interface->variant_get_ptr_indexed_setter({enum_type_name});"
  434. )
  435. result.append(
  436. f"\t_method_bindings.indexed_getter = internal::gdn_interface->variant_get_ptr_indexed_getter({enum_type_name});"
  437. )
  438. if "is_keyed" in builtin_api and builtin_api["is_keyed"]:
  439. result.append(
  440. f"\t_method_bindings.keyed_setter = internal::gdn_interface->variant_get_ptr_keyed_setter({enum_type_name});"
  441. )
  442. result.append(
  443. f"\t_method_bindings.keyed_getter = internal::gdn_interface->variant_get_ptr_keyed_getter({enum_type_name});"
  444. )
  445. result.append(
  446. f"\t_method_bindings.keyed_checker = internal::gdn_interface->variant_get_ptr_keyed_checker({enum_type_name});"
  447. )
  448. if "operators" in builtin_api:
  449. for operator in builtin_api["operators"]:
  450. if "right_type" in operator:
  451. result.append(
  452. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]} = internal::gdn_interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_{camel_to_snake(operator["right_type"]).upper()});'
  453. )
  454. else:
  455. result.append(
  456. f'\t_method_bindings.operator_{get_operator_id_name(operator["name"])} = internal::gdn_interface->variant_get_ptr_operator_evaluator(GDNATIVE_VARIANT_OP_{get_operator_id_name(operator["name"]).upper()}, {enum_type_name}, GDNATIVE_VARIANT_TYPE_NIL);'
  457. )
  458. result.append("}")
  459. result.append("")
  460. copy_constructor_index = -1
  461. if "constructors" in builtin_api:
  462. for constructor in builtin_api["constructors"]:
  463. method_signature = f"{class_name}::{class_name}("
  464. if "arguments" in constructor:
  465. method_signature += make_function_parameters(
  466. constructor["arguments"], include_default=False, for_builtin=True
  467. )
  468. method_signature += ") {"
  469. result.append(method_signature)
  470. method_call = (
  471. f'\tinternal::_call_builtin_constructor(_method_bindings.constructor_{constructor["index"]}, &opaque'
  472. )
  473. if "arguments" in constructor:
  474. if len(constructor["arguments"]) == 1 and constructor["arguments"][0]["type"] == class_name:
  475. copy_constructor_index = constructor["index"]
  476. method_call += ", "
  477. arguments = []
  478. for argument in constructor["arguments"]:
  479. (encode, arg_name) = get_encoded_arg(
  480. argument["name"],
  481. argument["type"],
  482. argument["meta"] if "meta" in argument else None,
  483. )
  484. result += encode
  485. arguments.append(arg_name)
  486. method_call += ", ".join(arguments)
  487. method_call += ");"
  488. result.append(method_call)
  489. result.append("}")
  490. result.append("")
  491. # Move constructor.
  492. result.append(f"{class_name}::{class_name}({class_name} &&other) {{")
  493. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  494. result.append(
  495. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &other);"
  496. )
  497. else:
  498. result.append("\tstd::swap(opaque, other.opaque);")
  499. result.append("}")
  500. result.append("")
  501. if builtin_api["has_destructor"]:
  502. result.append(f"{class_name}::~{class_name}() {{")
  503. result.append("\t_method_bindings.destructor(&opaque);")
  504. result.append("}")
  505. result.append("")
  506. method_list = []
  507. if "methods" in builtin_api:
  508. for method in builtin_api["methods"]:
  509. method_list.append(method["name"])
  510. if "is_vararg" in method and method["is_vararg"]:
  511. # Done in the header because of the template.
  512. continue
  513. method_signature = make_signature(class_name, method, for_builtin=True)
  514. result.append(method_signature + "{")
  515. method_call = "\t"
  516. if "return_type" in method:
  517. method_call += f'return internal::_call_builtin_method_ptr_ret<{correct_type(method["return_type"])}>('
  518. else:
  519. method_call += f"internal::_call_builtin_method_ptr_no_ret("
  520. method_call += f'_method_bindings.method_{method["name"]}, '
  521. if "is_static" in method and method["is_static"]:
  522. method_call += "nullptr"
  523. else:
  524. method_call += "(GDNativeTypePtr)&opaque"
  525. if "arguments" in method:
  526. arguments = []
  527. method_call += ", "
  528. for argument in method["arguments"]:
  529. (encode, arg_name) = get_encoded_arg(
  530. argument["name"],
  531. argument["type"],
  532. argument["meta"] if "meta" in argument else None,
  533. )
  534. result += encode
  535. arguments.append(arg_name)
  536. method_call += ", ".join(arguments)
  537. method_call += ");"
  538. result.append(method_call)
  539. result.append("}")
  540. result.append("")
  541. if "members" in builtin_api:
  542. for member in builtin_api["members"]:
  543. if f'get_{member["name"]}' not in method_list:
  544. result.append(f'{correct_type(member["type"])} {class_name}::get_{member["name"]}() const {{')
  545. result.append(
  546. f'\treturn internal::_call_builtin_ptr_getter<{correct_type(member["type"])}>(_method_bindings.member_{member["name"]}_getter, (const GDNativeTypePtr)&opaque);'
  547. )
  548. result.append("}")
  549. if f'set_{member["name"]}' not in method_list:
  550. result.append(f'void {class_name}::set_{member["name"]}({type_for_parameter(member["type"])}value) {{')
  551. (encode, arg_name) = get_encoded_arg("value", member["type"], None)
  552. result += encode
  553. result.append(
  554. f'\t_method_bindings.member_{member["name"]}_setter((const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  555. )
  556. result.append("}")
  557. result.append("")
  558. if "operators" in builtin_api:
  559. for operator in builtin_api["operators"]:
  560. if operator["name"] not in ["in", "xor"]:
  561. if "right_type" in operator:
  562. result.append(
  563. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"]}({type_for_parameter(operator["right_type"])}other) const {{'
  564. )
  565. (encode, arg_name) = get_encoded_arg("other", operator["right_type"], None)
  566. result += encode
  567. result.append(
  568. f'\treturn internal::_call_builtin_operator_ptr<{get_gdnative_type(correct_type(operator["return_type"]))}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}_{operator["right_type"]}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr){arg_name});'
  569. )
  570. result.append("}")
  571. else:
  572. result.append(
  573. f'{correct_type(operator["return_type"])} {class_name}::operator{operator["name"].replace("unary", "")}() const {{'
  574. )
  575. result.append(
  576. f'\treturn internal::_call_builtin_operator_ptr<{get_gdnative_type(correct_type(operator["return_type"]))}>(_method_bindings.operator_{get_operator_id_name(operator["name"])}, (const GDNativeTypePtr)&opaque, (const GDNativeTypePtr)nullptr);'
  577. )
  578. result.append("}")
  579. result.append("")
  580. # Copy assignment.
  581. if copy_constructor_index >= 0:
  582. result.append(f"{class_name} &{class_name}::operator=(const {class_name} &other) {{")
  583. if builtin_api["has_destructor"]:
  584. result.append("\t_method_bindings.destructor(&opaque);")
  585. (encode, arg_name) = get_encoded_arg(
  586. "other",
  587. class_name,
  588. None,
  589. )
  590. result += encode
  591. result.append(
  592. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, {arg_name});"
  593. )
  594. result.append("\treturn *this;")
  595. result.append("}")
  596. result.append("")
  597. # Move assignment.
  598. result.append(f"{class_name} &{class_name}::operator=({class_name} &&other) {{")
  599. if needs_copy_instead_of_move(class_name) and copy_constructor_index >= 0:
  600. result.append(
  601. f"\tinternal::_call_builtin_constructor(_method_bindings.constructor_{copy_constructor_index}, &opaque, &other);"
  602. )
  603. else:
  604. result.append("\tstd::swap(opaque, other.opaque);")
  605. result.append("\treturn *this;")
  606. result.append("}")
  607. result.append("")
  608. result.append("} //namespace godot")
  609. return "\n".join(result)
  610. def generate_engine_classes_bindings(api, output_dir, use_template_get_node):
  611. global engine_classes
  612. global singletons
  613. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  614. source_gen_folder = Path(output_dir) / "src" / "classes"
  615. include_gen_folder.mkdir(parents=True, exist_ok=True)
  616. source_gen_folder.mkdir(parents=True, exist_ok=True)
  617. # First create map of classes and singletons.
  618. for class_api in api["classes"]:
  619. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  620. if class_api["name"] == "ClassDB":
  621. continue
  622. engine_classes[class_api["name"]] = class_api["is_refcounted"]
  623. for native_struct in api["native_structures"]:
  624. engine_classes[native_struct["name"]] = False
  625. for singleton in api["singletons"]:
  626. singletons.append(singleton["name"])
  627. for class_api in api["classes"]:
  628. # TODO: Properly setup this singleton since it conflicts with ClassDB in the bindings.
  629. if class_api["name"] == "ClassDB":
  630. continue
  631. # Check used classes for header include.
  632. used_classes = set()
  633. fully_used_classes = set()
  634. class_name = class_api["name"]
  635. header_filename = include_gen_folder / (camel_to_snake(class_api["name"]) + ".hpp")
  636. source_filename = source_gen_folder / (camel_to_snake(class_api["name"]) + ".cpp")
  637. if "methods" in class_api:
  638. for method in class_api["methods"]:
  639. if "arguments" in method:
  640. for argument in method["arguments"]:
  641. type_name = argument["type"]
  642. if type_name.startswith("const "):
  643. type_name = type_name[6:]
  644. if type_name.endswith("*"):
  645. type_name = type_name[:-1]
  646. if is_included(type_name, class_name):
  647. if is_enum(type_name):
  648. fully_used_classes.add(get_enum_class(type_name))
  649. elif "default_value" in argument:
  650. fully_used_classes.add(type_name)
  651. else:
  652. used_classes.add(type_name)
  653. if is_refcounted(type_name):
  654. fully_used_classes.add("Ref")
  655. if "return_value" in method:
  656. type_name = method["return_value"]["type"]
  657. if type_name.startswith("const "):
  658. type_name = type_name[6:]
  659. if type_name.endswith("*"):
  660. type_name = type_name[:-1]
  661. if is_included(type_name, class_name):
  662. if is_enum(type_name):
  663. fully_used_classes.add(get_enum_class(type_name))
  664. elif is_variant(type_name):
  665. fully_used_classes.add(type_name)
  666. else:
  667. used_classes.add(type_name)
  668. if is_refcounted(type_name):
  669. fully_used_classes.add("Ref")
  670. if "members" in class_api:
  671. for member in class_api["members"]:
  672. if is_included(member["type"], class_name):
  673. if is_enum(member["type"]):
  674. fully_used_classes.add(get_enum_class(member["type"]))
  675. else:
  676. used_classes.add(member["type"])
  677. if is_refcounted(member["type"]):
  678. fully_used_classes.add("Ref")
  679. if "inherits" in class_api:
  680. if is_included(class_api["inherits"], class_name):
  681. fully_used_classes.add(class_api["inherits"])
  682. if is_refcounted(class_api["name"]):
  683. fully_used_classes.add("Ref")
  684. else:
  685. fully_used_classes.add("Wrapped")
  686. for type_name in fully_used_classes:
  687. if type_name in used_classes:
  688. used_classes.remove(type_name)
  689. with header_filename.open("w+") as header_file:
  690. header_file.write(
  691. generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node)
  692. )
  693. with source_filename.open("w+") as source_file:
  694. source_file.write(
  695. generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node)
  696. )
  697. for native_struct in api["native_structures"]:
  698. struct_name = native_struct["name"]
  699. snake_struct_name = camel_to_snake(struct_name)
  700. header_filename = include_gen_folder / (snake_struct_name + ".hpp")
  701. result = []
  702. add_header(f"{snake_struct_name}.hpp", result)
  703. header_guard = f"GODOT_CPP_{snake_struct_name.upper()}_HPP"
  704. result.append(f"#ifndef {header_guard}")
  705. result.append(f"#define {header_guard}")
  706. result.append("")
  707. result.append("namespace godot {")
  708. result.append("")
  709. result.append(f"struct {struct_name} {{")
  710. for field in native_struct["format"].split(","):
  711. result.append(f"\t{field};")
  712. result.append("};")
  713. result.append("")
  714. result.append(f"GDVIRTUAL_NATIVE_PTR({struct_name});")
  715. result.append("")
  716. result.append("} // namespace godot")
  717. result.append("")
  718. result.append(f"#endif // ! {header_guard}")
  719. with header_filename.open("w+") as header_file:
  720. header_file.write("\n".join(result))
  721. def generate_engine_class_header(class_api, used_classes, fully_used_classes, use_template_get_node):
  722. global singletons
  723. result = []
  724. class_name = class_api["name"]
  725. snake_class_name = camel_to_snake(class_name).upper()
  726. is_singleton = class_name in singletons
  727. add_header(f"{snake_class_name.lower()}.hpp", result)
  728. header_guard = f"GODOT_CPP_{snake_class_name}_HPP"
  729. result.append(f"#ifndef {header_guard}")
  730. result.append(f"#define {header_guard}")
  731. result.append("")
  732. for included in fully_used_classes:
  733. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  734. if len(fully_used_classes) > 0:
  735. result.append("")
  736. if class_name != "Object":
  737. result.append("#include <godot_cpp/core/class_db.hpp>")
  738. result.append("")
  739. result.append("#include <type_traits>")
  740. result.append("")
  741. result.append("namespace godot {")
  742. result.append("")
  743. for type_name in used_classes:
  744. result.append(f"class {type_name};")
  745. if len(used_classes) > 0:
  746. result.append("")
  747. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  748. result.append(f"class {class_name} : public {inherits} {{")
  749. result.append(f"\tGDNATIVE_CLASS({class_name}, {inherits})")
  750. result.append("")
  751. result.append("public:")
  752. result.append("")
  753. if "enums" in class_api:
  754. for enum_api in class_api["enums"]:
  755. result.append(f'\tenum {enum_api["name"]} {{')
  756. for value in enum_api["values"]:
  757. result.append(f'\t\t{value["name"]} = {value["value"]},')
  758. result.append("\t};")
  759. result.append("")
  760. if is_singleton:
  761. result.append(f"\tstatic {class_name} *get_singleton();")
  762. result.append("")
  763. if "methods" in class_api:
  764. for method in class_api["methods"]:
  765. if method["is_virtual"]:
  766. # Will be done later.
  767. continue
  768. vararg = "is_vararg" in method and method["is_vararg"]
  769. method_signature = "\t"
  770. if vararg:
  771. method_signature += "private: "
  772. method_signature += make_signature(
  773. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  774. )
  775. result.append(method_signature + ";")
  776. if vararg:
  777. # Add templated version.
  778. result += make_varargs_template(method)
  779. # Virtuals now.
  780. for method in class_api["methods"]:
  781. if not method["is_virtual"]:
  782. continue
  783. method_signature = "\t"
  784. method_signature += make_signature(
  785. class_name, method, for_header=True, use_template_get_node=use_template_get_node
  786. )
  787. result.append(method_signature + ";")
  788. result.append("protected:")
  789. result.append("\ttemplate <class T>")
  790. result.append("\tstatic void register_virtuals() {")
  791. if class_name != "Object":
  792. result.append(f"\t\t{inherits}::register_virtuals<T>();")
  793. if "methods" in class_api:
  794. for method in class_api["methods"]:
  795. if not method["is_virtual"]:
  796. continue
  797. method_name = escape_identifier(method["name"])
  798. result.append(
  799. f"\t\tif constexpr (!std::is_same_v<decltype(&{class_name}::{method_name}),decltype(&T::{method_name})>) {{"
  800. )
  801. result.append(f"\t\t\tBIND_VIRTUAL_METHOD(T, {method_name});")
  802. result.append("\t\t}")
  803. result.append("\t}")
  804. result.append("")
  805. result.append("public:")
  806. # Special cases.
  807. if class_name == "Object":
  808. result.append("")
  809. result.append("\ttemplate<class T>")
  810. result.append("\tstatic T *cast_to(Object *p_object);")
  811. result.append("\tvirtual ~Object() = default;")
  812. elif use_template_get_node and class_name == "Node":
  813. result.append("\ttemplate<class T>")
  814. result.append(
  815. "\tT *get_node(const NodePath &p_path) const { return Object::cast_to<T>(get_node_internal(p_path)); }"
  816. )
  817. result.append("")
  818. result.append("};")
  819. result.append("")
  820. result.append("} // namespace godot")
  821. result.append("")
  822. if "enums" in class_api and class_name != "Object":
  823. for enum_api in class_api["enums"]:
  824. result.append(f'VARIANT_ENUM_CAST({class_name}, {class_name}::{enum_api["name"]});')
  825. result.append("")
  826. result.append(f"#endif // ! {header_guard}")
  827. return "\n".join(result)
  828. def generate_engine_class_source(class_api, used_classes, fully_used_classes, use_template_get_node):
  829. global singletons
  830. result = []
  831. class_name = class_api["name"]
  832. snake_class_name = camel_to_snake(class_name)
  833. inherits = class_api["inherits"] if "inherits" in class_api else "Wrapped"
  834. is_singleton = class_name in singletons
  835. add_header(f"{snake_class_name}.cpp", result)
  836. result.append(f"#include <godot_cpp/classes/{snake_class_name}.hpp>")
  837. result.append("")
  838. result.append(f"#include <godot_cpp/core/engine_ptrcall.hpp>")
  839. result.append(f"#include <godot_cpp/core/error_macros.hpp>")
  840. result.append("")
  841. for included in used_classes:
  842. result.append(f"#include <godot_cpp/{get_include_path(included)}>")
  843. if len(used_classes) > 0:
  844. result.append(f"")
  845. result.append("namespace godot {")
  846. result.append("")
  847. if is_singleton:
  848. result.append(f"{class_name} *{class_name}::get_singleton() {{")
  849. result.append(
  850. f'\tstatic GDNativeObjectPtr singleton_obj = internal::gdn_interface->global_get_singleton("{class_name}");'
  851. )
  852. result.append("#ifdef DEBUG_ENABLED")
  853. result.append("\tERR_FAIL_COND_V(singleton_obj == nullptr, nullptr);")
  854. result.append("#endif // DEBUG_ENABLED")
  855. result.append(
  856. f"\tstatic {class_name} *singleton = reinterpret_cast<{class_name} *>(internal::gdn_interface->object_get_instance_binding(singleton_obj, internal::token, &{class_name}::___binding_callbacks));"
  857. )
  858. result.append("\treturn singleton;")
  859. result.append("}")
  860. result.append("")
  861. if "methods" in class_api:
  862. for method in class_api["methods"]:
  863. if method["is_virtual"]:
  864. # Will be done later
  865. continue
  866. vararg = "is_vararg" in method and method["is_vararg"]
  867. # Method signature.
  868. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  869. result.append(method_signature + " {")
  870. # Method body.
  871. result.append(
  872. f'\tstatic GDNativeMethodBindPtr ___method_bind = internal::gdn_interface->classdb_get_method_bind("{class_name}", "{method["name"]}", {method["hash"]});'
  873. )
  874. method_call = "\t"
  875. has_return = "return_value" in method and method["return_value"]["type"] != "void"
  876. if has_return:
  877. result.append(
  878. f'\tCHECK_METHOD_BIND_RET(___method_bind, {get_default_value_for_type(method["return_value"]["type"])});'
  879. )
  880. else:
  881. result.append(f"\tCHECK_METHOD_BIND(___method_bind);")
  882. is_ref = False
  883. if not vararg:
  884. if has_return:
  885. return_type = method["return_value"]["type"]
  886. meta_type = method["return_value"]["meta"] if "meta" in method["return_value"] else None
  887. if is_pod_type(return_type) or is_variant(return_type) or is_enum(return_type):
  888. method_call += f"return internal::_call_native_mb_ret<{get_gdnative_type(correct_type(return_type, meta_type))}>(___method_bind, _owner"
  889. elif is_refcounted(return_type):
  890. method_call += f"return Ref<{return_type}>::___internal_constructor(internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  891. is_ref = True
  892. else:
  893. method_call += f"return internal::_call_native_mb_ret_obj<{return_type}>(___method_bind, _owner"
  894. else:
  895. method_call += f"internal::_call_native_mb_no_ret(___method_bind, _owner"
  896. if "arguments" in method:
  897. method_call += ", "
  898. arguments = []
  899. for argument in method["arguments"]:
  900. (encode, arg_name) = get_encoded_arg(
  901. argument["name"],
  902. argument["type"],
  903. argument["meta"] if "meta" in argument else None,
  904. )
  905. result += encode
  906. arguments.append(arg_name)
  907. method_call += ", ".join(arguments)
  908. else: # vararg.
  909. result.append("\tGDNativeCallError error;")
  910. result.append("\tVariant ret;")
  911. method_call += "internal::gdn_interface->object_method_bind_call(___method_bind, _owner, (const GDNativeVariantPtr *)args, arg_count, &ret, &error"
  912. if is_ref:
  913. method_call += ")" # Close Ref<> constructor.
  914. method_call += ");"
  915. result.append(method_call)
  916. if vararg and ("return_value" in method and method["return_value"]["type"] != "void"):
  917. result.append("\treturn ret;")
  918. result.append("}")
  919. result.append("")
  920. # Virtuals now.
  921. for method in class_api["methods"]:
  922. if not method["is_virtual"]:
  923. continue
  924. method_signature = make_signature(class_name, method, use_template_get_node=use_template_get_node)
  925. method_signature += " {"
  926. if "return_value" in method and correct_type(method["return_value"]["type"]) != "void":
  927. result.append(method_signature)
  928. result.append(f'\treturn {get_default_value_for_type(method["return_value"]["type"])};')
  929. result.append("}")
  930. else:
  931. method_signature += "}"
  932. result.append(method_signature)
  933. result.append("")
  934. result.append("")
  935. result.append("} // namespace godot ")
  936. return "\n".join(result)
  937. def generate_global_constants(api, output_dir):
  938. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  939. source_gen_folder = Path(output_dir) / "src" / "classes"
  940. include_gen_folder.mkdir(parents=True, exist_ok=True)
  941. source_gen_folder.mkdir(parents=True, exist_ok=True)
  942. # Generate header
  943. header = []
  944. add_header("global_constants.hpp", header)
  945. header_filename = include_gen_folder / "global_constants.hpp"
  946. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_HPP"
  947. header.append(f"#ifndef {header_guard}")
  948. header.append(f"#define {header_guard}")
  949. header.append("")
  950. header.append("namespace godot {")
  951. header.append("")
  952. for constant in api["global_constants"]:
  953. header.append(f'\tconst int {escape_identifier(constant["name"])} = {constant["value"]};')
  954. header.append("")
  955. for enum_def in api["global_enums"]:
  956. if enum_def["name"].startswith("Variant."):
  957. continue
  958. header.append(f'\tenum {enum_def["name"]} {{')
  959. for value in enum_def["values"]:
  960. header.append(f'\t\t{value["name"]} = {value["value"]},')
  961. header.append("\t};")
  962. header.append("")
  963. header.append("} // namespace godot")
  964. header.append("")
  965. header.append(f"#endif // ! {header_guard}")
  966. with header_filename.open("w+") as header_file:
  967. header_file.write("\n".join(header))
  968. def generate_global_constant_binds(api, output_dir):
  969. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "classes"
  970. source_gen_folder = Path(output_dir) / "src" / "classes"
  971. include_gen_folder.mkdir(parents=True, exist_ok=True)
  972. source_gen_folder.mkdir(parents=True, exist_ok=True)
  973. # Generate header
  974. header = []
  975. add_header("global_constants_binds.hpp", header)
  976. header_filename = include_gen_folder / "global_constants_binds.hpp"
  977. header_guard = "GODOT_CPP_GLOBAL_CONSTANTS_BINDS_HPP"
  978. header.append(f"#ifndef {header_guard}")
  979. header.append(f"#define {header_guard}")
  980. header.append("")
  981. header.append("#include <godot_cpp/classes/global_constants.hpp>")
  982. header.append("#include <godot_cpp/core/binder_common.hpp>")
  983. header.append("")
  984. for enum_def in api["global_enums"]:
  985. if enum_def["name"].startswith("Variant."):
  986. continue
  987. header.append(f'VARIANT_ENUM_CAST(, godot::{enum_def["name"]});')
  988. header.append("")
  989. header.append(f"#endif // ! {header_guard}")
  990. with header_filename.open("w+") as header_file:
  991. header_file.write("\n".join(header))
  992. def generate_utility_functions(api, output_dir):
  993. include_gen_folder = Path(output_dir) / "include" / "godot_cpp" / "variant"
  994. source_gen_folder = Path(output_dir) / "src" / "variant"
  995. include_gen_folder.mkdir(parents=True, exist_ok=True)
  996. source_gen_folder.mkdir(parents=True, exist_ok=True)
  997. # Generate header.
  998. header = []
  999. add_header("utility_functions.hpp", header)
  1000. header_filename = include_gen_folder / "utility_functions.hpp"
  1001. header_guard = "GODOT_CPP_UTILITY_FUNCTIONS_HPP"
  1002. header.append(f"#ifndef {header_guard}")
  1003. header.append(f"#define {header_guard}")
  1004. header.append("")
  1005. header.append("#include <godot_cpp/variant/builtin_types.hpp>")
  1006. header.append("#include <godot_cpp/variant/variant.hpp>")
  1007. header.append("")
  1008. header.append("#include <array>")
  1009. header.append("")
  1010. header.append("namespace godot {")
  1011. header.append("")
  1012. header.append("class UtilityFunctions {")
  1013. header.append("public:")
  1014. for function in api["utility_functions"]:
  1015. vararg = "is_vararg" in function and function["is_vararg"]
  1016. function_signature = "\t"
  1017. function_signature += make_signature("UtilityFunctions", function, for_header=True, static=True)
  1018. header.append(function_signature + ";")
  1019. if vararg:
  1020. # Add templated version.
  1021. header += make_varargs_template(function, static=True)
  1022. header.append("};")
  1023. header.append("")
  1024. header.append("} // namespace godot")
  1025. header.append("")
  1026. header.append(f"#endif // ! {header_guard}")
  1027. with header_filename.open("w+") as header_file:
  1028. header_file.write("\n".join(header))
  1029. # Generate source.
  1030. source = []
  1031. add_header("utility_functions.cpp", source)
  1032. source_filename = source_gen_folder / "utility_functions.cpp"
  1033. source.append("#include <godot_cpp/variant/utility_functions.hpp>")
  1034. source.append("")
  1035. source.append("#include <godot_cpp/core/error_macros.hpp>")
  1036. source.append("#include <godot_cpp/core/engine_ptrcall.hpp>")
  1037. source.append("")
  1038. source.append("namespace godot {")
  1039. source.append("")
  1040. for function in api["utility_functions"]:
  1041. vararg = "is_vararg" in function and function["is_vararg"]
  1042. function_signature = make_signature("UtilityFunctions", function)
  1043. source.append(function_signature + " {")
  1044. # Function body.
  1045. source.append(
  1046. f'\tstatic GDNativePtrUtilityFunction ___function = internal::gdn_interface->variant_get_ptr_utility_function("{function["name"]}", {function["hash"]});'
  1047. )
  1048. has_return = "return_type" in function and function["return_type"] != "void"
  1049. if has_return:
  1050. source.append(
  1051. f'\tCHECK_METHOD_BIND_RET(___function, {get_default_value_for_type(function["return_type"])});'
  1052. )
  1053. else:
  1054. source.append(f"\tCHECK_METHOD_BIND(___function);")
  1055. function_call = "\t"
  1056. if not vararg:
  1057. if has_return:
  1058. function_call += "return "
  1059. if function["return_type"] == "Object":
  1060. function_call += "internal::_call_utility_ret_obj(___function"
  1061. else:
  1062. function_call += f'internal::_call_utility_ret<{get_gdnative_type(correct_type(function["return_type"]))}>(___function'
  1063. else:
  1064. function_call += "internal::_call_utility_no_ret(___function"
  1065. if "arguments" in function:
  1066. function_call += ", "
  1067. arguments = []
  1068. for argument in function["arguments"]:
  1069. (encode, arg_name) = get_encoded_arg(
  1070. argument["name"],
  1071. argument["type"],
  1072. argument["meta"] if "meta" in argument else None,
  1073. )
  1074. source += encode
  1075. arguments.append(arg_name)
  1076. function_call += ", ".join(arguments)
  1077. else:
  1078. source.append("\tVariant ret;")
  1079. function_call += "___function(&ret, (const GDNativeVariantPtr *)args, arg_count"
  1080. function_call += ");"
  1081. source.append(function_call)
  1082. if vararg and has_return:
  1083. source.append("\treturn ret;")
  1084. source.append("}")
  1085. source.append("")
  1086. source.append("} // namespace godot")
  1087. with source_filename.open("w+") as source_file:
  1088. source_file.write("\n".join(source))
  1089. # Helper functions.
  1090. def camel_to_snake(name):
  1091. name = re.sub("(.)([A-Z][a-z]+)", r"\1_\2", name)
  1092. name = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
  1093. return name.replace("2_D", "2D").replace("3_D", "3D").lower()
  1094. def make_function_parameters(parameters, include_default=False, for_builtin=False, is_vararg=False):
  1095. signature = []
  1096. for index, par in enumerate(parameters):
  1097. parameter = type_for_parameter(par["type"], par["meta"] if "meta" in par else None)
  1098. parameter_name = escape_identifier(par["name"])
  1099. if len(parameter_name) == 0:
  1100. parameter_name = "arg_" + str(index + 1)
  1101. parameter += parameter_name
  1102. if include_default and "default_value" in par and (not for_builtin or par["type"] != "Variant"):
  1103. parameter += " = "
  1104. if is_enum(par["type"]):
  1105. parameter_type = correct_type(par["type"])
  1106. if parameter_type == "void":
  1107. parameter_type = "Variant"
  1108. parameter += f"({parameter_type})"
  1109. parameter += correct_default_value(par["default_value"], par["type"])
  1110. signature.append(parameter)
  1111. if is_vararg:
  1112. signature.append("const Args&... args")
  1113. return ", ".join(signature)
  1114. def type_for_parameter(type_name, meta=None):
  1115. if type_name == "void":
  1116. return "Variant "
  1117. elif is_pod_type(type_name) and type_name != "Nil" or is_enum(type_name):
  1118. return f"{correct_type(type_name, meta)} "
  1119. elif is_variant(type_name) or is_refcounted(type_name):
  1120. return f"const {correct_type(type_name)} &"
  1121. else:
  1122. return f"{correct_type(type_name)}"
  1123. def get_include_path(type_name):
  1124. base_dir = ""
  1125. if type_name == "Object":
  1126. base_dir = "core"
  1127. elif is_variant(type_name):
  1128. base_dir = "variant"
  1129. else:
  1130. base_dir = "classes"
  1131. return f"{base_dir}/{camel_to_snake(type_name)}.hpp"
  1132. def get_encoded_arg(arg_name, type_name, type_meta):
  1133. result = []
  1134. name = escape_identifier(arg_name)
  1135. arg_type = correct_type(type_name)
  1136. if is_pod_type(arg_type):
  1137. result.append(f"\t{get_gdnative_type(arg_type)} {name}_encoded;")
  1138. result.append(f"\tPtrToArg<{correct_type(type_name)}>::encode({name}, &{name}_encoded);")
  1139. name = f"&{name}_encoded"
  1140. elif is_engine_class(type_name):
  1141. name = f"{name}->_owner"
  1142. else:
  1143. name = f"&{name}"
  1144. return (result, name)
  1145. def make_signature(
  1146. class_name, function_data, for_header=False, use_template_get_node=True, for_builtin=False, static=False
  1147. ):
  1148. function_signature = ""
  1149. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1150. if for_header:
  1151. if "is_virtual" in function_data and function_data["is_virtual"]:
  1152. function_signature += "virtual "
  1153. if is_vararg:
  1154. function_signature += "private: "
  1155. if static:
  1156. function_signature += "static "
  1157. return_type = "void"
  1158. return_meta = None
  1159. if "return_type" in function_data:
  1160. return_type = correct_type(function_data["return_type"])
  1161. elif "return_value" in function_data:
  1162. return_type = function_data["return_value"]["type"]
  1163. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1164. function_signature += correct_type(
  1165. return_type,
  1166. return_meta,
  1167. )
  1168. if not function_signature.endswith("*"):
  1169. function_signature += " "
  1170. if not for_header:
  1171. function_signature += f"{class_name}::"
  1172. function_signature += escape_identifier(function_data["name"])
  1173. if is_vararg or (
  1174. not for_builtin and use_template_get_node and class_name == "Node" and function_data["name"] == "get_node"
  1175. ):
  1176. function_signature += "_internal"
  1177. function_signature += "("
  1178. arguments = function_data["arguments"] if "arguments" in function_data else []
  1179. if not is_vararg:
  1180. function_signature += make_function_parameters(arguments, for_header, for_builtin, is_vararg)
  1181. else:
  1182. function_signature += "const Variant **args, GDNativeInt arg_count"
  1183. function_signature += ")"
  1184. if "is_const" in function_data and function_data["is_const"]:
  1185. function_signature += " const"
  1186. return function_signature
  1187. def make_varargs_template(function_data, static=False):
  1188. result = []
  1189. function_signature = "\tpublic: template<class... Args> "
  1190. if static:
  1191. function_signature += "static "
  1192. return_type = "void"
  1193. return_meta = None
  1194. if "return_type" in function_data:
  1195. return_type = correct_type(function_data["return_type"])
  1196. elif "return_value" in function_data:
  1197. return_type = function_data["return_value"]["type"]
  1198. return_meta = function_data["return_value"]["meta"] if "meta" in function_data["return_value"] else None
  1199. function_signature += correct_type(
  1200. return_type,
  1201. return_meta,
  1202. )
  1203. if not function_signature.endswith("*"):
  1204. function_signature += " "
  1205. function_signature += f'{escape_identifier(function_data["name"])}'
  1206. method_arguments = []
  1207. if "arguments" in function_data:
  1208. method_arguments = function_data["arguments"]
  1209. function_signature += "("
  1210. is_vararg = "is_vararg" in function_data and function_data["is_vararg"]
  1211. function_signature += make_function_parameters(method_arguments, include_default=True, is_vararg=is_vararg)
  1212. function_signature += ")"
  1213. if "is_const" in function_data and function_data["is_const"]:
  1214. function_signature += " const"
  1215. function_signature += " {"
  1216. result.append(function_signature)
  1217. args_array = f"\t\tstd::array<Variant, {len(method_arguments)} + sizeof...(Args)> variant_args {{ "
  1218. for argument in method_arguments:
  1219. if argument["type"] == "Variant":
  1220. args_array += argument["name"]
  1221. else:
  1222. args_array += f'Variant({argument["name"]})'
  1223. args_array += ", "
  1224. args_array += "Variant(args)... };"
  1225. result.append(args_array)
  1226. result.append(f"\t\tstd::array<const Variant *, {len(method_arguments)} + sizeof...(Args)> call_args;")
  1227. result.append("\t\tfor(size_t i = 0; i < variant_args.size(); i++) {")
  1228. result.append("\t\t\tcall_args[i] = &variant_args[i];")
  1229. result.append("\t\t}")
  1230. call_line = "\t\t"
  1231. if return_type != "void":
  1232. call_line += "return "
  1233. call_line += f'{escape_identifier(function_data["name"])}_internal(call_args.data(), variant_args.size());'
  1234. result.append(call_line)
  1235. result.append("\t}")
  1236. return result
  1237. # Engine idiosyncrasies.
  1238. def is_pod_type(type_name):
  1239. """
  1240. Those are types for which no class should be generated.
  1241. """
  1242. return type_name in [
  1243. "Nil",
  1244. "void",
  1245. "int",
  1246. "float",
  1247. "bool",
  1248. "double",
  1249. "int32_t",
  1250. "int64_t",
  1251. "uint32_t",
  1252. "uint64_t",
  1253. ]
  1254. def is_included_type(type_name):
  1255. """
  1256. Those are types for which we already have a class file implemented.
  1257. """
  1258. return type_name in [
  1259. "AABB",
  1260. "Basis",
  1261. "Color",
  1262. "Plane",
  1263. "Quaternion",
  1264. "Rect2",
  1265. "Rect2i",
  1266. "Transform2D",
  1267. "Transform3D",
  1268. "Vector2",
  1269. "Vector2i",
  1270. "Vector3",
  1271. "Vector3i",
  1272. ]
  1273. def is_packed_array(type_name):
  1274. """
  1275. Those are types for which we add our extra packed array functions.
  1276. """
  1277. return type_name in [
  1278. "PackedByteArray",
  1279. "PackedColorArray",
  1280. "PackedFloat32Array",
  1281. "PackedFloat64Array",
  1282. "PackedInt32Array",
  1283. "PackedInt64Array",
  1284. "PackedStringArray",
  1285. "PackedVector2Array",
  1286. "PackedVector3Array",
  1287. ]
  1288. def needs_copy_instead_of_move(type_name):
  1289. """
  1290. Those are types which need initialised data or we'll get warning spam so need a copy instead of move.
  1291. """
  1292. return type_name in [
  1293. "Dictionary",
  1294. ]
  1295. def is_enum(type_name):
  1296. return type_name.startswith("enum::")
  1297. def get_enum_class(enum_name: str):
  1298. if "." in enum_name:
  1299. return enum_name.replace("enum::", "").split(".")[0]
  1300. else:
  1301. return "GlobalConstants"
  1302. def get_enum_name(enum_name: str):
  1303. return enum_name.replace("enum::", "").split(".")[-1]
  1304. def is_variant(type_name):
  1305. return type_name == "Variant" or type_name in builtin_classes or type_name == "Nil"
  1306. def is_engine_class(type_name):
  1307. global engine_classes
  1308. return type_name == "Object" or type_name in engine_classes
  1309. def is_refcounted(type_name):
  1310. return type_name in engine_classes and engine_classes[type_name]
  1311. def is_included(type_name, current_type):
  1312. """
  1313. Check if a builtin type should be included.
  1314. This removes Variant and POD types from inclusion, and the current type.
  1315. """
  1316. to_include = get_enum_class(type_name) if is_enum(type_name) else type_name
  1317. if to_include == current_type or is_pod_type(to_include):
  1318. return False
  1319. if to_include == "GlobalConstants" or to_include == "UtilityFunctions":
  1320. return True
  1321. return is_engine_class(to_include) or is_variant(to_include)
  1322. def correct_default_value(value, type_name):
  1323. value_map = {
  1324. "null": "nullptr",
  1325. '""': "String()",
  1326. '&""': "StringName()",
  1327. "[]": "Array()",
  1328. "{}": "Dictionary()",
  1329. "Transform2D(1, 0, 0, 1, 0, 0)": "Transform2D()", # Default transform.
  1330. "Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)": "Transform3D()", # Default transform.
  1331. }
  1332. if value in value_map:
  1333. return value_map[value]
  1334. if value == "":
  1335. return f"{type_name}()"
  1336. return value
  1337. def correct_type(type_name, meta=None):
  1338. type_conversion = {"float": "double", "int": "int64_t", "Nil": "Variant"}
  1339. if meta != None:
  1340. if "int" in meta:
  1341. return f"{meta}_t"
  1342. elif meta in type_conversion:
  1343. return type_conversion[type_name]
  1344. else:
  1345. return meta
  1346. if type_name in type_conversion:
  1347. return type_conversion[type_name]
  1348. if is_enum(type_name):
  1349. base_class = get_enum_class(type_name)
  1350. if base_class == "GlobalConstants":
  1351. return f"{get_enum_name(type_name)}"
  1352. return f"{base_class}::{get_enum_name(type_name)}"
  1353. if is_refcounted(type_name):
  1354. return f"Ref<{type_name}>"
  1355. if type_name == "Object" or is_engine_class(type_name):
  1356. return f"{type_name} *"
  1357. if type_name.endswith("*"):
  1358. return f"{type_name[:-1]} *"
  1359. return type_name
  1360. def get_gdnative_type(type_name):
  1361. type_conversion_map = {
  1362. "bool": "int8_t",
  1363. "uint8_t": "int64_t",
  1364. "int8_t": "int64_t",
  1365. "uint16_t": "int64_t",
  1366. "int16_t": "int64_t",
  1367. "uint32_t": "int64_t",
  1368. "int32_t": "int64_t",
  1369. "int": "int64_t",
  1370. "float": "double",
  1371. }
  1372. if type_name in type_conversion_map:
  1373. return type_conversion_map[type_name]
  1374. return type_name
  1375. def escape_identifier(id):
  1376. cpp_keywords_map = {
  1377. "class": "_class",
  1378. "char": "_char",
  1379. "short": "_short",
  1380. "bool": "_bool",
  1381. "int": "_int",
  1382. "default": "_default",
  1383. "case": "_case",
  1384. "switch": "_switch",
  1385. "export": "_export",
  1386. "template": "_template",
  1387. "new": "new_",
  1388. "operator": "_operator",
  1389. "typeof": "type_of",
  1390. "typename": "type_name",
  1391. }
  1392. if id in cpp_keywords_map:
  1393. return cpp_keywords_map[id]
  1394. return id
  1395. def get_operator_id_name(op):
  1396. op_id_map = {
  1397. "==": "equal",
  1398. "!=": "not_equal",
  1399. "<": "less",
  1400. "<=": "less_equal",
  1401. ">": "greater",
  1402. ">=": "greater_equal",
  1403. "+": "add",
  1404. "-": "subtract",
  1405. "*": "multiply",
  1406. "/": "divide",
  1407. "unary-": "negate",
  1408. "unary+": "positive",
  1409. "%": "module",
  1410. "<<": "shift_left",
  1411. ">>": "shift_right",
  1412. "&": "bit_and",
  1413. "|": "bit_or",
  1414. "^": "bit_xor",
  1415. "~": "bit_negate",
  1416. "and": "and",
  1417. "or": "or",
  1418. "xor": "xor",
  1419. "not": "not",
  1420. "and": "and",
  1421. "in": "in",
  1422. }
  1423. return op_id_map[op]
  1424. def get_default_value_for_type(type_name):
  1425. if type_name == "int":
  1426. return "0"
  1427. if type_name == "float":
  1428. return "0.0"
  1429. if type_name == "bool":
  1430. return "false"
  1431. if is_enum(type_name):
  1432. return f"{correct_type(type_name)}(0)"
  1433. if is_variant(type_name):
  1434. return f"{type_name}()"
  1435. if is_refcounted(type_name):
  1436. return f"Ref<{type_name}>()"
  1437. return "nullptr"
  1438. header = """\
  1439. /*************************************************************************/
  1440. /* $filename */
  1441. /*************************************************************************/
  1442. /* This file is part of: */
  1443. /* GODOT ENGINE */
  1444. /* https://godotengine.org */
  1445. /*************************************************************************/
  1446. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  1447. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  1448. /* */
  1449. /* Permission is hereby granted, free of charge, to any person obtaining */
  1450. /* a copy of this software and associated documentation files (the */
  1451. /* "Software"), to deal in the Software without restriction, including */
  1452. /* without limitation the rights to use, copy, modify, merge, publish, */
  1453. /* distribute, sublicense, and/or sell copies of the Software, and to */
  1454. /* permit persons to whom the Software is furnished to do so, subject to */
  1455. /* the following conditions: */
  1456. /* */
  1457. /* The above copyright notice and this permission notice shall be */
  1458. /* included in all copies or substantial portions of the Software. */
  1459. /* */
  1460. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  1461. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  1462. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  1463. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  1464. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  1465. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  1466. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  1467. /*************************************************************************/
  1468. """
  1469. def add_header(filename, lines):
  1470. desired_length = len(header.split("\n")[0])
  1471. pad_spaces = desired_length - 6 - len(filename)
  1472. for num, line in enumerate(header.split("\n")):
  1473. if num == 1:
  1474. new_line = f"/* {filename}{' ' * pad_spaces}*/"
  1475. lines.append(new_line)
  1476. else:
  1477. lines.append(line)
  1478. lines.append("// THIS FILE IS GENERATED. EDITS WILL BE LOST.")
  1479. lines.append("")