binding_generator.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. #!/usr/bin/env python
  2. from __future__ import print_function
  3. import json
  4. import os
  5. import errno
  6. # Convenience function for using template get_node
  7. def correct_method_name(method_list):
  8. for method in method_list:
  9. if method["name"] == "get_node":
  10. method["name"] = "get_node_internal"
  11. classes = []
  12. def print_file_list(api_filepath, output_dir, headers=False, sources=False):
  13. global classes
  14. end = ';'
  15. with open(api_filepath) as api_file:
  16. classes = json.load(api_file)
  17. include_gen_folder = os.path.join(output_dir, 'include', 'gen')
  18. source_gen_folder = os.path.join(output_dir, 'src', 'gen')
  19. for _class in classes:
  20. header_filename = os.path.join(include_gen_folder, strip_name(_class["name"]) + ".hpp")
  21. source_filename = os.path.join(source_gen_folder, strip_name(_class["name"]) + ".cpp")
  22. if headers:
  23. print(header_filename, end=end)
  24. if sources:
  25. print(source_filename, end=end)
  26. icall_header_filename = os.path.join(include_gen_folder, '__icalls.hpp')
  27. register_types_filename = os.path.join(source_gen_folder, '__register_types.cpp')
  28. init_method_bindings_filename = os.path.join(source_gen_folder, '__init_method_bindings.cpp')
  29. if headers:
  30. print(icall_header_filename, end=end)
  31. if sources:
  32. print(register_types_filename, end=end)
  33. print(init_method_bindings_filename, end=end)
  34. def generate_bindings(api_filepath, use_template_get_node, output_dir="."):
  35. global classes
  36. with open(api_filepath) as api_file:
  37. classes = json.load(api_file)
  38. icalls = set()
  39. include_gen_folder = os.path.join(output_dir, 'include', 'gen')
  40. source_gen_folder = os.path.join(output_dir, 'src', 'gen')
  41. try:
  42. os.makedirs(include_gen_folder)
  43. except os.error as e:
  44. if e.errno == errno.EEXIST:
  45. print(include_gen_folder + ": " + os.strerror(e.errno))
  46. else:
  47. exit(1)
  48. try:
  49. os.makedirs(source_gen_folder)
  50. except os.error as e:
  51. if e.errno == errno.EEXIST:
  52. print(source_gen_folder + ": " + os.strerror(e.errno))
  53. else:
  54. exit(1)
  55. for c in classes:
  56. # print(c['name'])
  57. used_classes = get_used_classes(c)
  58. if use_template_get_node and c["name"] == "Node":
  59. correct_method_name(c["methods"])
  60. header = generate_class_header(used_classes, c, use_template_get_node)
  61. impl = generate_class_implementation(icalls, used_classes, c, use_template_get_node)
  62. header_filename = os.path.join(include_gen_folder, strip_name(c["name"]) + ".hpp")
  63. with open(header_filename, "w+") as header_file:
  64. header_file.write(header)
  65. source_filename = os.path.join(source_gen_folder, strip_name(c["name"]) + ".cpp")
  66. with open(source_filename, "w+") as source_file:
  67. source_file.write(impl)
  68. icall_header_filename = os.path.join(include_gen_folder, '__icalls.hpp')
  69. with open(icall_header_filename, "w+") as icall_header_file:
  70. icall_header_file.write(generate_icall_header(icalls))
  71. register_types_filename = os.path.join(source_gen_folder, '__register_types.cpp')
  72. with open(register_types_filename, "w+") as register_types_file:
  73. register_types_file.write(generate_type_registry(classes))
  74. init_method_bindings_filename = os.path.join(source_gen_folder, '__init_method_bindings.cpp')
  75. with open(init_method_bindings_filename, "w+") as init_method_bindings_file:
  76. init_method_bindings_file.write(generate_init_method_bindings(classes))
  77. def is_reference_type(t):
  78. for c in classes:
  79. if c['name'] != t:
  80. continue
  81. if c['is_reference']:
  82. return True
  83. return False
  84. def make_gdnative_type(t, ref_allowed):
  85. if is_enum(t):
  86. return remove_enum_prefix(t) + " "
  87. elif is_class_type(t):
  88. if is_reference_type(t) and ref_allowed:
  89. return "Ref<" + strip_name(t) + "> "
  90. else:
  91. return strip_name(t) + " *"
  92. else:
  93. if t == "int":
  94. return "int64_t "
  95. if t == "float" or t == "real":
  96. return "real_t "
  97. return strip_name(t) + " "
  98. def generate_class_header(used_classes, c, use_template_get_node):
  99. source = []
  100. source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  101. source.append("#define GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  102. source.append("")
  103. source.append("")
  104. source.append("#include <gdnative_api_struct.gen.h>")
  105. source.append("#include <cstdint>")
  106. source.append("")
  107. source.append("#include <core/CoreTypes.hpp>")
  108. class_name = strip_name(c["name"])
  109. # Ref<T> is not included in object.h in Godot either,
  110. # so don't include it here because it's not needed
  111. if class_name != "Object" and class_name != "Reference":
  112. source.append("#include <core/Ref.hpp>")
  113. ref_allowed = True
  114. else:
  115. source.append("#include <core/TagDB.hpp>")
  116. ref_allowed = False
  117. included = []
  118. for used_class in used_classes:
  119. if is_enum(used_class) and is_nested_type(used_class):
  120. used_class_name = remove_enum_prefix(extract_nested_type(used_class))
  121. if used_class_name not in included:
  122. included.append(used_class_name)
  123. source.append("#include \"" + used_class_name + ".hpp\"")
  124. elif is_enum(used_class) and is_nested_type(used_class) and not is_nested_type(used_class, class_name):
  125. used_class_name = remove_enum_prefix(used_class)
  126. if used_class_name not in included:
  127. included.append(used_class_name)
  128. source.append("#include \"" + used_class_name + ".hpp\"")
  129. source.append("")
  130. if c["base_class"] != "":
  131. source.append("#include \"" + strip_name(c["base_class"]) + ".hpp\"")
  132. source.append("namespace godot {")
  133. source.append("")
  134. for used_type in used_classes:
  135. if is_enum(used_type) or is_nested_type(used_type, class_name):
  136. continue
  137. else:
  138. source.append("class " + strip_name(used_type) + ";")
  139. source.append("")
  140. vararg_templates = ""
  141. # generate the class definition here
  142. source.append("class " + class_name + (" : public _Wrapped" if c["base_class"] == "" else (" : public " + strip_name(c["base_class"])) ) + " {")
  143. if c["base_class"] == "":
  144. source.append("public: enum { ___CLASS_IS_SCRIPT = 0, };")
  145. source.append("")
  146. source.append("private:")
  147. if c["singleton"]:
  148. source.append("\tstatic " + class_name + " *_singleton;")
  149. source.append("")
  150. source.append("\t" + class_name + "();")
  151. source.append("")
  152. # Generate method table
  153. source.append("\tstruct ___method_bindings {")
  154. for method in c["methods"]:
  155. source.append("\t\tgodot_method_bind *mb_" + method["name"] + ";")
  156. source.append("\t};")
  157. source.append("\tstatic ___method_bindings ___mb;")
  158. source.append("\tstatic void *_detail_class_tag;")
  159. source.append("")
  160. source.append("public:")
  161. source.append("\tstatic void ___init_method_bindings();")
  162. # class id from core engine for casting
  163. source.append("\tinline static size_t ___get_id() { return (size_t)_detail_class_tag; }")
  164. source.append("")
  165. if c["singleton"]:
  166. source.append("\tstatic inline " + class_name + " *get_singleton()")
  167. source.append("\t{")
  168. source.append("\t\tif (!" + class_name + "::_singleton) {")
  169. source.append("\t\t\t" + class_name + "::_singleton = new " + class_name + ";")
  170. source.append("\t\t}")
  171. source.append("\t\treturn " + class_name + "::_singleton;")
  172. source.append("\t}")
  173. source.append("")
  174. # godot::api->godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");"
  175. # class name:
  176. # Two versions needed needed because when the user implements a custom class,
  177. # we want to override `___get_class_name` while `___get_godot_class_name` can keep returning the base name
  178. source.append("\tstatic inline const char *___get_class_name() { return (const char *) \"" + strip_name(c["name"]) + "\"; }")
  179. source.append("\tstatic inline const char *___get_godot_class_name() { return (const char *) \"" + strip_name(c["name"]) + "\"; }")
  180. source.append("\tstatic inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; }")
  181. enum_values = []
  182. source.append("\n\t// enums")
  183. for enum in c["enums"]:
  184. source.append("\tenum " + strip_name(enum["name"]) + " {")
  185. for value in enum["values"]:
  186. source.append("\t\t" + remove_nested_type_prefix(value) + " = " + str(enum["values"][value]) + ",")
  187. enum_values.append(value)
  188. source.append("\t};")
  189. source.append("\n\t// constants")
  190. for name in c["constants"]:
  191. if name not in enum_values:
  192. source.append("\tconst static int " + name + " = " + str(c["constants"][name]) + ";")
  193. if c["instanciable"]:
  194. source.append("")
  195. source.append("")
  196. source.append("\tstatic " + class_name + " *_new();")
  197. source.append("\n\t// methods")
  198. if class_name == "Object":
  199. source.append("#ifndef GODOT_CPP_NO_OBJECT_CAST")
  200. source.append("\ttemplate<class T>")
  201. source.append("\tstatic T *cast_to(const Object *obj);")
  202. source.append("#endif")
  203. source.append("")
  204. for method in c["methods"]:
  205. method_signature = ""
  206. # TODO decide what to do about virtual methods
  207. # method_signature += "virtual " if method["is_virtual"] else ""
  208. method_signature += make_gdnative_type(method["return_type"], ref_allowed)
  209. method_name = escape_cpp(method["name"])
  210. method_signature += method_name + "("
  211. has_default_argument = False
  212. method_arguments = ""
  213. for i, argument in enumerate(method["arguments"]):
  214. method_signature += "const " + make_gdnative_type(argument["type"], ref_allowed)
  215. argument_name = escape_cpp(argument["name"])
  216. method_signature += argument_name
  217. method_arguments += argument_name
  218. # default arguments
  219. def escape_default_arg(_type, default_value):
  220. if _type == "Color":
  221. return "Color(" + default_value + ")"
  222. if _type == "bool" or _type == "int":
  223. return default_value.lower()
  224. if _type == "Array":
  225. return "Array()"
  226. if _type in ["PoolVector2Array", "PoolStringArray", "PoolVector3Array", "PoolColorArray", "PoolIntArray", "PoolRealArray"]:
  227. return _type + "()"
  228. if _type == "Vector2":
  229. return "Vector2" + default_value
  230. if _type == "Vector3":
  231. return "Vector3" + default_value
  232. if _type == "Transform":
  233. return "Transform()"
  234. if _type == "Transform2D":
  235. return "Transform2D()"
  236. if _type == "Rect2":
  237. return "Rect2" + default_value
  238. if _type == "Variant":
  239. return "Variant()" if default_value == "Null" else default_value
  240. if _type == "String":
  241. return "\"" + default_value + "\""
  242. if _type == "RID":
  243. return "RID()"
  244. if default_value == "Null" or default_value == "[Object:null]":
  245. return "nullptr"
  246. return default_value
  247. if argument["has_default_value"] or has_default_argument:
  248. method_signature += " = " + escape_default_arg(argument["type"], argument["default_value"])
  249. has_default_argument = True
  250. if i != len(method["arguments"]) - 1:
  251. method_signature += ", "
  252. method_arguments += ","
  253. if method["has_varargs"]:
  254. if len(method["arguments"]) > 0:
  255. method_signature += ", "
  256. method_arguments += ", "
  257. vararg_templates += "\ttemplate <class... Args> " + method_signature + "Args... args){\n\t\treturn " + method_name + "(" + method_arguments + "Array::make(args...));\n\t}\n"""
  258. method_signature += "const Array& __var_args = Array()"
  259. method_signature += ")" + (" const" if method["is_const"] else "")
  260. source.append("\t" + method_signature + ";")
  261. source.append(vararg_templates)
  262. if use_template_get_node and class_name == "Node":
  263. # Extra definition for template get_node that calls the renamed get_node_internal; has a default template parameter for backwards compatibility.
  264. source.append("\ttemplate <class T = Node>")
  265. source.append("\tT *get_node(const NodePath path) const {")
  266. source.append("\t\treturn Object::cast_to<T>(get_node_internal(path));")
  267. source.append("\t}")
  268. source.append("};")
  269. source.append("")
  270. # ...And a specialized version so we don't unnecessarily cast when using the default.
  271. source.append("template <>")
  272. source.append("inline Node *Node::get_node<Node>(const NodePath path) const {")
  273. source.append("\treturn get_node_internal(path);")
  274. source.append("}")
  275. source.append("")
  276. else:
  277. source.append("};")
  278. source.append("")
  279. source.append("}")
  280. source.append("")
  281. source.append("#endif")
  282. return "\n".join(source)
  283. def generate_class_implementation(icalls, used_classes, c, use_template_get_node):
  284. class_name = strip_name(c["name"])
  285. ref_allowed = class_name != "Object" and class_name != "Reference"
  286. source = []
  287. source.append("#include \"" + class_name + ".hpp\"")
  288. source.append("")
  289. source.append("")
  290. source.append("#include <core/GodotGlobal.hpp>")
  291. source.append("#include <core/CoreTypes.hpp>")
  292. source.append("#include <core/Ref.hpp>")
  293. source.append("#include <core/Godot.hpp>")
  294. source.append("")
  295. source.append("#include \"__icalls.hpp\"")
  296. source.append("")
  297. source.append("")
  298. for used_class in used_classes:
  299. if is_enum(used_class):
  300. continue
  301. else:
  302. source.append("#include \"" + strip_name(used_class) + ".hpp\"")
  303. source.append("")
  304. source.append("")
  305. source.append("namespace godot {")
  306. core_object_name = "this"
  307. source.append("")
  308. source.append("")
  309. if c["singleton"]:
  310. source.append("" + class_name + " *" + class_name + "::_singleton = NULL;")
  311. source.append("")
  312. source.append("")
  313. # FIXME Test if inlining has a huge impact on binary size
  314. source.append(class_name + "::" + class_name + "() {")
  315. source.append("\t_owner = godot::api->godot_global_get_singleton((char *) \"" + strip_name(c["name"]) + "\");")
  316. source.append("}")
  317. source.append("")
  318. source.append("")
  319. # Method table initialization
  320. source.append(class_name + "::___method_bindings " + class_name + "::___mb = {};")
  321. source.append("")
  322. source.append("void *" + class_name + "::_detail_class_tag = nullptr;")
  323. source.append("")
  324. source.append("void " + class_name + "::___init_method_bindings() {")
  325. for method in c["methods"]:
  326. source.append("\t___mb.mb_" + method["name"] + " = godot::api->godot_method_bind_get_method(\"" + c["name"] + "\", \"" + ("get_node" if use_template_get_node and method["name"] == "get_node_internal" else method["name"]) + "\");")
  327. source.append("\tgodot_string_name class_name;")
  328. source.append("\tgodot::api->godot_string_name_new_data(&class_name, \"" + c["name"] + "\");")
  329. source.append("\t_detail_class_tag = godot::core_1_2_api->godot_get_class_tag(&class_name);")
  330. source.append("\tgodot::api->godot_string_name_destroy(&class_name);")
  331. source.append("}")
  332. source.append("")
  333. if c["instanciable"]:
  334. source.append(class_name + " *" + strip_name(c["name"]) + "::_new()")
  335. source.append("{")
  336. source.append("\treturn (" + class_name + " *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, godot::api->godot_get_class_constructor((char *)\"" + c["name"] + "\")());")
  337. source.append("}")
  338. for method in c["methods"]:
  339. method_signature = ""
  340. method_signature += make_gdnative_type(method["return_type"], ref_allowed)
  341. method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
  342. for i, argument in enumerate(method["arguments"]):
  343. method_signature += "const " + make_gdnative_type(argument["type"], ref_allowed)
  344. method_signature += escape_cpp(argument["name"])
  345. if i != len(method["arguments"]) - 1:
  346. method_signature += ", "
  347. if method["has_varargs"]:
  348. if len(method["arguments"]) > 0:
  349. method_signature += ", "
  350. method_signature += "const Array& __var_args"
  351. method_signature += ")" + (" const" if method["is_const"] else "")
  352. source.append(method_signature + " {")
  353. if method["name"] == "free":
  354. # dirty hack because Object::free is marked virtual but doesn't actually exist...
  355. source.append("\tgodot::api->godot_object_destroy(_owner);")
  356. source.append("}")
  357. source.append("")
  358. continue
  359. return_statement = ""
  360. return_type_is_ref = is_reference_type(method["return_type"]) and ref_allowed
  361. if method["return_type"] != "void":
  362. if is_class_type(method["return_type"]):
  363. if is_enum(method["return_type"]):
  364. return_statement += "return (" + remove_enum_prefix(method["return_type"]) + ") "
  365. elif return_type_is_ref:
  366. return_statement += "return Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor("
  367. else:
  368. return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
  369. else:
  370. return_statement += "return "
  371. def get_icall_type_name(name):
  372. if is_enum(name):
  373. return "int"
  374. if is_class_type(name):
  375. return "Object"
  376. return name
  377. if method["has_varargs"]:
  378. if len(method["arguments"]) != 0:
  379. source.append("\tVariant __given_args[" + str(len(method["arguments"])) + "];")
  380. for i, argument in enumerate(method["arguments"]):
  381. source.append("\tgodot::api->godot_variant_new_nil((godot_variant *) &__given_args[" + str(i) + "]);")
  382. source.append("")
  383. for i, argument in enumerate(method["arguments"]):
  384. source.append("\t__given_args[" + str(i) + "] = " + escape_cpp(argument["name"]) + ";")
  385. source.append("")
  386. size = ""
  387. if method["has_varargs"]:
  388. size = "(__var_args.size() + " + str(len(method["arguments"])) + ")"
  389. else:
  390. size = "(" + str(len(method["arguments"])) + ")"
  391. source.append("\tgodot_variant **__args = (godot_variant **) alloca(sizeof(godot_variant *) * " + size + ");")
  392. source.append("")
  393. for i, argument in enumerate(method["arguments"]):
  394. source.append("\t__args[" + str(i) + "] = (godot_variant *) &__given_args[" + str(i) + "];")
  395. source.append("")
  396. if method["has_varargs"]:
  397. source.append("\tfor (int i = 0; i < __var_args.size(); i++) {")
  398. source.append("\t\t__args[i + " + str(len(method["arguments"])) + "] = (godot_variant *) &((Array &) __var_args)[i];")
  399. source.append("\t}")
  400. source.append("")
  401. source.append("\tVariant __result;")
  402. source.append("\t*(godot_variant *) &__result = godot::api->godot_method_bind_call(___mb.mb_" + method["name"] + ", ((const Object *) " + core_object_name + ")->_owner, (const godot_variant **) __args, " + size + ", nullptr);")
  403. source.append("")
  404. if is_class_type(method["return_type"]):
  405. source.append("\tObject *obj = Object::___get_from_variant(__result);")
  406. source.append("\tif (obj->has_method(\"reference\"))")
  407. source.append("\t\tobj->callv(\"reference\", Array());")
  408. source.append("")
  409. for i, argument in enumerate(method["arguments"]):
  410. source.append("\tgodot::api->godot_variant_destroy((godot_variant *) &__given_args[" + str(i) + "]);")
  411. source.append("")
  412. if method["return_type"] != "void":
  413. cast = ""
  414. if is_class_type(method["return_type"]):
  415. if return_type_is_ref:
  416. cast += "Ref<" + strip_name(method["return_type"]) + ">::__internal_constructor(__result);"
  417. else:
  418. cast += "(" + strip_name(method["return_type"]) + " *) " + strip_name(method["return_type"] + "::___get_from_variant(") + "__result);"
  419. else:
  420. cast += "__result;"
  421. source.append("\treturn " + cast)
  422. else:
  423. args = []
  424. for arg in method["arguments"]:
  425. args.append(get_icall_type_name(arg["type"]))
  426. icall_ret_type = get_icall_type_name(method["return_type"])
  427. icall_sig = tuple((icall_ret_type, tuple(args)))
  428. icalls.add(icall_sig)
  429. icall_name = get_icall_name(icall_sig)
  430. return_statement += icall_name + "(___mb.mb_" + method["name"] + ", (const Object *) " + core_object_name
  431. for arg in method["arguments"]:
  432. arg_is_ref = is_reference_type(arg["type"]) and ref_allowed
  433. return_statement += ", " + escape_cpp(arg["name"]) + (".ptr()" if arg_is_ref else "")
  434. return_statement += ")"
  435. if return_type_is_ref:
  436. return_statement += ")"
  437. source.append("\t" + return_statement + ";")
  438. source.append("}")
  439. source.append("")
  440. source.append("}")
  441. return "\n".join(source)
  442. def generate_icall_header(icalls):
  443. source = []
  444. source.append("#ifndef GODOT_CPP__ICALLS_HPP")
  445. source.append("#define GODOT_CPP__ICALLS_HPP")
  446. source.append("")
  447. source.append("#include <gdnative_api_struct.gen.h>")
  448. source.append("#include <stdint.h>")
  449. source.append("")
  450. source.append("#include <core/GodotGlobal.hpp>")
  451. source.append("#include <core/CoreTypes.hpp>")
  452. source.append("#include \"Object.hpp\"")
  453. source.append("")
  454. source.append("")
  455. source.append("namespace godot {")
  456. source.append("")
  457. for icall in icalls:
  458. ret_type = icall[0]
  459. args = icall[1]
  460. method_signature = "static inline "
  461. method_signature += get_icall_return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, const Object *inst"
  462. for i, arg in enumerate(args):
  463. method_signature += ", const "
  464. if is_core_type(arg):
  465. method_signature += arg + "&"
  466. elif arg == "int":
  467. method_signature += "int64_t "
  468. elif arg == "float":
  469. method_signature += "double "
  470. elif is_primitive(arg):
  471. method_signature += arg + " "
  472. else:
  473. method_signature += "Object *"
  474. method_signature += "arg" + str(i)
  475. method_signature += ")"
  476. source.append(method_signature + " {")
  477. if ret_type != "void":
  478. source.append("\t" + ("godot_object *" if is_class_type(ret_type) else get_icall_return_type(ret_type)) + "ret;")
  479. if is_class_type(ret_type):
  480. source.append("\tret = nullptr;")
  481. source.append("\tconst void *args[" + ("1" if len(args) == 0 else "") + "] = {")
  482. for i, arg in enumerate(args):
  483. wrapped_argument = "\t\t"
  484. if is_primitive(arg) or is_core_type(arg):
  485. wrapped_argument += "(void *) &arg" + str(i)
  486. else:
  487. wrapped_argument += "(void *) (arg" + str(i) + ") ? arg" + str(i) + "->_owner : nullptr"
  488. wrapped_argument += ","
  489. source.append(wrapped_argument)
  490. source.append("\t};")
  491. source.append("")
  492. source.append("\tgodot::api->godot_method_bind_ptrcall(mb, inst->_owner, args, " + ("nullptr" if ret_type == "void" else "&ret") + ");")
  493. if ret_type != "void":
  494. if is_class_type(ret_type):
  495. source.append("\tif (ret) {")
  496. source.append("\t\treturn (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, ret);")
  497. source.append("\t}")
  498. source.append("")
  499. source.append("\treturn (Object *) ret;")
  500. else:
  501. source.append("\treturn ret;")
  502. source.append("}")
  503. source.append("")
  504. source.append("}")
  505. source.append("")
  506. source.append("#endif")
  507. return "\n".join(source)
  508. def generate_type_registry(classes):
  509. source = []
  510. source.append("#include \"TagDB.hpp\"")
  511. source.append("#include <typeinfo>")
  512. source.append("\n")
  513. for c in classes:
  514. source.append("#include <" + strip_name(c["name"]) + ".hpp>")
  515. source.append("")
  516. source.append("")
  517. source.append("namespace godot {")
  518. source.append("void ___register_types()")
  519. source.append("{")
  520. for c in classes:
  521. class_name = strip_name(c["name"])
  522. base_class_name = strip_name(c["base_class"])
  523. class_type_hash = "typeid(" + class_name + ").hash_code()"
  524. base_class_type_hash = "typeid(" + base_class_name + ").hash_code()"
  525. if base_class_name == "":
  526. base_class_type_hash = "0"
  527. source.append("\tgodot::_TagDB::register_global_type(\"" + c["name"] + "\", " + class_type_hash + ", " + base_class_type_hash + ");")
  528. source.append("}")
  529. source.append("")
  530. source.append("}")
  531. return "\n".join(source)
  532. def generate_init_method_bindings(classes):
  533. source = []
  534. for c in classes:
  535. source.append("#include <" + strip_name(c["name"]) + ".hpp>")
  536. source.append("")
  537. source.append("")
  538. source.append("namespace godot {")
  539. source.append("void ___init_method_bindings()")
  540. source.append("{")
  541. for c in classes:
  542. source.append("\t" + strip_name(c["name"]) + "::___init_method_bindings();")
  543. source.append("}")
  544. source.append("")
  545. source.append("}")
  546. return "\n".join(source)
  547. def get_icall_return_type(t):
  548. if is_class_type(t):
  549. return "Object *"
  550. if t == "int":
  551. return "int64_t "
  552. if t == "float" or t == "real":
  553. return "double "
  554. return t + " "
  555. def get_icall_name(sig):
  556. ret_type = sig[0]
  557. args = sig[1]
  558. name = "___godot_icall_"
  559. name += strip_name(ret_type)
  560. for arg in args:
  561. name += "_" + strip_name(arg)
  562. return name
  563. def get_used_classes(c):
  564. classes = []
  565. for method in c["methods"]:
  566. if is_class_type(method["return_type"]) and not (method["return_type"] in classes):
  567. classes.append(method["return_type"])
  568. for arg in method["arguments"]:
  569. if is_class_type(arg["type"]) and not (arg["type"] in classes):
  570. classes.append(arg["type"])
  571. return classes
  572. def strip_name(name):
  573. if len(name) == 0:
  574. return name
  575. if name[0] == '_':
  576. return name[1:]
  577. return name
  578. def extract_nested_type(nested_type):
  579. return strip_name(nested_type[:nested_type.find("::")])
  580. def remove_nested_type_prefix(name):
  581. return name if name.find("::") == -1 else strip_name(name[name.find("::") + 2:])
  582. def remove_enum_prefix(name):
  583. return strip_name(name[name.find("enum.") + 5:])
  584. def is_nested_type(name, type = ""):
  585. return name.find(type + "::") != -1
  586. def is_enum(name):
  587. return name.find("enum.") == 0
  588. def is_class_type(name):
  589. return not is_core_type(name) and not is_primitive(name)
  590. def is_core_type(name):
  591. core_types = ["Array",
  592. "Basis",
  593. "Color",
  594. "Dictionary",
  595. "Error",
  596. "NodePath",
  597. "Plane",
  598. "PoolByteArray",
  599. "PoolIntArray",
  600. "PoolRealArray",
  601. "PoolStringArray",
  602. "PoolVector2Array",
  603. "PoolVector3Array",
  604. "PoolColorArray",
  605. "PoolIntArray",
  606. "PoolRealArray",
  607. "Quat",
  608. "Rect2",
  609. "AABB",
  610. "RID",
  611. "String",
  612. "Transform",
  613. "Transform2D",
  614. "Variant",
  615. "Vector2",
  616. "Vector3"]
  617. return name in core_types
  618. def is_primitive(name):
  619. core_types = ["int", "bool", "real", "float", "void"]
  620. return name in core_types
  621. def escape_cpp(name):
  622. escapes = {
  623. "class": "_class",
  624. "char": "_char",
  625. "short": "_short",
  626. "bool": "_bool",
  627. "int": "_int",
  628. "default": "_default",
  629. "case": "_case",
  630. "switch": "_switch",
  631. "export": "_export",
  632. "template": "_template",
  633. "new": "new_",
  634. "operator": "_operator",
  635. "typename": "_typename"
  636. }
  637. if name in escapes:
  638. return escapes[name]
  639. return name