binding_generator.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. #!python
  2. import json
  3. # comment.
  4. def generate_bindings(path):
  5. classes = json.load(open(path))
  6. icalls = set()
  7. for c in classes:
  8. # print c['name']
  9. used_classes = get_used_classes(c)
  10. header = generate_class_header(used_classes, c)
  11. impl = generate_class_implementation(icalls, used_classes, c)
  12. header_file = open("include/" + strip_name(c["name"]) + ".hpp", "w+")
  13. header_file.write(header)
  14. source_file = open("src/" + strip_name(c["name"]) + ".cpp", "w+")
  15. source_file.write(impl)
  16. icall_header_file = open("src/__icalls.hpp", "w+")
  17. icall_header_file.write(generate_icall_header(icalls))
  18. icall_source_file = open("src/__icalls.cpp", "w+")
  19. icall_source_file.write(generate_icall_implementation(icalls))
  20. def generate_class_header(used_classes, c):
  21. source = []
  22. source.append("#ifndef GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  23. source.append("#define GODOT_CPP_" + strip_name(c["name"]).upper() + "_HPP")
  24. source.append("")
  25. source.append("#if defined(_WIN32) && defined(_GD_CPP_BINDING_IMPL)")
  26. source.append("# define GD_CPP_BINDING_API __declspec(dllexport)")
  27. source.append("#elif defined(_WIN32)")
  28. source.append("# define GD_CPP_BINDING_API __declspec(dllimport)")
  29. source.append("#else")
  30. source.append("# define GD_CPP_BINDING_API")
  31. source.append("#endif");
  32. source.append("")
  33. source.append("")
  34. source.append("")
  35. source.append("")
  36. source.append("#include <godot.h>")
  37. source.append("")
  38. source.append("#include <CoreTypes.hpp>")
  39. if c["base_class"] != "":
  40. source.append("#include <" + strip_name(c["base_class"]) + ".hpp>")
  41. source.append("namespace godot {")
  42. source.append("")
  43. for used_type in used_classes:
  44. source.append("class " + strip_name(used_type) + ";")
  45. source.append("")
  46. # generate the class definition here
  47. source.append("class GD_CPP_BINDING_API " + strip_name(c["name"]) + ("" if c["base_class"] == "" else (" : public " + strip_name(c["base_class"])) ) + " {")
  48. source.append("public:")
  49. source.append("")
  50. # ___get_class_name
  51. source.append("\tstatic inline char *___get_class_name() { return (char *) \"" + strip_name(c["name"]) + "\"; }")
  52. source.append("\t// constants")
  53. for name in c["constants"]:
  54. source.append("\tconst static int " + name + " = " + str(c["constants"][name]) + ";")
  55. source.append("")
  56. source.append("\n\t// methods")
  57. for method in c["methods"]:
  58. method_signature = ""
  59. method_signature += "static " if c["singleton"] else ""
  60. method_signature += strip_name(method["return_type"])
  61. method_signature += " *" if is_class_type(method["return_type"]) else " "
  62. method_signature += escape_cpp(method["name"]) + "("
  63. has_default_argument = False
  64. for i, argument in enumerate(method["arguments"]):
  65. method_signature += "const " + argument["type"] + (" *" if is_class_type(argument["type"]) else " ")
  66. method_signature += escape_cpp(argument["name"])
  67. # default arguments
  68. def escape_default_arg(_type, default_value):
  69. if _type == "Color":
  70. return "Color(" + default_value + ")"
  71. if _type == "bool" or _type == "int":
  72. return default_value.lower()
  73. if _type == "Array":
  74. return "Array()"
  75. if _type in ["PoolVector2Array", "PoolStringArray", "PoolVector3Array", "PoolColorArray"]:
  76. return _type + "()"
  77. if _type == "Vector2":
  78. return "Vector2" + default_value
  79. if _type == "Vector3":
  80. return "Vector3" + default_value
  81. if _type == "Transform":
  82. return "Transform()"
  83. if _type == "Transform2D":
  84. return "Transform2D()"
  85. if _type == "Rect2":
  86. return "Rect2" + default_value
  87. if _type == "Variant":
  88. return "Variant()" if default_value == "Null" else default_value
  89. if _type == "String":
  90. return "\"" + default_value + "\""
  91. if _type == "RID":
  92. return "RID()"
  93. if default_value == "Null" or default_value == "[Object:null]":
  94. return "nullptr"
  95. return default_value
  96. if argument["has_default_value"] or has_default_argument:
  97. method_signature += " = " + escape_default_arg(argument["type"], argument["default_value"])
  98. has_default_argument = True
  99. if i != len(method["arguments"]) - 1:
  100. method_signature += ", "
  101. if method["has_varargs"]:
  102. if len(method["arguments"]) > 0:
  103. method_signature += ", "
  104. method_signature += "const Array& __var_args = Array()"
  105. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  106. source.append("\t" + method_signature + ";")
  107. source.append("};")
  108. source.append("")
  109. source.append("}")
  110. source.append("")
  111. source.append("#endif")
  112. return "\n".join(source)
  113. def generate_class_implementation(icalls, used_classes, c):
  114. source = []
  115. source.append("#include <" + strip_name(c["name"]) + ".hpp>")
  116. source.append("")
  117. source.append("")
  118. source.append("#include <CoreTypes.hpp>")
  119. source.append("#include <Godot.hpp>")
  120. source.append("")
  121. source.append("#include \"__icalls.hpp\"")
  122. source.append("")
  123. source.append("")
  124. for used_class in used_classes:
  125. source.append("#include <" + strip_name(used_class) + ".hpp>")
  126. source.append("")
  127. source.append("")
  128. source.append("namespace godot {")
  129. core_object_name = ("___static_object_" + strip_name(c["name"])) if c["singleton"] else "this"
  130. source.append("")
  131. source.append("")
  132. if c["singleton"]:
  133. source.append("static godot_object *" + core_object_name + ";")
  134. source.append("")
  135. source.append("")
  136. # FIXME Test if inlining has a huge impact on binary size
  137. source.append("static inline void ___singleton_init()")
  138. source.append("{")
  139. source.append("\tif (" + core_object_name + " == nullptr) {")
  140. source.append("\t\t" + core_object_name + " = godot_global_get_singleton(\"" + c["name"] + "\");")
  141. source.append("\t}")
  142. source.append("}")
  143. source.append("")
  144. source.append("")
  145. for method in c["methods"]:
  146. method_signature = ""
  147. method_signature += strip_name(method["return_type"])
  148. method_signature += " *" if is_class_type(method["return_type"]) else " "
  149. method_signature += strip_name(c["name"]) + "::" + escape_cpp(method["name"]) + "("
  150. for i, argument in enumerate(method["arguments"]):
  151. method_signature += "const " + argument["type"] + (" *" if is_class_type(argument["type"]) else " ")
  152. method_signature += escape_cpp(argument["name"])
  153. if i != len(method["arguments"]) - 1:
  154. method_signature += ", "
  155. if method["has_varargs"]:
  156. if len(method["arguments"]) > 0:
  157. method_signature += ", "
  158. method_signature += "const Array& __var_args"
  159. method_signature += ")" + (" const" if method["is_const"] and not c["singleton"] else "")
  160. source.append(method_signature + " {")
  161. if c["singleton"]:
  162. source.append("\t___singleton_init();")
  163. source.append("\tstatic godot_method_bind *mb = NULL;")
  164. source.append("\tif (mb == NULL) {")
  165. source.append("\t\tmb = godot_method_bind_get_method(\"" + c["name"] +"\", \"" + method["name"] + "\");")
  166. source.append("\t}")
  167. return_statement = ""
  168. if method["return_type"] != "void":
  169. return_statement += "return " + ("(" + strip_name(method["return_type"]) + " *) " if is_class_type(method["return_type"]) else "")
  170. def get_icall_type_name(name):
  171. if is_class_type(name):
  172. return "Object"
  173. return name
  174. if method["is_virtual"] or method["has_varargs"]:
  175. source.append("\tVariant __given_args[" + str(len(method["arguments"])) + "];")
  176. for i, argument in enumerate(method["arguments"]):
  177. source.append("\tgodot_variant_new_nil((godot_variant *) &__given_args[" + str(i) + "]);")
  178. source.append("")
  179. for i, argument in enumerate(method["arguments"]):
  180. source.append("\t__given_args[" + str(i) + "] = " + escape_cpp(argument["name"]) + ";")
  181. source.append("")
  182. size = ""
  183. if method["has_varargs"]:
  184. size = "(__var_args.size() + " + str(len(method["arguments"])) + ")"
  185. else:
  186. size = "(" + str(len(method["arguments"])) + ")"
  187. source.append("\tgodot_variant **__args = (godot_variant **) alloca(sizeof(godot_variant *) * " + size + ");")
  188. source.append("")
  189. for i, argument in enumerate(method["arguments"]):
  190. source.append("\t__args[" + str(i) + "] = (godot_variant *) &__given_args[" + str(i) + "];")
  191. source.append("")
  192. if method["has_varargs"]:
  193. source.append("\tfor (int i = 0; i < __var_args.size(); i++) {")
  194. source.append("\t\t__args[i + " + str(len(method["arguments"])) + "] = (godot_variant *) &((Array &) __var_args)[i];")
  195. source.append("\t}")
  196. source.append("")
  197. source.append("\tVariant __result;")
  198. source.append("\t*(godot_variant *) &__result = godot_method_bind_call(mb, (godot_object *) " + core_object_name + ", (const godot_variant **) __args, " + size + ", nullptr);")
  199. source.append("")
  200. for i, argument in enumerate(method["arguments"]):
  201. source.append("\tgodot_variant_destroy((godot_variant *) &__given_args[" + str(i) + "]);")
  202. source.append("")
  203. if method["return_type"] != "void":
  204. cast = ""
  205. if is_class_type(method["return_type"]):
  206. cast += "(" + strip_name(method["return_type"]) + " *) (Object *) "
  207. source.append("\treturn " + cast + "__result;")
  208. else:
  209. args = []
  210. for arg in method["arguments"]:
  211. args.append(get_icall_type_name(arg["type"]))
  212. icall_ret_type = get_icall_type_name(method["return_type"])
  213. icall_sig = tuple((icall_ret_type, tuple(args)))
  214. icalls.add(icall_sig)
  215. icall_name = get_icall_name(icall_sig)
  216. return_statement += icall_name + "(mb, (godot_object *) " + core_object_name
  217. for arg in method["arguments"]:
  218. return_statement += ", " + escape_cpp(arg["name"])
  219. return_statement += ")"
  220. source.append("\t" + return_statement + ";")
  221. source.append("}")
  222. source.append("")
  223. source.append("}")
  224. return "\n".join(source)
  225. def generate_icall_header(icalls):
  226. source = []
  227. source.append("#ifndef GODOT_CPP__ICALLS_HPP")
  228. source.append("#define GODOT_CPP__ICALLS_HPP")
  229. source.append("")
  230. source.append("#include <godot.h>")
  231. source.append("")
  232. source.append("")
  233. source.append("#include <CoreTypes.hpp>")
  234. source.append("#include <Object.hpp>")
  235. source.append("")
  236. source.append("")
  237. source.append("namespace godot {")
  238. source.append("")
  239. for icall in icalls:
  240. ret_type = icall[0]
  241. args = icall[1]
  242. method_signature = ""
  243. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  244. for arg in args:
  245. method_signature += ", const "
  246. if is_core_type(arg):
  247. method_signature += arg + "&"
  248. elif is_primitive(arg):
  249. method_signature += arg
  250. else:
  251. method_signature += "Object *"
  252. method_signature += ");"
  253. source.append(method_signature)
  254. source.append("")
  255. source.append("}")
  256. source.append("")
  257. source.append("#endif")
  258. return "\n".join(source)
  259. def generate_icall_implementation(icalls):
  260. source = []
  261. source.append("#include \"__icalls.hpp\"")
  262. source.append("")
  263. source.append("#include <godot.h>")
  264. source.append("")
  265. source.append("")
  266. source.append("#include <CoreTypes.hpp>")
  267. source.append("#include <Object.hpp>")
  268. source.append("")
  269. source.append("")
  270. source.append("using namespace godot;")
  271. source.append("")
  272. for icall in icalls:
  273. ret_type = icall[0]
  274. args = icall[1]
  275. method_signature = ""
  276. method_signature += return_type(ret_type) + get_icall_name(icall) + "(godot_method_bind *mb, godot_object *inst"
  277. for i, arg in enumerate(args):
  278. method_signature += ", const "
  279. if is_core_type(arg):
  280. method_signature += arg + "& "
  281. elif is_primitive(arg):
  282. method_signature += arg + " "
  283. else:
  284. method_signature += "Object *"
  285. method_signature += "arg" + str(i)
  286. method_signature += ")"
  287. source.append(method_signature + " {")
  288. if ret_type != "void":
  289. source.append("\t" + strip_name(ret_type) + (" *" if is_class_type(ret_type) else " ") + "ret;")
  290. if is_class_type(ret_type):
  291. source.append("\tret = nullptr;")
  292. source.append("\tconst void *args[" + ("1" if len(args) == 0 else "") + "] = {")
  293. for i, arg in enumerate(args):
  294. wrapped_argument = "\t\t"
  295. if is_primitive(arg) or is_core_type(arg):
  296. wrapped_argument += "(void *) &arg" + str(i)
  297. else:
  298. wrapped_argument += "(void *) arg" + str(i)
  299. wrapped_argument += ","
  300. source.append(wrapped_argument)
  301. source.append("\t};")
  302. source.append("")
  303. source.append("\tgodot_method_bind_ptrcall(mb, inst, args, " + ("nullptr" if ret_type == "void" else "&ret") + ");")
  304. if ret_type != "void":
  305. source.append("\treturn ret;")
  306. source.append("}")
  307. source.append("")
  308. return "\n".join(source)
  309. def return_type(t):
  310. if is_class_type(t):
  311. return "Object *"
  312. return t + " "
  313. def get_icall_name(sig):
  314. ret_type = sig[0]
  315. args = sig[1]
  316. name = "___godot_icall_"
  317. name += strip_name(ret_type)
  318. for arg in args:
  319. name += "_" + strip_name(arg)
  320. return name
  321. def get_used_classes(c):
  322. classes = []
  323. for method in c["methods"]:
  324. if is_class_type(method["return_type"]) and not (method["return_type"] in classes):
  325. classes.append(method["return_type"])
  326. for arg in method["arguments"]:
  327. if is_class_type(arg["type"]) and not (arg["type"] in classes):
  328. classes.append(arg["type"])
  329. return classes
  330. def strip_name(name):
  331. if name[0] == '_':
  332. return name[1:]
  333. return name
  334. def is_class_type(name):
  335. return not is_core_type(name) and not is_primitive(name)
  336. def is_core_type(name):
  337. core_types = ["Array",
  338. "Basis",
  339. "Color",
  340. "Dictionary",
  341. "Error",
  342. "Image",
  343. "InputEvent",
  344. "NodePath",
  345. "Plane",
  346. "PoolByteArray",
  347. "PoolIntArray",
  348. "PoolRealArray",
  349. "PoolStringArray",
  350. "PoolVector2Array",
  351. "PoolVector3Array",
  352. "PoolColorArray",
  353. "Quat",
  354. "Rect2",
  355. "Rect3",
  356. "RID",
  357. "String",
  358. "Transform",
  359. "Transform2D",
  360. "Variant",
  361. "Vector2",
  362. "Vector3"]
  363. return name in core_types
  364. def is_primitive(name):
  365. core_types = ["int", "bool", "real", "float", "void"]
  366. return name in core_types
  367. def escape_cpp(name):
  368. escapes = {
  369. "class": "_class",
  370. "char": "_char",
  371. "short": "_short",
  372. "bool": "_bool",
  373. "int": "_int",
  374. "default": "_default",
  375. "case": "_case",
  376. "switch": "_switch",
  377. "export": "_export",
  378. "template": "_template",
  379. "new": "new_"
  380. }
  381. if name in escapes:
  382. return escapes[name]
  383. return name