binding_generator.py 110 KB

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