create_lua_library.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. import sys
  2. import CppHeaderParser
  3. import os
  4. import errno
  5. import re
  6. from zipfile import *
  7. import fnmatch
  8. import re
  9. def mkdir_p(path): # Same effect as mkdir -p, create dir and all necessary parent dirs
  10. try:
  11. os.makedirs(path)
  12. except OSError as e:
  13. if e.errno == errno.EEXIST: # Dir already exists; not really an error
  14. pass
  15. else: raise
  16. def template_returnPtrLookupArray(prefix, className, ptr):
  17. out = ""
  18. out += "%sfor i=1,count(%s) do\n" % (prefix, ptr)
  19. out += "%s\tlocal __c = _G[%s](\"__skip_ptr__\")\n" % (prefix, className)
  20. out += "%s\t__c.__ptr = %s[i]\n" % (prefix, ptr)
  21. out += "%s\t%s[i] = __c\n" % (prefix, ptr)
  22. out += "%send\n" % (prefix)
  23. out += "%sreturn %s\n" % (prefix,ptr)
  24. return out
  25. # Note we expect className to be a valid string
  26. def template_returnPtrLookup(prefix, className, ptr):
  27. out = ""
  28. out += "%slocal __c = _G[%s](\"__skip_ptr__\")\n" % (prefix, className)
  29. out += "%s__c.__ptr = %s\n" % (prefix, ptr)
  30. out += "%sreturn __c\n" % (prefix)
  31. return out
  32. def template_quote(str):
  33. return "\"%s\"" % str;
  34. def cleanDocs(docs):
  35. return docs.replace("/*", "").replace("*/", "").replace("*", "").replace("\n", "").replace("\r", "").replace("::", ".").replace("\t", "")
  36. def toLuaType(t):
  37. return t.replace("void", "nil").replace("int", "Integer").replace("bool", "Boolean")
  38. # FIXME: Some "unsigned int *" functions are still being generated on the polycode API?
  39. def typeFilter(ty):
  40. ty = ty.replace("Polycode::", "")
  41. ty = ty.replace("std::", "")
  42. ty = ty.replace("const", "")
  43. ty = ty.replace("inline", "")
  44. ty = ty.replace("static", "")
  45. ty = ty.replace("virtual", "")
  46. ty = ty.replace("&", "")
  47. ty = re.sub(r'^.*\sint\s*$', 'int', ty) # eg "unsigned int"
  48. ty = re.sub(r'^.*\slong\s*$', 'int', ty)
  49. ty = re.sub(r'^.*\sfloat\s*$', 'Number', ty)
  50. ty = re.sub(r'^.*\sdouble\s*$', 'Number', ty) # eg "long double"
  51. ty = ty.replace("unsigned", "int")
  52. ty = ty.replace("long", "int")
  53. ty = ty.replace("float", "Number")
  54. ty = ty.replace("double", "Number")
  55. ty = ty.replace(" ", "") # Not very safe!
  56. return ty
  57. def createLUABindings(inputPath, prefix, mainInclude, libSmallName, libName, apiPath, apiClassPath, includePath, sourcePath, luaDocPath, inheritInModuleFiles):
  58. wrappersHeaderOut = "" # Def: Global C++ *LUAWrappers.h
  59. cppRegisterOut = "" # Def: Global C++ *LUA.cpp
  60. cppLoaderOut = "" # Def: Global C++ *LUA.cpp
  61. luaDocOut = ""
  62. luaIndexOut = "" # Def: Global Lua everything-gets-required-from-this-file file
  63. # Header boilerplate for wrappersHeaderOut and cppRegisterOut
  64. cppRegisterOut += "#include \"%sLUA.h\"\n" % (prefix)
  65. cppRegisterOut += "#include \"%sLUAWrappers.h\"\n" % (prefix)
  66. cppRegisterOut += "#include \"PolyCoreServices.h\"\n\n"
  67. cppRegisterOut += "using namespace Polycode;\n\n"
  68. cppRegisterOut += "int luaopen_%s(lua_State *L) {\n" % (prefix)
  69. # if prefix != "Polycode":
  70. # cppRegisterOut += "CoreServices *inst = (CoreServices*) *((void**)lua_touserdata(L, 1));\n"
  71. # cppRegisterOut += "CoreServices::setInstance(inst);\n"
  72. cppRegisterOut += "\tstatic const struct luaL_reg %sLib [] = {" % (libSmallName)
  73. wrappersHeaderOut += "#pragma once\n\n"
  74. wrappersHeaderOut += "extern \"C\" {\n\n"
  75. wrappersHeaderOut += "#include <stdio.h>\n"
  76. wrappersHeaderOut += "#include \"lua.h\"\n"
  77. wrappersHeaderOut += "#include \"lualib.h\"\n"
  78. wrappersHeaderOut += "#include \"lauxlib.h\"\n"
  79. wrappersHeaderOut += "} // extern \"C\" \n\n"
  80. luaDocOut += "<?xml version=\"1.0\" ?>\n"
  81. luaDocOut += "<docs>\n"
  82. luaDocOut += "<classes>\n"
  83. # Get list of headers to create bindings from
  84. inputPathIsDir = os.path.isdir(inputPath)
  85. if inputPathIsDir:
  86. files = os.listdir(inputPath)
  87. else:
  88. files = []
  89. with open(inputPath) as f:
  90. for line in f.readlines():
  91. files.append(line.strip()) # Strip whitespace, path/
  92. filteredFiles = []
  93. for fileName in files:
  94. if inputPathIsDir:
  95. fileName = "%s/%s" % (inputPath, fileName)
  96. head, tail = os.path.split(fileName)
  97. ignore = ["PolyGLSLProgram", "PolyGLSLShader", "PolyGLSLShaderModule", "PolyWinCore", "PolyCocoaCore", "PolyAGLCore", "PolySDLCore", "Poly_iPhone", "PolyGLES1Renderer", "PolyGLRenderer", "tinyxml", "tinystr", "OpenGLCubemap", "PolyiPhoneCore", "PolyGLES1Texture", "PolyGLTexture", "PolyGLVertexBuffer", "PolyThreaded", "PolyGLHeaders", "GLee", "PolyPeer", "PolySocket", "PolyClient", "PolyServer", "PolyServerWorld", "OSFILE", "OSFileEntry", "OSBasics", "PolyLogger"]
  98. if tail.split(".")[1] == "h" and tail.split(".")[0] not in ignore:
  99. filteredFiles.append(fileName)
  100. wrappersHeaderOut += "#include \"%s\"\n" % (tail)
  101. wrappersHeaderOut += "\nusing namespace std;\n\n"
  102. wrappersHeaderOut += "\nnamespace Polycode {\n\n"
  103. # list of classes that don't get the garbage collection in their meta table
  104. disable_gc = ["Entity", "ScreenEntity", "ScreenShape", "ScreenMesh", "ScreenLabel", "SceneLabel", "SceneMesh", "Screen", "Scene", "Texture", "Image", "Camera", "ScreenParticleEmitter", "SceneParticleEmitter", "Mesh", "Vertex", "Polygon", "Polycode::Polygon", "Material", "ScenePrimitive", "SceneLine", "SceneLight", "SceneSound", "ScreenImage", "SceneEntity"]
  105. # Special case: If we are building the Polycode library itself, inject the LuaEventHandler class.
  106. # Note: so that event callbacks can work, any object inheriting from EventHandler will secretly
  107. # be modified to actually inherit from LuaEventHandler instead.
  108. if prefix == "Polycode":
  109. wrappersHeaderOut += "class LuaEventHandler : public EventHandler {\n"
  110. wrappersHeaderOut += "public:\n"
  111. wrappersHeaderOut += " LuaEventHandler() : EventHandler() {}\n"
  112. wrappersHeaderOut += " void handleEvent(Event *e) {\n"
  113. wrappersHeaderOut += " lua_getfield (L, LUA_GLOBALSINDEX, \"__customError\");\n"
  114. wrappersHeaderOut += " int errH = lua_gettop(L);\n"
  115. wrappersHeaderOut += " lua_getfield(L, LUA_GLOBALSINDEX, \"__handleEvent\");\n"
  116. wrappersHeaderOut += " lua_rawgeti( L, LUA_REGISTRYINDEX, wrapperIndex );\n"
  117. wrappersHeaderOut += " PolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  118. wrappersHeaderOut += " *userdataPtr = (PolyBase*)e;\n"
  119. wrappersHeaderOut += " lua_pcall(L, 2, 0, errH);\n"
  120. wrappersHeaderOut += " lua_settop(L, 0);\n"
  121. wrappersHeaderOut += " }\n"
  122. wrappersHeaderOut += " int wrapperIndex;\n"
  123. wrappersHeaderOut += " lua_State *L;\n"
  124. wrappersHeaderOut += "};\n\n"
  125. # Iterate, process each input file
  126. for fileName in filteredFiles:
  127. # "Package owned" classes that ship with Polycode
  128. inheritInModule = ["PhysicsSceneEntity", "CollisionScene", "CollisionSceneEntity", "UIElement", "UIWindow"]
  129. # A file or comma-separated list of files can be given to specify classes which are "package owned"
  130. # and should not be inherited out of Polycode/. The files should contain one class name per line,
  131. # and the class name may be prefixed with a path (which will be ignored).
  132. if inheritInModuleFiles:
  133. for moduleFileName in inheritInModuleFiles.split(","):
  134. with open(moduleFileName) as f:
  135. for line in f.readlines():
  136. inheritInModule.append(line.strip().split("/",1)[-1]) # Strip whitespace, path/
  137. print("Parsing %s" % fileName)
  138. try: # One input file parse.
  139. f = open(fileName) # Def: Input file handle
  140. contents = f.read().replace("_PolyExport", "") # Def: Input file contents, strip out "_PolyExport"
  141. cppHeader = CppHeaderParser.CppHeader(contents, "string") # Def: Input file contents, parsed structure
  142. ignore_classes = ["PolycodeShaderModule", "Object", "Threaded", "OpenGLCubemap", "PolyBase"]
  143. # Iterate, check each class in this file.
  144. for ckey in cppHeader.classes:
  145. print(">> Parsing class %s" % ckey)
  146. c = cppHeader.classes[ckey] # Def: The class structure
  147. luaClassBindingOut = "" # Def: The local lua file to generate for this class.
  148. inherits = False
  149. parentClass = ""
  150. if len(c["inherits"]) > 0: # Does this class have parents?
  151. if c["inherits"][0]["class"] not in ignore_classes:
  152. if c["inherits"][0]["class"] in inheritInModule: # Parent class is in this module
  153. luaClassBindingOut += "require \"%s/%s\"\n\n" % (prefix, c["inherits"][0]["class"])
  154. else: # Parent class is in Polycore
  155. luaClassBindingOut += "require \"Polycode/%s\"\n\n" % (c["inherits"][0]["class"])
  156. if (ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter"):
  157. luaClassBindingOut += "require \"Polycode/ParticleEmitter\"\n\n"
  158. luaClassBindingOut += "class \"%s\" (%s)\n\n" % (ckey, c["inherits"][0]["class"])
  159. parentClass = c["inherits"][0]["class"]
  160. inherits = True
  161. if inherits == False: # Class does not have parents
  162. luaClassBindingOut += "class \"%s\"\n\n" % ckey
  163. if ckey in ignore_classes:
  164. continue
  165. if len(c["methods"]["public"]) < 2: # Used to, this was a continue.
  166. print("Warning: Lua-binding class with less than two methods")
  167. continue # FIXME: Remove this, move any non-compileable classes into ignore_classes
  168. extendString = ""
  169. if len(c["inherits"]) > 0:
  170. if c["inherits"][0]["class"] != "PolyBase":
  171. extendString = " extends=\"%s\"" % (c["inherits"][0]["class"])
  172. luaDocOut += "\t<class name=\"%s\"%s>\n" % (ckey, extendString)
  173. if 'doxygen' in c:
  174. luaDocOut += "\t\t<desc><![CDATA[%s]]></desc>\n" % (cleanDocs(c['doxygen']))
  175. parsed_methods = [] # Def: List of discovered methods
  176. ignore_methods = ["readByte32", "readByte16", "getCustomEntitiesByType", "Core", "Renderer", "Shader", "Texture", "handleEvent", "secondaryHandler", "getSTLString"]
  177. luaClassBindingOut += "\n\n"
  178. luaDocOut += "\t\t<static_members>\n"
  179. classProperties = [] # Def: List of found property structures ("properties" meaning "data members")
  180. for pp in c["properties"]["public"]:
  181. pp["type"] = pp["type"].replace("Polycode::", "")
  182. pp["type"] = pp["type"].replace("std::", "")
  183. if pp["type"].find("POLYIGNORE") != -1:
  184. continue
  185. if pp["type"].find("static ") != -1: # If static. FIXME: Static doesn't work?
  186. if "defaltValue" in pp: # FIXME: defaltValue is misspelled.
  187. luaClassBindingOut += "%s.%s = %s\n" % (ckey, pp["name"], pp["defaltValue"])
  188. luaDocOut += "\t\t\t<static_member name=\"%s\" type=\"%s\" value=\"%s\">\n" % (pp["name"], toLuaType(typeFilter(pp["type"])), pp["defaltValue"])
  189. if 'doxygen' in pp:
  190. luaDocOut += "\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (cleanDocs(pp['doxygen']))
  191. luaDocOut += "\t\t\t</static_member>\n"
  192. else: # FIXME: Nonstatic method ? variable ?? found.
  193. #there are some bugs in the class parser that cause it to return junk
  194. if pp["type"].find("*") == -1 and pp["type"].find("vector") == -1 and pp["name"] != "setScale" and pp["name"] != "setPosition" and pp["name"] != "BUFFER_CACHE_PRECISION" and not pp["name"].isdigit():
  195. classProperties.append(pp)
  196. luaDocOut += "\t\t</static_members>\n"
  197. # Iterate over properties, creating getters
  198. pidx = 0 # Def: Count of properties processed so far
  199. # TODO: Remove or generalize ParticleEmitter special casing. These lines are marked with #SPEC
  200. luaDocOut += "\t\t<members>\n"
  201. numGetVars = 0
  202. if len(classProperties) > 0: # If there are properties, add index lookup to the metatable
  203. luaClassBindingOut += "function %s:__getvar(name)\n" % ckey
  204. # Iterate over property structures, creating if/else clauses for each.
  205. # TODO: Could a table be more appropriate for
  206. for pp in classProperties:
  207. if pp["name"] == "" or pp["array"] == 1:
  208. continue
  209. numGetVars = numGetVars + 1
  210. pp["type"] = typeFilter(pp["type"])
  211. if pidx == 0:
  212. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  213. else:
  214. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  215. # Generate Lua side of binding:
  216. # If type is a primitive such as Number/String/int/bool
  217. if pp["type"] == "PolyKEY" or pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool":
  218. luaClassBindingOut += "\t\treturn %s.%s_get_%s(self.__ptr)\n" % (libName, ckey, pp["name"])
  219. # If type is a particle emitter, specifically #SPEC
  220. elif (ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter") and pp["name"] == "emitter":
  221. luaClassBindingOut += "\t\tlocal ret = %s(\"__skip_ptr__\")\n" % (pp["type"])
  222. luaClassBindingOut += "\t\tret.__ptr = self.__ptr\n"
  223. luaClassBindingOut += "\t\treturn ret\n"
  224. # If type is a class
  225. else:
  226. luaClassBindingOut += "\t\tlocal retVal = %s.%s_get_%s(self.__ptr)\n" % (libName, ckey, pp["name"])
  227. luaClassBindingOut += template_returnPtrLookup("\t\t", template_quote(pp["type"]), "retVal")
  228. luaDocOut += "\t\t\t<member name=\"%s\" type=\"%s\">\n" % (pp["name"], toLuaType(typeFilter(pp["type"])))
  229. if 'doxygen' in pp:
  230. luaDocOut += "\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (cleanDocs(pp['doxygen']))
  231. luaDocOut += "\t\t\t</member>\n"
  232. # Generate C++ side of binding:
  233. if not ((ckey == "ScreenParticleEmitter" or ckey == "SceneParticleEmitter") and pp["name"] == "emitter"): #SPEC
  234. cppRegisterOut += "\t\t{\"%s_get_%s\", %s_%s_get_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  235. wrappersHeaderOut += "static int %s_%s_get_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  236. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  237. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  238. outfunc = "this_shouldnt_happen"
  239. retFunc = ""
  240. if pp["type"] == "Number":
  241. outfunc = "lua_pushnumber"
  242. if pp["type"] == "String":
  243. outfunc = "lua_pushstring"
  244. retFunc = ".c_str()"
  245. if pp["type"] == "int" or pp["type"] == "PolyKEY":
  246. outfunc = "lua_pushinteger"
  247. if pp["type"] == "bool":
  248. outfunc = "lua_pushboolean"
  249. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool" or pp["type"] == "PolyKEY":
  250. wrappersHeaderOut += "\t%s(L, inst->%s%s);\n" % (outfunc, pp["name"], retFunc)
  251. else:
  252. wrappersHeaderOut += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  253. wrappersHeaderOut += "\t*userdataPtr = (PolyBase*)&inst->%s%s;\n" % (pp["name"], retFunc)
  254. wrappersHeaderOut += "\treturn 1;\n"
  255. wrappersHeaderOut += "}\n\n"
  256. # Success
  257. pidx = pidx + 1
  258. if numGetVars != 0:
  259. luaClassBindingOut += "\tend\n"
  260. if inherits:
  261. luaClassBindingOut += "\tif %s[\"__getvar\"] ~= nil then\n" % (parentClass)
  262. luaClassBindingOut += "\t\treturn %s.__getvar(self, name)\n" % (parentClass)
  263. luaClassBindingOut += "\tend\n"
  264. luaClassBindingOut += "end\n"
  265. luaDocOut += "\t\t</members>\n"
  266. luaClassBindingOut += "\n\n"
  267. # Iterate over properties again, creating setters
  268. pidx = 0 # Def: Count of
  269. if len(classProperties) > 0: # If there are properties, add index setter to the metatable
  270. luaClassBindingOut += "function %s:__setvar(name,value)\n" % ckey
  271. for pp in classProperties:
  272. if pp["name"] == "" or pp["array"] == 1:
  273. continue
  274. pp["type"] = typeFilter(pp["type"])
  275. # If type is a primitive: Create lua and C++ sides at the same time.
  276. if pp["type"] == "Number" or pp["type"] == "String" or pp["type"] == "int" or pp["type"] == "bool" or pp["type"] == "PolyKEY":
  277. if pidx == 0:
  278. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  279. else:
  280. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  281. luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value)\n" % (libName, ckey, pp["name"])
  282. luaClassBindingOut += "\t\treturn true\n"
  283. cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  284. wrappersHeaderOut += "static int %s_%s_set_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  285. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  286. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  287. outfunc = "this_shouldnt_happen"
  288. if pp["type"] == "Number":
  289. outfunc = "lua_tonumber"
  290. if pp["type"] == "String":
  291. outfunc = "lua_tostring"
  292. if pp["type"] == "int":
  293. outfunc = "lua_tointeger"
  294. if pp["type"] == "PolyKEY":
  295. outfunc = "(PolyKEY)lua_tointeger"
  296. if pp["type"] == "bool":
  297. outfunc = "lua_toboolean"
  298. wrappersHeaderOut += "\t%s param = %s(L, 2);\n" % (pp["type"], outfunc)
  299. wrappersHeaderOut += "\tinst->%s = param;\n" % (pp["name"])
  300. wrappersHeaderOut += "\treturn 0;\n"
  301. wrappersHeaderOut += "}\n\n"
  302. pidx = pidx + 1 # Success
  303. else:
  304. if pp["type"].find("*") == -1 and pp["type"].find("static") == -1:
  305. if pidx == 0:
  306. luaClassBindingOut += "\tif name == \"%s\" then\n" % (pp["name"])
  307. else:
  308. luaClassBindingOut += "\telseif name == \"%s\" then\n" % (pp["name"])
  309. luaClassBindingOut += "\t\t%s.%s_set_%s(self.__ptr, value.__ptr)\n" % (libName, ckey, pp["name"])
  310. luaClassBindingOut += "\t\treturn true\n"
  311. cppRegisterOut += "\t\t{\"%s_set_%s\", %s_%s_set_%s},\n" % (ckey, pp["name"], libName, ckey, pp["name"])
  312. wrappersHeaderOut += "static int %s_%s_set_%s(lua_State *L) {\n" % (libName, ckey, pp["name"])
  313. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  314. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  315. wrappersHeaderOut += "\tluaL_checktype(L, 2, LUA_TUSERDATA);\n"
  316. wrappersHeaderOut += "\t%s *argInst = (%s*) *((PolyBase**)lua_touserdata(L, 2));\n" % (typeFilter(pp["type"]), typeFilter(pp["type"]))
  317. wrappersHeaderOut += "\tinst->%s = *argInst;\n" % (pp["name"])
  318. wrappersHeaderOut += "\treturn 0;\n"
  319. wrappersHeaderOut += "}\n\n"
  320. pidx = pidx + 1 # Success
  321. # Notice: Setters for object types are not created.
  322. if pidx != 0:
  323. luaClassBindingOut += "\tend\n"
  324. if inherits:
  325. luaClassBindingOut += "\tif %s[\"__setvar\"] ~= nil then\n" % (parentClass)
  326. luaClassBindingOut += "\t\treturn %s.__setvar(self, name, value)\n" % (parentClass)
  327. luaClassBindingOut += "\telse\n"
  328. luaClassBindingOut += "\t\treturn false\n"
  329. luaClassBindingOut += "\tend\n"
  330. else:
  331. luaClassBindingOut += "\treturn false\n"
  332. luaClassBindingOut += "end\n"
  333. # Iterate over methods
  334. luaClassBindingOut += "\n\n"
  335. luaDocOut += "\t\t<methods>\n"
  336. for pm in c["methods"]["public"]:
  337. # Skip argument-overloaded methods and operators.
  338. # TODO: Instead of skipping arguemnt overloads, have special behavior.
  339. # TODO: Instead of skipping operators, add to metatable.
  340. if pm["name"] in parsed_methods or pm["name"].find("operator") > -1 or pm["rtnType"].find("POLYIGNORE") > -1 or pm["name"] in ignore_methods:
  341. continue
  342. # Skip destructors and methods which return templates.
  343. # TODO: Special-case certain kind of vector<>s?
  344. if pm["name"] == "~"+ckey or pm["name"] == "CoreServices":
  345. continue
  346. staticString = ""
  347. if pm["rtnType"].find("static ") != -1:
  348. staticString = " static=\"true\""
  349. if pm["rtnType"].find("std::vector") > -1:
  350. vectorReturnClass = pm["rtnType"].replace("std::vector<", "").replace(">","").replace(" ", "")
  351. luaDocOut += "\t\t\t<method name=\"%s\" return_array=\"true\" return_type=\"%s\"%s>\n" % (pm["name"], toLuaType(typeFilter(vectorReturnClass).replace("*", "")), staticString)
  352. else:
  353. luaDocOut += "\t\t\t<method name=\"%s\" return_type=\"%s\"%s>\n" % (pm["name"], toLuaType(typeFilter(pm["rtnType"].replace("*", ""))), staticString)
  354. docs = None
  355. if 'doxygen' in pm:
  356. if pm['doxygen'].find("@return") > -1:
  357. docs = cleanDocs(pm['doxygen']).split("@return")[0].split("@param")
  358. else:
  359. docs = cleanDocs(pm['doxygen']).split("@param")
  360. luaDocOut += "\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (docs[0])
  361. if len(pm["parameters"]) > 0:
  362. luaDocOut += "\t\t\t\t<params>\n"
  363. paramIndex = 0
  364. for param in pm["parameters"]:
  365. if "name" in param:
  366. if not "type" in param:
  367. continue
  368. if param["type"] == "0":
  369. continue
  370. if param["type"].find("vector<") != -1:
  371. vectorClass = param["type"].replace("std::vector<", "").replace(">","").replace(" ", "")
  372. luaDocOut += "\t\t\t\t\t<param name=\"%s\" param_array=\"true\" type=\"%s\">\n" % (param["name"], toLuaType(vectorClass.replace("*","")))
  373. else:
  374. luaDocOut += "\t\t\t\t\t<param name=\"%s\" type=\"%s\">\n" % (param["name"], toLuaType(typeFilter(param["type"]).replace("*","")))
  375. if docs != None:
  376. if len(docs) > paramIndex+1:
  377. cdoc = docs[paramIndex+1].split()
  378. cdoc.pop(0)
  379. luaDocOut += "\t\t\t\t\t\t<desc><![CDATA[%s]]></desc>\n" % (" ".join(cdoc).replace("\n", ""))
  380. luaDocOut += "\t\t\t\t\t</param>\n"
  381. paramIndex = paramIndex + 1
  382. luaDocOut += "\t\t\t\t</params>\n"
  383. luaDocOut += "\t\t\t</method>\n"
  384. basicType = False
  385. voidRet = False
  386. vectorReturn = False
  387. vectorReturnClass = ""
  388. # Def: True if method takes a lua_State* as argument (i.e.: no preprocessing by us)
  389. rawMethod = len(pm["parameters"]) > 0 and pm["parameters"][0].get("type","").find("lua_State") > -1
  390. # Basic setup, C++ side: Add function to registry and start building wrapper function.
  391. if pm["name"] == ckey: # It's a constructor
  392. cppRegisterOut += "\t\t{\"%s\", %s_%s},\n" % (ckey, libName, ckey)
  393. wrappersHeaderOut += "static int %s_%s(lua_State *L) {\n" % (libName, ckey)
  394. idx = 1 # Def: Current stack depth (TODO: Figure out, is this correct?)
  395. else: # It's not a constructor
  396. cppRegisterOut += "\t\t{\"%s_%s\", %s_%s_%s},\n" % (ckey, pm["name"], libName, ckey, pm["name"])
  397. wrappersHeaderOut += "static int %s_%s_%s(lua_State *L) {\n" % (libName, ckey, pm["name"])
  398. # Skip static methods (TODO: Figure out, why is this being done here?). # FIXME
  399. if pm["rtnType"].find("static ") == -1:
  400. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  401. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  402. idx = 2
  403. else:
  404. idx = 1
  405. if rawMethod:
  406. wrappersHeaderOut += "\treturn inst->%s(L);\n" % (pm["name"])
  407. else:
  408. # Generate C++ side parameter pushing
  409. paramlist = []
  410. lparamlist = []
  411. for param in pm["parameters"]:
  412. if not "type" in param:
  413. continue
  414. if param["type"] == "0":
  415. continue
  416. param["type"] = typeFilter(param["type"])
  417. param["name"] = param["name"].replace("end", "_end").replace("repeat", "_repeat")
  418. if"type" in param:
  419. luatype = "LUA_TUSERDATA"
  420. checkfunc = "lua_isuserdata"
  421. if param["type"].find("*") > -1:
  422. luafunc = "(%s) *((PolyBase**)lua_touserdata" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  423. elif param["type"].find("&") > -1:
  424. luafunc = "*(%s*) *((PolyBase**)lua_touserdata" % (param["type"].replace("const", "").replace("&", "").replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  425. else:
  426. luafunc = "*(%s*) *((PolyBase**)lua_touserdata" % (param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle"))
  427. lend = ".__ptr"
  428. luafuncsuffix = ")"
  429. if param["type"] == "int" or param["type"] == "unsigned int" or param["type"] == "short":
  430. luafunc = "lua_tointeger"
  431. luatype = "LUA_TNUMBER"
  432. checkfunc = "lua_isnumber"
  433. luafuncsuffix = ""
  434. lend = ""
  435. if param["type"] == "PolyKEY":
  436. luafunc = "(PolyKEY)lua_tointeger"
  437. luatype = "LUA_TNUMBER"
  438. checkfunc = "lua_isnumber"
  439. luafuncsuffix = ""
  440. lend = ""
  441. if param["type"] == "bool":
  442. luafunc = "lua_toboolean"
  443. luatype = "LUA_TBOOLEAN"
  444. checkfunc = "lua_isboolean"
  445. luafuncsuffix = ""
  446. lend = ""
  447. if param["type"] == "Number" or param["type"] == "float" or param["type"] == "double":
  448. luatype = "LUA_TNUMBER"
  449. luafunc = "lua_tonumber"
  450. checkfunc = "lua_isnumber"
  451. luafuncsuffix = ""
  452. lend = ""
  453. if param["type"] == "String":
  454. luatype = "LUA_TSTRING"
  455. luafunc = "lua_tostring"
  456. checkfunc = "lua_isstring"
  457. luafuncsuffix = ""
  458. lend = ""
  459. param["type"] = param["type"].replace("Polygon", "Polycode::Polygon").replace("Rectangle", "Polycode::Rectangle")
  460. if "defaltValue" in param:
  461. if checkfunc != "lua_isuserdata" or (checkfunc == "lua_isuserdata" and param["defaltValue"] == "NULL"):
  462. #param["defaltValue"] = param["defaltValue"].replace(" 0f", ".0f")
  463. param["defaltValue"] = param["defaltValue"].replace(": :", "::")
  464. #param["defaltValue"] = param["defaltValue"].replace("0 ", "0.")
  465. param["defaltValue"] = re.sub(r'([0-9]+) ([0-9])+', r'\1.\2', param["defaltValue"])
  466. wrappersHeaderOut += "\t%s %s;\n" % (param["type"], param["name"])
  467. wrappersHeaderOut += "\tif(%s(L, %d)) {\n" % (checkfunc, idx)
  468. wrappersHeaderOut += "\t\t%s = %s(L, %d)%s;\n" % (param["name"], luafunc, idx, luafuncsuffix)
  469. wrappersHeaderOut += "\t} else {\n"
  470. wrappersHeaderOut += "\t\t%s = %s;\n" % (param["name"], param["defaltValue"])
  471. wrappersHeaderOut += "\t}\n"
  472. else:
  473. wrappersHeaderOut += "\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  474. if param["type"] == "String":
  475. wrappersHeaderOut += "\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  476. else:
  477. wrappersHeaderOut += "\t%s %s = %s(L, %d)%s;\n" % (param["type"], param["name"], luafunc, idx,luafuncsuffix)
  478. else:
  479. wrappersHeaderOut += "\tluaL_checktype(L, %d, %s);\n" % (idx, luatype);
  480. if param["type"] == "String":
  481. wrappersHeaderOut += "\t%s %s = String(%s(L, %d));\n" % (param["type"], param["name"], luafunc, idx)
  482. else:
  483. wrappersHeaderOut += "\t%s %s = %s(L, %d)%s;\n" % (param["type"], param["name"], luafunc, idx, luafuncsuffix)
  484. paramlist.append(param["name"])
  485. lparamlist.append(param["name"]+lend)
  486. idx = idx +1 # Param parse success-- mark the increased stack
  487. # Generate C++-side method call / generate return value
  488. if pm["name"] == ckey: # If constructor
  489. if ckey == "EventHandler": # See LuaEventHandler above
  490. wrappersHeaderOut += "\tLuaEventHandler *inst = new LuaEventHandler();\n"
  491. wrappersHeaderOut += "\tinst->wrapperIndex = luaL_ref(L, LUA_REGISTRYINDEX );\n"
  492. wrappersHeaderOut += "\tinst->L = L;\n"
  493. else:
  494. wrappersHeaderOut += "\t%s *inst = new %s(%s);\n" % (ckey, ckey, ", ".join(paramlist))
  495. wrappersHeaderOut += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  496. wrappersHeaderOut += "\t*userdataPtr = (PolyBase*)inst;\n"
  497. wrappersHeaderOut += "\tluaL_getmetatable(L, \"%s.%s\");\n" % (libName, ckey)
  498. wrappersHeaderOut += "\tlua_setmetatable(L, -2);\n"
  499. wrappersHeaderOut += "\treturn 1;\n"
  500. else: #If non-constructor
  501. if pm["rtnType"].find("static ") == -1: # If non-static
  502. call = "inst->%s(%s)" % (pm["name"], ", ".join(paramlist))
  503. else: # If static (FIXME: Why doesn't this work?)
  504. call = "%s::%s(%s)" % (ckey, pm["name"], ", ".join(paramlist))
  505. #check if returning a template
  506. if pm["rtnType"].find("<") > -1:
  507. #if returning a vector, convert to lua table
  508. if pm["rtnType"].find("std::vector") > -1:
  509. vectorReturnClass = pm["rtnType"].replace("std::vector<", "").replace(">","").replace(" ", "")
  510. if vectorReturnClass.find("&") == -1 and vectorReturnClass.find("*") > -1: #FIXME: return references to std::vectors and basic types
  511. vectorReturn = True
  512. wrappersHeaderOut += "\tstd::vector<%s> retVector = %s;\n" % (vectorReturnClass,call)
  513. wrappersHeaderOut += "\tlua_newtable(L);\n"
  514. wrappersHeaderOut += "\tfor(int i=0; i < retVector.size(); i++) {\n"
  515. wrappersHeaderOut += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  516. wrappersHeaderOut += "\t\t*userdataPtr = (PolyBase*)retVector[i];\n"
  517. wrappersHeaderOut += "\t\tlua_rawseti(L, -2, i+1);\n"
  518. wrappersHeaderOut += "\t}\n"
  519. wrappersHeaderOut += "\treturn 1;\n"
  520. else:
  521. wrappersHeaderOut += "\treturn 0;\n"
  522. # else If void-typed:
  523. elif pm["rtnType"] == "void" or pm["rtnType"] == "static void" or pm["rtnType"] == "virtual void" or pm["rtnType"] == "inline void":
  524. wrappersHeaderOut += "\t%s;\n" % (call)
  525. basicType = True
  526. voidRet = True
  527. vectorReturn = False
  528. wrappersHeaderOut += "\treturn 0;\n" # 0 arguments returned
  529. else: # If there is a return value:
  530. # What type is the return value? Default to pointer
  531. outfunc = "this_shouldnt_happen"
  532. retFunc = ""
  533. basicType = False
  534. vectorReturn = False
  535. if pm["rtnType"] == "Number" or pm["rtnType"] == "inline Number":
  536. outfunc = "lua_pushnumber"
  537. basicType = True
  538. if pm["rtnType"] == "String" or pm["rtnType"] == "static String": # TODO: Path for STL strings?
  539. outfunc = "lua_pushstring"
  540. basicType = True
  541. retFunc = ".c_str()"
  542. if pm["rtnType"] == "int" or pm["rtnType"] == "unsigned int" or pm["rtnType"] == "static int" or pm["rtnType"] == "size_t" or pm["rtnType"] == "static size_t" or pm["rtnType"] == "long" or pm["rtnType"] == "unsigned int" or pm["rtnType"] == "static long" or pm["rtnType"] == "short" or pm["rtnType"] == "PolyKEY":
  543. outfunc = "lua_pushinteger"
  544. basicType = True
  545. if pm["rtnType"] == "bool" or pm["rtnType"] == "static bool" or pm["rtnType"] == "virtual bool":
  546. outfunc = "lua_pushboolean"
  547. basicType = True
  548. if pm["rtnType"].find("*") > -1: # Returned var is definitely a pointer.
  549. wrappersHeaderOut += "\tPolyBase *ptrRetVal = (PolyBase*)%s%s;\n" % (call, retFunc)
  550. wrappersHeaderOut += "\tif(ptrRetVal == NULL) {\n"
  551. wrappersHeaderOut += "\t\tlua_pushnil(L);\n"
  552. wrappersHeaderOut += "\t} else {\n"
  553. wrappersHeaderOut += "\t\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  554. wrappersHeaderOut += "\t\t*userdataPtr = ptrRetVal;\n"
  555. wrappersHeaderOut += "\t}\n"
  556. elif basicType == True: # Returned var has been flagged as a recognized primitive type
  557. wrappersHeaderOut += "\t%s(L, %s%s);\n" % (outfunc, call, retFunc)
  558. else: # Some static object is being returned. Convert it to a pointer, then return that.
  559. className = pm["rtnType"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "")
  560. if className == "Polygon": # Deal with potential windows.h conflict
  561. className = "Polycode::Polygon"
  562. if className == "Rectangle":
  563. className = "Polycode::Rectangle"
  564. if className == "Polycode : : Rectangle":
  565. className = "Polycode::Rectangle"
  566. wrappersHeaderOut += "\t%s *retInst = new %s();\n" % (className, className)
  567. wrappersHeaderOut += "\t*retInst = %s;\n" % (call)
  568. wrappersHeaderOut += "\tPolyBase **userdataPtr = (PolyBase**)lua_newuserdata(L, sizeof(PolyBase*));\n"
  569. wrappersHeaderOut += "\tluaL_getmetatable(L, \"%s.%s\");\n" % (libName, className)
  570. wrappersHeaderOut += "\tlua_setmetatable(L, -2);\n"
  571. wrappersHeaderOut += "\t*userdataPtr = (PolyBase*)retInst;\n"
  572. wrappersHeaderOut += "\treturn 1;\n"
  573. wrappersHeaderOut += "}\n\n" # Close out C++ generation
  574. # Now generate the Lua side method.
  575. if rawMethod:
  576. luaClassBindingOut += "function %s:%s(...)\n" % (ckey, pm["name"])
  577. luaClassBindingOut += "\treturn %s.%s_%s(self.__ptr, ...)\n" % (libName, ckey, pm["name"])
  578. luaClassBindingOut += "end\n"
  579. elif pm["name"] == ckey: # Constructors
  580. luaClassBindingOut += "function %s:%s(...)\n" % (ckey, ckey)
  581. luaClassBindingOut += "\tlocal arg = {...}\n"
  582. if inherits:
  583. luaClassBindingOut += "\tif type(arg[1]) == \"table\" and count(arg) == 1 then\n"
  584. luaClassBindingOut += "\t\tif \"\"..arg[1].__classname == \"%s\" then\n" % (c["inherits"][0]["class"])
  585. luaClassBindingOut += "\t\t\tself.__ptr = arg[1].__ptr\n"
  586. luaClassBindingOut += "\t\t\treturn\n"
  587. luaClassBindingOut += "\t\tend\n"
  588. luaClassBindingOut += "\tend\n"
  589. luaClassBindingOut += "\tfor k,v in pairs(arg) do\n"
  590. luaClassBindingOut += "\t\tif type(v) == \"table\" then\n"
  591. luaClassBindingOut += "\t\t\tif v.__ptr ~= nil then\n"
  592. luaClassBindingOut += "\t\t\t\targ[k] = v.__ptr\n"
  593. luaClassBindingOut += "\t\t\tend\n"
  594. luaClassBindingOut += "\t\tend\n"
  595. luaClassBindingOut += "\tend\n"
  596. luaClassBindingOut += "\tif self.__ptr == nil and arg[1] ~= \"__skip_ptr__\" then\n"
  597. if ckey == "EventHandler": # See LuaEventHandler above
  598. luaClassBindingOut += "\t\tself.__ptr = %s.%s(self)\n" % (libName, ckey)
  599. else:
  600. luaClassBindingOut += "\t\tself.__ptr = %s.%s(unpack(arg))\n" % (libName, ckey)
  601. luaClassBindingOut += "\tend\n"
  602. luaClassBindingOut += "end\n\n"
  603. else: # Non-constructors.
  604. if pm["rtnType"].find("static ") == -1: # Non-static method
  605. luaClassBindingOut += "function %s:%s(%s)\n" % (ckey, pm["name"], ", ".join(paramlist))
  606. if len(lparamlist):
  607. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr, %s)\n" % (libName, ckey, pm["name"], ", ".join(lparamlist))
  608. else:
  609. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(self.__ptr)\n" % (libName, ckey, pm["name"])
  610. else: # Static method
  611. luaClassBindingOut += "function %s.%s(%s)\n" % (ckey, pm["name"], ", ".join(paramlist))
  612. if len(lparamlist):
  613. luaClassBindingOut += "\tlocal retVal = %s.%s_%s(%s)\n" % (libName, ckey, pm["name"], ", ".join(lparamlist))
  614. else:
  615. luaClassBindingOut += "\tlocal retVal = %s.%s_%s()\n" % (libName, ckey, pm["name"])
  616. if not voidRet: # Was there a return value?
  617. if basicType == True: # Yes, a primitive
  618. luaClassBindingOut += "\treturn retVal\n"
  619. else: # Yes, a pointer was returned
  620. luaClassBindingOut += "\tif retVal == nil then return nil end\n"
  621. if vectorReturn == True:
  622. className = vectorReturnClass.replace("*", "")
  623. luaClassBindingOut += template_returnPtrLookupArray("\t",template_quote(className),"retVal")
  624. else:
  625. className = pm["rtnType"].replace("const", "").replace("&", "").replace("inline", "").replace("virtual", "").replace("static", "").replace("*","").replace(" ", "")
  626. luaClassBindingOut += template_returnPtrLookup("\t",template_quote(className),"retVal")
  627. luaClassBindingOut += "end\n\n" # Close out Lua generation
  628. parsed_methods.append(pm["name"]) # Method parse success
  629. luaDocOut += "\t\t</methods>\n"
  630. # With methods out of the way, do some final cleanup:
  631. # user pointer metatable creation in C++
  632. cppLoaderOut += "\n\tluaL_newmetatable(L, \"%s.%s\");\n" % (libName, ckey)
  633. if ckey not in disable_gc:
  634. cppLoaderOut += "\tlua_pushstring(L, \"__gc\");\n"
  635. cppLoaderOut += "\tlua_pushcfunction(L, %s_delete_%s);\n" % (libName, ckey)
  636. cppLoaderOut += "\tlua_settable(L, -3);\n"
  637. cppLoaderOut +="\tlua_pop(L, 1);\n"
  638. # Delete method (C++ side)
  639. cppRegisterOut += "\t\t{\"delete_%s\", %s_delete_%s},\n" % (ckey, libName, ckey)
  640. wrappersHeaderOut += "static int %s_delete_%s(lua_State *L) {\n" % (libName, ckey)
  641. wrappersHeaderOut += "\tluaL_checktype(L, 1, LUA_TUSERDATA);\n"
  642. wrappersHeaderOut += "\t%s *inst = (%s*) *((PolyBase**)lua_touserdata(L, 1));\n" % (ckey, ckey)
  643. wrappersHeaderOut += "\tdelete inst;\n"
  644. wrappersHeaderOut += "\treturn 0;\n"
  645. wrappersHeaderOut += "}\n\n"
  646. # Delete method (Lua side)
  647. luaClassBindingOut += "function %s:__delete()\n" % (ckey)
  648. luaClassBindingOut += "\t%s.delete_%s(self.__ptr)\n" % (libName, ckey)
  649. luaClassBindingOut += "end\n"
  650. # Add class to lua index file
  651. luaIndexOut += "require \"%s/%s\"\n" % (prefix, ckey)
  652. # Write lua file
  653. mkdir_p(apiClassPath)
  654. if ckey != "EventDispatcher":
  655. fout = open("%s/%s.lua" % (apiClassPath, ckey), "w")
  656. fout.write(luaClassBindingOut)
  657. luaDocOut += "\t</class>\n"
  658. except CppHeaderParser.CppParseError as e: # One input file parse; failed.
  659. print(e)
  660. sys.exit(1)
  661. luaDocOut += "</classes>\n"
  662. luaDocOut += "</docs>\n"
  663. # Footer boilerplate for wrappersHeaderOut and cppRegisterOut.
  664. wrappersHeaderOut += "} // namespace Polycode\n"
  665. cppRegisterOut += "\t\t{NULL, NULL}\n"
  666. cppRegisterOut += "\t};\n"
  667. cppRegisterOut += "\tluaL_openlib(L, \"%s\", %sLib, 0);\n" % (libName, libSmallName)
  668. cppRegisterOut += cppLoaderOut
  669. cppRegisterOut += "\treturn 1;\n"
  670. cppRegisterOut += "}"
  671. cppRegisterHeaderOut = "" # Def: Global C++ *LUA.h
  672. cppRegisterHeaderOut += "#pragma once\n"
  673. cppRegisterHeaderOut += "#include <%s>\n" % (mainInclude)
  674. cppRegisterHeaderOut += "extern \"C\" {\n"
  675. cppRegisterHeaderOut += "#include <stdio.h>\n"
  676. cppRegisterHeaderOut += "#include \"lua.h\"\n"
  677. cppRegisterHeaderOut += "#include \"lualib.h\"\n"
  678. cppRegisterHeaderOut += "#include \"lauxlib.h\"\n"
  679. cppRegisterHeaderOut += "int _PolyExport luaopen_%s(lua_State *L);\n" % (prefix)
  680. cppRegisterHeaderOut += "}\n"
  681. # Write out global files
  682. mkdir_p(includePath)
  683. mkdir_p(apiPath)
  684. mkdir_p(sourcePath)
  685. fout = open("%s/%sLUA.h" % (includePath, prefix), "w")
  686. fout.write(cppRegisterHeaderOut)
  687. if luaDocPath is None:
  688. luaDocPath = "../../../Documentation/Lua/xml"
  689. if luaDocPath != "-":
  690. fout = open("%s/%s.xml" % (luaDocPath, prefix), "w")
  691. fout.write(luaDocOut)
  692. fout = open("%s/%s.lua" % (apiPath, prefix), "w")
  693. fout.write(luaIndexOut)
  694. fout = open("%s/%sLUAWrappers.h" % (includePath, prefix), "w")
  695. fout.write(wrappersHeaderOut)
  696. fout = open("%s/%sLUA.cpp" % (sourcePath, prefix), "w")
  697. fout.write(cppRegisterOut)
  698. # Create .pak zip archive
  699. pattern = '*.lua'
  700. os.chdir(apiPath)
  701. if libName == "Polycore":
  702. with ZipFile("api.pak", 'w') as myzip:
  703. for root, dirs, files in os.walk("."):
  704. for filename in fnmatch.filter(files, pattern):
  705. myzip.write(os.path.join(root, filename))
  706. else:
  707. with ZipFile("%s.pak" % (libName), 'w') as myzip:
  708. for root, dirs, files in os.walk("."):
  709. for filename in fnmatch.filter(files, pattern):
  710. myzip.write(os.path.join(root, filename))
  711. if len(sys.argv) < 10:
  712. print ("Usage:\n%s [input path] [prefix] [main include] [lib small name] [lib name] [api path] [api class-path] [include path] [source path] [lua doc path (optional) (or - for omit)] [inherit-in-module-file path (optional)]" % (sys.argv[0]))
  713. sys.exit(1)
  714. else:
  715. createLUABindings(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5], sys.argv[6], sys.argv[7], sys.argv[8], sys.argv[9], sys.argv[10] if len(sys.argv)>10 else None, sys.argv[11] if len(sys.argv)>11 else None)