binding_generator.py 72 KB

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