PolycodePlayer.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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. #include <string>
  21. PolycodeRemoteDebuggerClient::PolycodeRemoteDebuggerClient() : EventDispatcher() {
  22. client = new Client(6445, 1);
  23. client->Connect("127.0.0.1", 4630);
  24. client->addEventListener(this, ClientEvent::EVENT_SERVER_DISCONNECTED);
  25. }
  26. void PolycodeRemoteDebuggerClient::handleEvent(Event *event) {
  27. if(event->getDispatcher() == client) {
  28. switch(event->getEventCode()) {
  29. case ClientEvent::EVENT_SERVER_DISCONNECTED:
  30. dispatchEvent(new Event(), Event::COMPLETE_EVENT);
  31. break;
  32. }
  33. } else {
  34. PolycodeDebugEvent *debugEvent = (PolycodeDebugEvent*) event;
  35. switch(event->getEventCode()) {
  36. case PolycodeDebugEvent::EVENT_PRINT:
  37. client->sendReliableDataToServer((char*)debugEvent->errorString.c_str(), debugEvent->errorString.length()+1, EVENT_DEBUG_PRINT);
  38. break;
  39. case PolycodeDebugEvent::EVENT_ERROR:
  40. RemoteErrorData data;
  41. if(debugEvent->errorString.length() > 254) {
  42. debugEvent->errorString = debugEvent->errorString.substr(0,254);
  43. }
  44. if(debugEvent->fileName.length() > 254) {
  45. debugEvent->fileName = debugEvent->fileName.substr(0,254);
  46. }
  47. strcpy(data.errorMessage, debugEvent->errorString.c_str());
  48. strcpy(data.fileName, debugEvent->fileName.c_str());
  49. data.lineNumber = debugEvent->lineNumber;
  50. data.backTraceSize = debugEvent->backTrace.size();
  51. client->sendReliableDataToServer((char*)&data, sizeof(data), EVENT_DEBUG_ERROR);
  52. for(int i=0; i < debugEvent->backTrace.size(); i++) {
  53. RemoteBacktraceData btData;
  54. if(debugEvent->backTrace[i].fileName.length() > 254) {
  55. debugEvent->backTrace[i].fileName = debugEvent->backTrace[i].fileName.substr(0,254);
  56. }
  57. strcpy(btData.fileName, debugEvent->backTrace[i].fileName.c_str());
  58. btData.lineNumber = debugEvent->backTrace[i].lineNumber;
  59. client->sendReliableDataToServer((char*)&btData, sizeof(btData), EVENT_DEBUG_BACKTRACE_INFO);
  60. }
  61. break;
  62. }
  63. }
  64. }
  65. PolycodeRemoteDebuggerClient::~PolycodeRemoteDebuggerClient() {
  66. printf("disconnecting debugger\n");
  67. client->Disconnect();
  68. }
  69. extern "C" {
  70. static void dumpstack (lua_State *L) {
  71. int i;
  72. int top=lua_gettop(L);
  73. printf("dumpstack -- \n");
  74. for (i=1; i<=top; i++) {
  75. printf("%d\t%s\t",i,luaL_typename(L,i));
  76. switch (lua_type(L, i)) {
  77. case LUA_TNUMBER:
  78. printf("%g\n",lua_tonumber(L,i));
  79. break;
  80. case LUA_TSTRING:
  81. printf("%s\n",lua_tostring(L,i));
  82. break;
  83. case LUA_TBOOLEAN:
  84. printf("%s\n", (lua_toboolean(L, i) ? "true" : "false"));
  85. break;
  86. case LUA_TNIL:
  87. printf("%s\n", "nil");
  88. break;
  89. default:
  90. printf("%p\n",lua_topointer(L,i));
  91. break;
  92. }
  93. }
  94. printf("dumpstack -- END\n");
  95. }
  96. // extern int luaopen_Tau(lua_State* L); // declare the wrapped module
  97. // loadFileIntoState(L, "Polycode Player.app/Contents/Resources/API/class.lua");
  98. int MyLoader(lua_State* pState)
  99. {
  100. std::string module = lua_tostring(pState, 1);
  101. module += ".lua";
  102. std::string defaultPath = "API/";
  103. defaultPath.append(module);
  104. const char* fullPath = module.c_str();
  105. // Logger::log("Loading custom class: %s\n", module.c_str());
  106. OSFILE *inFile = OSBasics::open(module, "r");
  107. if(!inFile) {
  108. inFile = OSBasics::open(defaultPath, "r");
  109. }
  110. if(inFile) {
  111. OSBasics::seek(inFile, 0, SEEK_END);
  112. long progsize = OSBasics::tell(inFile);
  113. OSBasics::seek(inFile, 0, SEEK_SET);
  114. char *buffer = (char*)malloc(progsize+1);
  115. memset(buffer, 0, progsize+1);
  116. OSBasics::read(buffer, progsize, 1, inFile);
  117. PolycodePlayer *player = (PolycodePlayer*)CoreServices::getInstance()->getCore()->getUserPointer();
  118. player->report(pState, luaL_loadbuffer(pState, (const char*)buffer, progsize, fullPath));
  119. //free(buffer);
  120. OSBasics::close(inFile);
  121. } else {
  122. std::string err = "\n\tError - Could could not find ";
  123. err += module;
  124. err += ".";
  125. lua_pushstring(pState, err.c_str());
  126. }
  127. return 1;
  128. }
  129. static int customError(lua_State *L) {
  130. PolycodePlayer *player = (PolycodePlayer*)CoreServices::getInstance()->getCore()->getUserPointer();
  131. player->crashed = true;
  132. std::vector<BackTraceEntry> backTrace;
  133. lua_Debug entry;
  134. int depth = 0;
  135. while (lua_getstack(L, depth, &entry)) {
  136. lua_getinfo(L, "Sln", &entry);
  137. std::vector<String> bits = String(entry.short_src).split("\"");
  138. if(bits.size() > 1) {
  139. String fileName = bits[1];
  140. if(fileName != "class.lua") {
  141. BackTraceEntry trace;
  142. trace.lineNumber = entry.currentline;
  143. trace.fileName = fileName;
  144. backTrace.push_back(trace);
  145. printf(">>>> In file: %s on line %d\n", fileName.c_str(), trace.lineNumber);
  146. //backTrace += "In file: " + fileName + " on line " + String::IntToString(entry.currentline)+"\n";
  147. }
  148. }
  149. depth++;
  150. }
  151. // horrible hack to determine the filenames of things
  152. bool stringThatIsTheMainFileSet = false;
  153. String stringThatIsTheMainFile;
  154. if(backTrace.size() == 0) {
  155. BackTraceEntry trace;
  156. trace.lineNumber = 0;
  157. trace.fileName = player->fullPath;
  158. backTrace.push_back(trace);
  159. } else {
  160. stringThatIsTheMainFileSet = true;
  161. stringThatIsTheMainFile = backTrace[backTrace.size()-1].fileName;
  162. backTrace[backTrace.size()-1].fileName = player->fullPath;
  163. }
  164. if(stringThatIsTheMainFileSet) {
  165. for(int i=0; i < backTrace.size(); i++) {
  166. if(backTrace[i].fileName == stringThatIsTheMainFile) {
  167. backTrace[i].fileName = player->fullPath;
  168. }
  169. }
  170. }
  171. const char *msg = lua_tostring(L, -1);
  172. if (msg == NULL) msg = "(error with no message)";
  173. lua_pop(L, 1);
  174. String errorString;
  175. std::vector<String> info = String(msg).split(":");
  176. if(info.size() > 2) {
  177. errorString = info[2];
  178. } else {
  179. errorString = msg;
  180. }
  181. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  182. event->errorString = errorString;
  183. event->backTrace = backTrace;
  184. event->fileName = backTrace[0].fileName;
  185. event->lineNumber = backTrace[0].lineNumber;
  186. player->dispatchEvent(event, PolycodeDebugEvent::EVENT_ERROR);
  187. return 0;
  188. }
  189. static int areSameCClass(lua_State *L) {
  190. luaL_checktype(L, 1, LUA_TUSERDATA);
  191. PolyBase *classOne = *((PolyBase**)lua_touserdata(L, 1));
  192. luaL_checktype(L, 2, LUA_TUSERDATA);
  193. PolyBase *classTwo = *((PolyBase**)lua_touserdata(L, 2));
  194. if(classOne == classTwo) {
  195. lua_pushboolean(L, true);
  196. } else {
  197. lua_pushboolean(L, false);
  198. }
  199. return 1;
  200. }
  201. static int debugPrint(lua_State *L)
  202. {
  203. const char *msg = lua_tostring(L, 1);
  204. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  205. if(msg)
  206. event->errorString = std::string(msg);
  207. else
  208. event->errorString = std::string("<invalid string>");
  209. Logger::log(">> %s\n", event->errorString.c_str());
  210. PolycodePlayer *player = (PolycodePlayer*)CoreServices::getInstance()->getCore()->getUserPointer();
  211. player->dispatchEvent(event, PolycodeDebugEvent::EVENT_PRINT);
  212. return 0;
  213. }
  214. int PolycodePlayer::report (lua_State *L, int status) {
  215. const char *msg;
  216. PolycodePlayer *player = (PolycodePlayer*)CoreServices::getInstance()->getCore()->getUserPointer();
  217. // Logger::log("Error status: %d\n", status);
  218. if (status) {
  219. std::vector<BackTraceEntry> backTrace;
  220. msg = lua_tostring(L, -1);
  221. if (msg == NULL) msg = "(error with no message)";
  222. Logger::log("status=%d, (%s)\n", status, msg);
  223. lua_pop(L, 1);
  224. std::vector<String> info = String(msg).split(":");
  225. BackTraceEntry trace;
  226. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  227. if(info.size() > 2) {
  228. event->errorString = info[2];
  229. event->lineNumber = atoi(info[1].c_str());
  230. event->fileName = info[0].replace("string ", "").replace("\"", "").replace("[", "").replace("]", "");
  231. trace.lineNumber = event->lineNumber;
  232. trace.fileName = event->fileName;
  233. printf(">>>> In file: %s on line %d\n", trace.fileName.c_str(), trace.lineNumber);
  234. } else {
  235. event->errorString = std::string(msg);
  236. event->lineNumber = 0;
  237. event->fileName = player->fullPath;
  238. trace.fileName = event->fileName;
  239. trace.lineNumber = 0;
  240. }
  241. backTrace.push_back(trace);
  242. event->backTrace = backTrace;
  243. dispatchEvent(event, PolycodeDebugEvent::EVENT_ERROR);
  244. }
  245. return status;
  246. }
  247. void PolycodePlayer::runFile(String fileName) {
  248. Logger::log("Running %s\n", fileName.c_str());
  249. L=lua_open();
  250. luaL_openlibs(L);
  251. luaopen_debug(L);
  252. luaopen_Polycode(L);
  253. lua_getfield(L, LUA_GLOBALSINDEX, "package"); // push "package"
  254. lua_getfield(L, -1, "loaders"); // push "package.loaders"
  255. lua_remove(L, -2); // remove "package"
  256. // Count the number of entries in package.loaders.
  257. // Table is now at index -2, since 'nil' is right on top of it.
  258. // lua_next pushes a key and a value onto the stack.
  259. int numLoaders = 0;
  260. lua_pushnil(L);
  261. while (lua_next(L, -2) != 0)
  262. {
  263. lua_pop(L, 1);
  264. numLoaders++;
  265. }
  266. lua_pushinteger(L, numLoaders + 1);
  267. lua_pushcfunction(L, MyLoader);
  268. lua_rawset(L, -3);
  269. // Table is still on the stack. Get rid of it now.
  270. lua_pop(L, 1);
  271. lua_register(L, "debugPrint", debugPrint);
  272. lua_register(L, "__customError", customError);
  273. lua_register(L, "__are_same_c_class", areSameCClass);
  274. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  275. lua_pushstring(L, "class");
  276. lua_call(L, 1, 0);
  277. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  278. lua_pushstring(L, "Polycode");
  279. lua_call(L, 1, 0);
  280. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  281. lua_pushstring(L, "Physics2D");
  282. lua_call(L, 1, 0);
  283. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  284. lua_pushstring(L, "Physics3D");
  285. lua_call(L, 1, 0);
  286. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  287. lua_pushstring(L, "UI");
  288. lua_call(L, 1, 0);
  289. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  290. lua_pushstring(L, "defaults");
  291. lua_call(L, 1, 0);
  292. luaopen_Physics2D(L);
  293. luaopen_Physics3D(L);
  294. luaopen_UI(L);
  295. /*
  296. for(int i=0; i < loadedModules.size(); i++) {
  297. String moduleName = loadedModules[i];
  298. #ifdef _WINDOWS
  299. TCHAR _tempPath[4098];
  300. TCHAR tempPath[4098];
  301. GetTempPathW(4098, _tempPath);
  302. GetLongPathNameW(_tempPath, tempPath, 4098);
  303. String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
  304. #else
  305. #if defined(__APPLE__) && defined(__MACH__)
  306. String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
  307. #else
  308. String moduleDestPath = String("/tmp/") + moduleName+ String(".so");
  309. #endif
  310. #endif
  311. String moduleLoadCall = String("luaopen_") + moduleName;
  312. lua_getfield(L, LUA_GLOBALSINDEX, "require");
  313. lua_pushstring(L, moduleName.c_str());
  314. lua_call(L, 1, 0);
  315. printf("LOADING MODULE %s\n", moduleDestPath.c_str());
  316. lua_getfield(L, LUA_GLOBALSINDEX, "package");
  317. lua_getfield(L, -1, "loadlib");
  318. lua_pushstring(L, moduleDestPath.c_str());
  319. lua_pushstring(L, moduleLoadCall.c_str());
  320. lua_call(L, 2, 2);
  321. lua_setfield(L, LUA_GLOBALSINDEX, "err");
  322. lua_setfield(L, LUA_GLOBALSINDEX, "f");
  323. // lua_getfield(L, LUA_GLOBALSINDEX, "print");
  324. // lua_getfield(L, LUA_GLOBALSINDEX, "err");
  325. // lua_call(L, 1, 0);
  326. printf("SETTING CORE SERVICES\n");
  327. lua_getfield(L, LUA_GLOBALSINDEX, "f");
  328. lua_getfield(L, LUA_GLOBALSINDEX, "__core__services__instance");
  329. lua_call(L, 1, 0);
  330. printf("DONE LOADING MODULE...\n");
  331. //local f = package.loadlib("/Users/ivansafrin/Desktop/Workshop/HelloPolycodeLUA/libPolycode2DPhysicsModule.dylib", "luaopen_Physics2D")
  332. //f(Polycore.CoreServices_getInstance())
  333. }
  334. */
  335. String fileData = "";
  336. OSFILE *inFile = OSBasics::open(fileName, "r");
  337. if(inFile) {
  338. Logger::log("Opened entrypoint file...");
  339. OSBasics::seek(inFile, 0, SEEK_END);
  340. long progsize = OSBasics::tell(inFile);
  341. OSBasics::seek(inFile, 0, SEEK_SET);
  342. char *buffer = (char*)malloc(progsize+1);
  343. memset(buffer, 0, progsize+1);
  344. OSBasics::read(buffer, progsize, 1, inFile);
  345. fileData = String(buffer);
  346. free(buffer);
  347. OSBasics::close(inFile);
  348. } else {
  349. Logger::log("Error opening entrypoint file (%s)\n", fileName.c_str());
  350. }
  351. String fullScript = fileData;
  352. doneLoading = true;
  353. //lua_gc(L, LUA_GCSTOP, 0);
  354. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  355. errH = lua_gettop(L);
  356. //CoreServices::getInstance()->getCore()->lockMutex(CoreServices::getRenderMutex());
  357. if (report(L, luaL_loadstring(L, fullScript.c_str()))) {
  358. //CoreServices::getInstance()->getCore()->unlockMutex(CoreServices::getRenderMutex());
  359. Logger::log("CRASH LOADING SCRIPT FILE\n");
  360. // exit(1);
  361. } else {
  362. if (lua_pcall(L, 0,0,errH)) {
  363. Logger::log("CRASH EXECUTING FILE\n");
  364. }
  365. }
  366. }
  367. }
  368. PolycodeDebugEvent::PolycodeDebugEvent() : Event() {
  369. }
  370. PolycodeDebugEvent::~PolycodeDebugEvent() {
  371. }
  372. PolycodePlayer::PolycodePlayer(String fileName, bool knownArchive, bool useDebugger) : EventDispatcher() {
  373. L = NULL;
  374. remoteDebuggerClient = NULL;
  375. crashed = false;
  376. doCodeInject = false;
  377. this->useDebugger = useDebugger;
  378. fileToRun = fileName;
  379. core = NULL;
  380. doneLoading = false;
  381. _knownArchive = knownArchive;
  382. xRes = 640;
  383. yRes = 480;
  384. aaLevel = 6;
  385. fullScreen = false;
  386. }
  387. void PolycodePlayer::loadFile(const char *fileName) {
  388. String mainFile = "";
  389. String basePath = fileName;
  390. Number red = 0.2f;
  391. Number green = 0.2f;
  392. Number blue = 0.2f;
  393. String textureFiltering = "linear";
  394. frameRate = 60;
  395. Object configFile;
  396. String nameString = fileName;
  397. bool loadingArchive = false;
  398. if(nameString != "") {
  399. String ext = nameString.substr(nameString.length() - 8, nameString.length());
  400. Logger::log("Loading %s\n", fileName);
  401. String configPath;
  402. if(ext == ".polyapp" || _knownArchive) {
  403. ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
  404. rman->addArchive(nameString);
  405. configPath = "runinfo.polyrun";
  406. loadingArchive = true;
  407. Logger::log("Reading configuration from POLYAPP file... (%s)\n", nameString.c_str());
  408. } else {
  409. ResourceManager *rman = CoreServices::getInstance()->getResourceManager();
  410. String fileDir = "";
  411. std::vector<String> bits = String(fileName).split("/");
  412. for(int i=0; i < bits.size()-1; i++) {
  413. fileDir += "/"+bits[i];
  414. }
  415. rman->addArchive(fileDir);
  416. configPath = fileName;
  417. Logger::log("Reading configuration from .polycode file directly... (%s)\n", fileName);
  418. }
  419. if(!configFile.loadFromXML(configPath)) {
  420. Logger::log("Error loading config file\n");
  421. } else {
  422. if(configFile.root["entryPoint"]) {
  423. mainFile = configFile.root["entryPoint"]->stringVal;
  424. }
  425. if(configFile.root["defaultWidth"]) {
  426. xRes = configFile.root["defaultWidth"]->intVal;
  427. }
  428. if(configFile.root["defaultHeight"]) {
  429. yRes = configFile.root["defaultHeight"]->intVal;
  430. }
  431. if(configFile.root["frameRate"]) {
  432. frameRate = configFile.root["frameRate"]->intVal;
  433. }
  434. if(configFile.root["antiAliasingLevel"]) {
  435. aaLevel = configFile.root["antiAliasingLevel"]->intVal;
  436. }
  437. if(configFile.root["anisotropyLevel"]) {
  438. anisotropyLevel = configFile.root["anisotropyLevel"]->intVal;
  439. }
  440. if(configFile.root["vSync"]) {
  441. vSync = configFile.root["vSync"]->boolVal;
  442. }
  443. if(configFile.root["fullScreen"]) {
  444. fullScreen = configFile.root["fullScreen"]->boolVal;
  445. }
  446. if(configFile.root["textureFiltering"]) {
  447. textureFiltering = configFile.root["textureFiltering"]->stringVal;
  448. }
  449. if(configFile.root["backgroundColor"]) {
  450. ObjectEntry *color = configFile.root["backgroundColor"];
  451. if((*color)["red"] && (*color)["green"] && (*color)["blue"]) {
  452. red = (*color)["red"]->NumberVal;
  453. green = (*color)["green"]->NumberVal;
  454. blue = (*color)["blue"]->NumberVal;
  455. }
  456. }
  457. ObjectEntry *fonts = configFile.root["fonts"];
  458. if(fonts) {
  459. for(int i=0; i < fonts->length; i++) {
  460. ObjectEntry *fontName = (*(*fonts)[i])["name"];
  461. ObjectEntry *fontPath = (*(*fonts)[i])["path"];
  462. if(fontName && fontPath) {
  463. printf("REGISTERING FONT %s %s\n", fontName->stringVal.c_str(), fontPath->stringVal.c_str());
  464. CoreServices::getInstance()->getFontManager()->registerFont(fontName->stringVal, fontPath->stringVal);
  465. }
  466. }
  467. }
  468. ObjectEntry *modules = configFile.root["modules"];
  469. if(modules) {
  470. for(int i=0; i < modules->length; i++) {
  471. String moduleName = (*modules)[i]->stringVal;
  472. Logger::log("Loading module: %s\n", moduleName.c_str());
  473. #ifdef _WINDOWS
  474. TCHAR _tempPath[4098];
  475. TCHAR tempPath[4098];
  476. GetTempPathW(4098, _tempPath);
  477. GetLongPathNameW(_tempPath, tempPath, 4098);
  478. String moduleDestPath = String(tempPath) + String("\\") + moduleName+ String(".dll");
  479. String moduleFileName = String("__lib/win/") + moduleName+ String(".dll");
  480. #else
  481. #if defined(__APPLE__) && defined(__MACH__)
  482. String moduleFileName = String("__lib/osx/") + moduleName+ String(".dylib");
  483. String moduleDestPath = String("/tmp/") + moduleName+ String(".dylib");
  484. #else
  485. String moduleFileName = String("__lib/linux/") + moduleName+ String(".so");
  486. String moduleDestPath = String("/tmp/") + moduleName+ String(".so");
  487. #endif
  488. #endif
  489. OSFILE *inFile = OSBasics::open(moduleFileName, "rb");
  490. if(inFile) {
  491. OSBasics::seek(inFile, 0, SEEK_END);
  492. long progsize = OSBasics::tell(inFile);
  493. OSBasics::seek(inFile, 0, SEEK_SET);
  494. char *buffer = (char*)malloc(progsize+1);
  495. memset(buffer, 0, progsize+1);
  496. OSBasics::read(buffer, progsize, 1, inFile);
  497. OSFILE *outFile = OSBasics::open(moduleDestPath, "wb");
  498. OSBasics::write(buffer, progsize, 1, outFile);
  499. OSBasics::close(outFile);
  500. free(buffer);
  501. OSBasics::close(inFile);
  502. loadedModules.push_back(moduleName);
  503. } else {
  504. Logger::log("Error loading module: %s\n", (*modules)[i]->stringVal.c_str());
  505. }
  506. }
  507. }
  508. }
  509. Logger::log("Mainfile: %s\n", mainFile.c_str());
  510. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  511. event->xRes = xRes;
  512. event->yRes = yRes;
  513. }
  514. createCore();
  515. core->getInput()->addEventListener(this, InputEvent::EVENT_KEYDOWN);
  516. core->getInput()->addEventListener(this, InputEvent::EVENT_KEYUP);
  517. core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEDOWN);
  518. core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEMOVE);
  519. core->getInput()->addEventListener(this, InputEvent::EVENT_MOUSEUP);
  520. if(nameString == "") {
  521. return;
  522. }
  523. Logger::log("Core created...\n");
  524. CoreServices::getInstance()->getResourceManager()->addArchive("UIThemes.pak");
  525. CoreServices::getInstance()->getConfig()->loadConfig("Polycode", "UIThemes/default/theme.xml");
  526. CoreServices::getInstance()->getResourceManager()->addArchive("api.pak");
  527. CoreServices::getInstance()->getResourceManager()->addArchive("Physics2D.pak");
  528. CoreServices::getInstance()->getResourceManager()->addArchive("Physics3D.pak");
  529. CoreServices::getInstance()->getResourceManager()->addArchive("UI.pak");
  530. if(configFile.root["packedItems"]) {
  531. ObjectEntry *packed = configFile.root["packedItems"];
  532. if(packed) {
  533. for(int i=0; i < packed->length; i++) {
  534. ObjectEntry *entryIsResource = (*(*packed)[i])["isResource"];
  535. ObjectEntry *entryPath = (*(*packed)[i])["path"];
  536. if(entryIsResource && entryPath) {
  537. if(entryIsResource->boolVal == true) {
  538. CoreServices::getInstance()->getResourceManager()->addDirResource(entryPath->stringVal, true);
  539. }
  540. }
  541. }
  542. }
  543. }
  544. core->setUserPointer(this);
  545. //core->addEventListener(this, Core::EVENT_CORE_RESIZE);
  546. core->setVideoMode(xRes, yRes, fullScreen, vSync, aaLevel, anisotropyLevel);
  547. if(textureFiltering == "nearest") {
  548. CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_NEAREST);
  549. } else {
  550. CoreServices::getInstance()->getRenderer()->setTextureFilteringMode(Renderer::TEX_FILTERING_LINEAR);
  551. }
  552. CoreServices::getInstance()->getResourceManager()->addArchive("default.pak");
  553. CoreServices::getInstance()->getResourceManager()->addDirResource("default", false);
  554. // dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);
  555. CoreServices::getInstance()->getRenderer()->setClearColor(red, green, blue);
  556. // CoreServices::getInstance()->getRenderer()->setClearColor(1,0,0);
  557. srand(core->getTicks());
  558. if(loadingArchive) {
  559. fullPath = mainFile;
  560. } else {
  561. int lindex = basePath.find_last_of("/");
  562. fullPath = basePath.substr(0, lindex);
  563. fullPath += mainFile;
  564. Logger::log(fullPath.c_str());
  565. }
  566. if(useDebugger) {
  567. remoteDebuggerClient = new PolycodeRemoteDebuggerClient();
  568. remoteDebuggerClient->addEventListener(this, Event::COMPLETE_EVENT);
  569. this->addEventListener(remoteDebuggerClient, PolycodeDebugEvent::EVENT_PRINT);
  570. this->addEventListener(remoteDebuggerClient, PolycodeDebugEvent::EVENT_ERROR);
  571. remoteDebuggerClient->client->addEventListener(this, ClientEvent::EVENT_CLIENT_READY);
  572. remoteDebuggerClient->client->addEventListener(this, ClientEvent::EVENT_SERVER_DATA);
  573. debuggerTimer = new Timer(true, 5000);
  574. debuggerTimer->addEventListener(this, Timer::EVENT_TRIGGER);
  575. } else{
  576. runFile(fullPath);
  577. }
  578. }
  579. void PolycodePlayer::runPlayer() {
  580. Logger::log("Running player\n");
  581. loadFile(fileToRun.c_str());
  582. }
  583. PolycodePlayer::~PolycodePlayer() {
  584. this->removeAllHandlers();
  585. delete remoteDebuggerClient;
  586. Logger::log("deleting core...\n");
  587. delete core;
  588. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  589. dispatchEvent(event, PolycodeDebugEvent::EVENT_REMOVE);
  590. // lua_close(L);
  591. }
  592. void PolycodePlayer::handleEvent(Event *event) {
  593. if(event->getDispatcher() == debuggerTimer) {
  594. runFile(fullPath);
  595. debuggerTimer->Pause(true);
  596. }
  597. if(remoteDebuggerClient) {
  598. if(event->getDispatcher() == remoteDebuggerClient) {
  599. if(event->getEventCode() == Event::COMPLETE_EVENT) {
  600. dispatchEvent(new PolycodeDebugEvent(), PolycodeDebugEvent::EVENT_CLOSE);
  601. }
  602. }
  603. if(event->getDispatcher() == remoteDebuggerClient->client) {
  604. ClientEvent *clientEvent = (ClientEvent*) event;
  605. switch(event->getEventCode()) {
  606. case ClientEvent::EVENT_CLIENT_READY:
  607. debuggerTimer->Pause(true);
  608. runFile(fullPath);
  609. break;
  610. case ClientEvent::EVENT_SERVER_DATA:
  611. {
  612. switch(clientEvent->dataType) {
  613. case PolycodeRemoteDebuggerClient::EVENT_INJECT_CODE:
  614. {
  615. char *code = (char*) clientEvent->data;
  616. injectCodeString = String(code);
  617. doCodeInject = true;
  618. }
  619. break;
  620. }
  621. }
  622. break;
  623. }
  624. }
  625. }
  626. if(event->getDispatcher() == core) {
  627. switch(event->getEventCode()) {
  628. case Core::EVENT_CORE_RESIZE:
  629. PolycodeDebugEvent *event = new PolycodeDebugEvent();
  630. event->xRes = core->getXRes();
  631. event->yRes = core->getYRes();
  632. dispatchEvent(event, PolycodeDebugEvent::EVENT_RESIZE);
  633. break;
  634. }
  635. }
  636. if(event->getDispatcher() == core->getInput()) {
  637. InputEvent *inputEvent = (InputEvent*) event;
  638. switch(event->getEventCode()) {
  639. case InputEvent::EVENT_KEYDOWN:
  640. {
  641. if(L && !crashed) {
  642. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  643. errH = lua_gettop(L);
  644. lua_getfield(L, LUA_GLOBALSINDEX, "onKeyDown");
  645. lua_pushinteger(L, inputEvent->keyCode());
  646. lua_pcall(L, 1,0,errH);
  647. lua_settop(L, 0);
  648. }
  649. }
  650. break;
  651. case InputEvent::EVENT_KEYUP:
  652. {
  653. if(L && !crashed) {
  654. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  655. errH = lua_gettop(L);
  656. lua_getfield(L, LUA_GLOBALSINDEX, "onKeyUp");
  657. lua_pushinteger(L, inputEvent->keyCode());
  658. lua_pcall(L, 1,0,errH);
  659. lua_settop(L, 0);
  660. }
  661. }
  662. break;
  663. case InputEvent::EVENT_MOUSEDOWN:
  664. {
  665. if(L && !crashed) {
  666. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  667. errH = lua_gettop(L);
  668. lua_getfield(L, LUA_GLOBALSINDEX, "onMouseDown");
  669. lua_pushinteger(L, inputEvent->mouseButton);
  670. lua_pushnumber(L, inputEvent->mousePosition.x);
  671. lua_pushnumber(L, inputEvent->mousePosition.y);
  672. lua_pcall(L, 3,0,errH);
  673. lua_settop(L, 0);
  674. }
  675. }
  676. break;
  677. case InputEvent::EVENT_MOUSEUP:
  678. {
  679. if(L && !crashed) {
  680. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  681. errH = lua_gettop(L);
  682. lua_getfield(L, LUA_GLOBALSINDEX, "onMouseUp");
  683. lua_pushinteger(L, inputEvent->mouseButton);
  684. lua_pushnumber(L, inputEvent->mousePosition.x);
  685. lua_pushnumber(L, inputEvent->mousePosition.y);
  686. lua_pcall(L, 3,0,errH);
  687. lua_settop(L, 0);
  688. }
  689. }
  690. break;
  691. case InputEvent::EVENT_MOUSEMOVE:
  692. {
  693. if(L && !crashed) {
  694. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  695. errH = lua_gettop(L);
  696. lua_getfield(L, LUA_GLOBALSINDEX, "onMouseMove");
  697. lua_pushnumber(L, inputEvent->mousePosition.x);
  698. lua_pushnumber(L, inputEvent->mousePosition.y);
  699. lua_pcall(L, 2,0,errH);
  700. lua_settop(L, 0);
  701. }
  702. }
  703. break;
  704. }
  705. }
  706. }
  707. bool PolycodePlayer::Update() {
  708. bool retVal = core->Update();
  709. if(L) {
  710. lua_getfield (L, LUA_GLOBALSINDEX, "__customError");
  711. errH = lua_gettop(L);
  712. if(doCodeInject) {
  713. printf("INJECTING CODE:[%s]\n", injectCodeString.c_str());
  714. doCodeInject = false;
  715. report(L, luaL_loadstring(L, injectCodeString.c_str()));
  716. lua_pcall(L, 0,0,errH);
  717. }
  718. if(!crashed) {
  719. lua_getfield(L, LUA_GLOBALSINDEX, "Update");
  720. lua_pushnumber(L, core->getElapsed());
  721. lua_pcall(L, 1,0,errH);
  722. }
  723. lua_settop(L, 0);
  724. }
  725. core->Render();
  726. return retVal;
  727. }