PolycodePlayer.mm 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. /*
  2. Copyright (C) 2011 by Ivan Safrin
  3. Permission is hereby granted, free of charge, to any person obtaining a copy
  4. of this software and associated documentation files (the "Software"), to deal
  5. in the Software without restriction, including without limitation the rights
  6. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. copies of the Software, and to permit persons to whom the Software is
  8. furnished to do so, subject to the following conditions:
  9. The above copyright notice and this permission notice shall be included in
  10. all copies or substantial portions of the Software.
  11. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  13. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  14. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  15. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  16. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  17. THE SOFTWARE.
  18. */
  19. #include "PolycodePlayer.h"
  20. extern "C" {
  21. // extern int luaopen_Tau(lua_State* L); // declare the wrapped module
  22. // loadFileIntoState(L, "Polycode Player.app/Contents/Resources/API/class.lua");
  23. int MyLoader(lua_State* pState)
  24. {
  25. std::string module = lua_tostring(pState, 1);
  26. module += ".lua";
  27. string defaultPath = "API/";
  28. defaultPath.append(module);
  29. const char* fullPath = module.c_str();
  30. printf("Loading custom class: %s\n", module.c_str());
  31. OSFILE *inFile = OSBasics::open(module, "r");
  32. if(!inFile) {
  33. inFile = OSBasics::open(defaultPath, "r");
  34. }
  35. if(inFile) {
  36. OSBasics::seek(inFile, 0, SEEK_END);
  37. long progsize = OSBasics::tell(inFile);
  38. OSBasics::seek(inFile, 0, SEEK_SET);
  39. char *buffer = (char*)malloc(progsize+1);
  40. memset(buffer, 0, progsize+1);
  41. OSBasics::read(buffer, progsize, 1, inFile);
  42. luaL_loadbuffer(pState, (const char*)buffer, progsize, fullPath);
  43. //free(buffer);
  44. OSBasics::close(inFile);
  45. } else {
  46. std::string err = "\n\tError - Could could not find ";
  47. err += module;
  48. err += ".";
  49. lua_pushstring(pState, err.c_str());
  50. }
  51. return 1;
  52. }
  53. static int debugPrint(lua_State *L)
  54. {
  55. const char *msg = lua_tostring(L, 1);
  56. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  57. if(msg)
  58. event->errorString = string(msg);
  59. else
  60. event->errorString = string("<invalid string>");
  61. Logger::log(">> %s\n", event->errorString.c_str());
  62. PolycodePlayer *player = (PolycodePlayer*)CoreServices::getInstance()->getCore()->getUserPointer();
  63. player->dispatchEvent(event, PolycodeDebugEvent::EVENT_PRINT);
  64. return 0;
  65. }
  66. int PolycodePlayer::report (lua_State *L, int status) {
  67. const char *msg;
  68. printf("Error status: %d\n", status);
  69. if (status) {
  70. msg = lua_tostring(L, -1);
  71. if (msg == NULL) msg = "(error with no message)";
  72. printf("status=%d, %s\n", status, msg);
  73. lua_pop(L, 1);
  74. vector<String> info = String(msg).split(":");
  75. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  76. if(info.size() > 2) {
  77. event->errorString = info[2];
  78. event->lineNumber = atoi(info[1].c_str());
  79. } else {
  80. event->errorString = string(msg);
  81. event->lineNumber = 0;
  82. }
  83. dispatchEvent(event, PolycodeDebugEvent::EVENT_ERROR);
  84. }
  85. return status;
  86. }
  87. void PolycodePlayer::runFile(String fileName) {
  88. printf("Running %s\n", fileName.c_str());
  89. L=lua_open();
  90. /*
  91. luaopen_base(L); // load basic libs (eg. print)
  92. luaopen_math(L);
  93. luaopen_table(L);
  94. luaopen_package(L);
  95. */
  96. luaL_openlibs(L);
  97. luaopen_Polycode(L);
  98. //luaopen_Tau(L); // load the wrappered module
  99. lua_getfield(L, LUA_GLOBALSINDEX, "package"); // push "package"
  100. lua_getfield(L, -1, "loaders"); // push "package.loaders"
  101. lua_remove(L, -2); // remove "package"
  102. // Count the number of entries in package.loaders.
  103. // Table is now at index -2, since 'nil' is right on top of it.
  104. // lua_next pushes a key and a value onto the stack.
  105. int numLoaders = 0;
  106. lua_pushnil(L);
  107. while (lua_next(L, -2) != 0)
  108. {
  109. lua_pop(L, 1);
  110. numLoaders++;
  111. }
  112. lua_pushinteger(L, numLoaders + 1);
  113. lua_pushcfunction(L, MyLoader);
  114. lua_rawset(L, -3);
  115. // Table is still on the stack. Get rid of it now.
  116. lua_pop(L, 1);
  117. lua_register(L, "debugPrint", debugPrint);
  118. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  119. lua_pushstring(L, "class");
  120. lua_call(L, 1, 0);
  121. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  122. lua_pushstring(L, "Polycode");
  123. lua_call(L, 1, 0);
  124. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  125. lua_pushstring(L, "defaults");
  126. lua_call(L, 1, 0);
  127. for(int i=0; i < loadedModules.size(); i++) {
  128. String moduleName = loadedModules[i];
  129. String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
  130. String moduleLoadCall = String("luaopen_") + moduleName;
  131. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  132. lua_pushstring(L, moduleName.c_str());
  133. lua_call(L, 1, 0);
  134. lua_getfield(L, LUA_GLOBALSINDEX, "package");
  135. lua_getfield(L, -1, "loadlib");
  136. lua_pushstring(L, moduleDestPath.c_str());
  137. lua_pushstring(L, moduleLoadCall.c_str());
  138. lua_call(L, 2, 1);
  139. lua_setfield(L, LUA_GLOBALSINDEX, "f");
  140. lua_getfield(L, LUA_GLOBALSINDEX, "f");
  141. lua_getfield(L, LUA_GLOBALSINDEX, "__core__services__instance");
  142. lua_call(L, 1, 0);
  143. //local f = package.loadlib("/Users/ivansafrin/Desktop/Workshop/HelloPolycodeLUA/libPolycode2DPhysicsModule.dylib", "luaopen_Physics2D")
  144. //f(Polycore.CoreServices_getInstance())
  145. }
  146. String fileData = "";
  147. OSFILE *inFile = OSBasics::open(fileName, "r");
  148. if(inFile) {
  149. Logger::log("Opened entrypoint file...");
  150. OSBasics::seek(inFile, 0, SEEK_END);
  151. long progsize = OSBasics::tell(inFile);
  152. OSBasics::seek(inFile, 0, SEEK_SET);
  153. char *buffer = (char*)malloc(progsize+1);
  154. memset(buffer, 0, progsize+1);
  155. OSBasics::read(buffer, progsize, 1, inFile);
  156. fileData = String(buffer);
  157. free(buffer);
  158. OSBasics::close(inFile);
  159. } else {
  160. Logger::log("Error opening entrypoint file (%s)\n", fileName.c_str());
  161. }
  162. String postpend = ""; //" \nif update == nil then\nfunction update(e)\nend\nend\nwhile CORE:Update() do\nupdate(CORE:getElapsed())\nend";
  163. //String fullScript = prepend + prepend2 + prepend3 + fileData;// + postpend;
  164. String fullScript = fileData;
  165. //String fullScript = fileData;// + postpend;
  166. doneLoading = true;
  167. //lua_gc(L, LUA_GCSTOP, 0);
  168. /*
  169. lua_pushliteral(L, "debug");
  170. lua_gettable(L, LUA_GLOBALSINDEX);
  171. lua_pushliteral(L, "traceback"); // correct fn name?
  172. lua_gettable(L, -2);
  173. */
  174. CoreServices::getInstance()->getCore()->lockMutex(CoreServices::getRenderMutex());
  175. if (report(L, luaL_loadstring(L, fullScript.c_str()) || lua_pcall(L, 0,0,0))) {
  176. CoreServices::getInstance()->getCore()->unlockMutex(CoreServices::getRenderMutex());
  177. printf("CRASH LOADING SCRIPT FILE\n");
  178. // exit(1);
  179. } else {
  180. CoreServices::getInstance()->getCore()->unlockMutex(CoreServices::getRenderMutex());
  181. if (report(L, luaL_loadstring(L, postpend.c_str()) || lua_pcall(L, 0,0,0))) {
  182. // exit(1);
  183. printf("CRASH IN SCRIPT EXECUTION FILE\n");
  184. } else {
  185. }
  186. }
  187. }
  188. }
  189. PolycodeDebugEvent::PolycodeDebugEvent() : Event() {
  190. }
  191. PolycodeDebugEvent::~PolycodeDebugEvent() {
  192. }
  193. PolycodePlayer::PolycodePlayer(String fileName, bool knownArchive) : EventDispatcher() {
  194. fileToRun = fileName;
  195. core = NULL;
  196. doneLoading = false;
  197. _knownArchive = knownArchive;
  198. xRes = 640;
  199. yRes = 480;
  200. aaLevel = 6;
  201. fullScreen = false;
  202. }
  203. void PolycodePlayer::loadFile(const char *fileName) {
  204. String nameString = fileName;
  205. String ext = nameString.substr(nameString.length() - 8, nameString.length());
  206. printf("Loading %s\n", fileName);
  207. bool loadingArchive = false;
  208. String configPath;
  209. if(ext == ".polyapp" || _knownArchive) {
  210. ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
  211. rman->addArchive(nameString);
  212. configPath = "runinfo.polyrun";
  213. loadingArchive = true;
  214. Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
  215. } else {
  216. ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
  217. String fileDir = "";
  218. vector<String> bits = String(fileName).split("/");
  219. for(int i=0; i < bits.size()-1; i++) {
  220. fileDir += "/"+bits[i];
  221. }
  222. rman->addArchive(fileDir);
  223. configPath = fileName;
  224. Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);
  225. }
  226. String mainFile = "";
  227. String basePath = fileName;
  228. Number red = 0.2f;
  229. Number green = 0.2f;
  230. Number blue = 0.2f;
  231. frameRate = 60;
  232. Object configFile;
  233. if(!configFile.loadFromXML(configPath)) {
  234. Logger::log("Error loading config file\n");
  235. } else {
  236. if(configFile.root["entryPoint"]) {
  237. mainFile = configFile.root["entryPoint"]->stringVal;
  238. }
  239. if(configFile.root["defaultWidth"]) {
  240. xRes = configFile.root["defaultWidth"]->intVal;
  241. }
  242. if(configFile.root["defaultHeight"]) {
  243. yRes = configFile.root["defaultHeight"]->intVal;
  244. }
  245. if(configFile.root["frameRate"]) {
  246. frameRate = configFile.root["frameRate"]->intVal;
  247. }
  248. if(configFile.root["antiAliasingLevel"]) {
  249. aaLevel = configFile.root["antiAliasingLevel"]->intVal;
  250. }
  251. if(configFile.root["fullScreen"]) {
  252. fullScreen = configFile.root["fullScreen"]->boolVal;
  253. }
  254. if(configFile.root["backgroundColor"]) {
  255. ObjectEntry *color = configFile.root["backgroundColor"];
  256. if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
  257. red = (*color)["red"]->NumberVal;
  258. green = (*color)["green"]->NumberVal;
  259. blue = (*color)["blue"]->NumberVal;
  260. }
  261. }
  262. ObjectEntry *modules = configFile.root["modules"];
  263. if(modules) {
  264. for(int i=0; i < modules->length; i++) {
  265. String moduleName = (*modules)[i]->stringVal;
  266. printf("Loading module: %s\n", moduleName.c_str());
  267. String moduleFileName = String("__lib/osx/") + moduleName+ String(".dylib");
  268. String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
  269. OSFILE *inFile = OSBasics::open(moduleFileName, "r");
  270. if(inFile) {
  271. OSBasics::seek(inFile, 0, SEEK_END);
  272. long progsize = OSBasics::tell(inFile);
  273. OSBasics::seek(inFile, 0, SEEK_SET);
  274. char *buffer = (char*)malloc(progsize+1);
  275. memset(buffer, 0, progsize+1);
  276. OSBasics::read(buffer, progsize, 1, inFile);
  277. OSFILE *outFile = OSBasics::open(moduleDestPath, "w");
  278. OSBasics::write(buffer, progsize, 1, outFile);
  279. OSBasics::close(outFile);
  280. free(buffer);
  281. OSBasics::close(inFile);
  282. loadedModules.push_back(moduleName);
  283. } else {
  284. printf("Error loading module: %s\n", (*modules)[i]->stringVal.c_str());
  285. }
  286. }
  287. }
  288. }
  289. Logger::log("Mainfile: %s\n", mainFile.c_str());
  290. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  291. event->xRes = xRes;
  292. event->yRes = yRes;
  293. createCore();
  294. Logger::log("Core created...\n");
  295. CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
  296. CoreServices::getInstance()->getResourceManager()->addDirResource("default");
  297. //CoreServices::getInstance()->installModule(new GLSLShaderModule());
  298. if(configFile.root["packedItems"]) {
  299. ObjectEntry *packed = configFile.root["packedItems"];
  300. if(packed) {
  301. for(int i=0; i < packed->length; i++) {
  302. ObjectEntry *entryIsResource = (*(*packed)[i])["isResource"];
  303. ObjectEntry *entryPath = (*(*packed)[i])["path"];
  304. if(entryIsResource && entryPath) {
  305. if(entryIsResource->boolVal == true) {
  306. CoreServices::getInstance()->getResourceManager()->addDirResource(entryPath->stringVal, true);
  307. }
  308. }
  309. }
  310. }
  311. }
  312. core->setUserPointer(this);
  313. //core->addEventListener(this, Core::EVENT_CORE_RESIZE);
  314. core->setVideoMode(xRes, yRes, fullScreen, aaLevel);
  315. // dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);
  316. CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
  317. // CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
  318. srand(core->getTicks());
  319. String fullPath;
  320. if(loadingArchive) {
  321. fullPath = mainFile;
  322. } else {
  323. int lindex = basePath.find_last_of("/");
  324. fullPath = basePath.substr(0, lindex);
  325. fullPath += mainFile;
  326. Logger::log(fullPath.c_str());
  327. }
  328. runFile(fullPath);
  329. }
  330. void PolycodePlayer::runPlayer() {
  331. Logger::log("Running player\n");
  332. loadFile(fileToRun.c_str());
  333. }
  334. PolycodePlayer::~PolycodePlayer() {
  335. printf("deleting core...\n");
  336. delete core;
  337. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  338. dispatchEvent(event, PolycodeDebugEvent::EVENT_REMOVE);
  339. // lua_close(L);
  340. }
  341. void PolycodePlayer::handleEvent(Event *event) {
  342. if(event->getDispatcher() == core) {
  343. switch(event->getEventCode()) {
  344. case Core::EVENT_CORE_RESIZE:
  345. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  346. event->xRes = core->getXRes();
  347. event->yRes = core->getYRes();
  348. dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);
  349. break;
  350. }
  351. }
  352. }
  353. bool PolycodePlayer::Update() {
  354. lua_getfield(L, LUA_GLOBALSINDEX, "Update");
  355. lua_pushnumber(L, core->getElapsed());
  356. lua_call(L, 1, 0);
  357. return core->Update();
  358. }