ScriptFile.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "File.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ResourceCache.h"
  28. #include "ScriptEngine.h"
  29. #include "ScriptFile.h"
  30. #include "ScriptInstance.h"
  31. #include "SharedArrayPtr.h"
  32. #include "StringUtils.h"
  33. #include <angelscript.h>
  34. #include <cstring>
  35. #include "DebugNew.h"
  36. static unsigned scriptNestingLevel = 0;
  37. std::map<asIScriptModule*, ScriptFile*> moduleToFile;
  38. ScriptFile::ScriptFile(ScriptEngine* scriptEngine, const std::string& name) :
  39. Resource(name),
  40. mScriptEngine(scriptEngine),
  41. mScriptModule(0),
  42. mCompiled(false)
  43. {
  44. if (!mScriptEngine)
  45. EXCEPTION("Null script engine for ScriptFile");
  46. }
  47. ScriptFile::~ScriptFile()
  48. {
  49. releaseModule();
  50. }
  51. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  52. {
  53. PROFILE(Script_Load);
  54. // If script instances have created objects from this file, release them now
  55. // Make a copy of the vector because the script instances will remove themselves from the member vector
  56. std::vector<ScriptInstance*> instances = mScriptInstances;
  57. releaseModule();
  58. // Create the module. Discard previous module if there was one
  59. if (mScriptModule)
  60. moduleToFile.erase(mScriptModule);
  61. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  62. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  63. if (!mScriptModule)
  64. EXCEPTION("Failed to create script module " + getName());
  65. // Add the initial section and check for includes
  66. addScriptSection(engine, source, cache);
  67. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  68. mScriptEngine->setLogMode(LOGMODE_RETAINED);
  69. mScriptEngine->clearLogMessages();
  70. int result = mScriptModule->Build();
  71. std::string errors = mScriptEngine->getLogMessages();
  72. mScriptEngine->setLogMode(LOGMODE_IMMEDIATE);
  73. if (result < 0)
  74. EXCEPTION("Failed to compile script module " + getName() + ":\n" + errors);
  75. if (!errors.empty())
  76. LOGWARNING(errors);
  77. LOGINFO("Compiled script module " + getName());
  78. mCompiled = true;
  79. moduleToFile[mScriptModule] = this;
  80. // Now let the script instances recreate their objects
  81. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  82. (*i)->createObject();
  83. }
  84. void ScriptFile::addEventHandler(StringHash eventType, const std::string& handlerName)
  85. {
  86. if (!mCompiled)
  87. return;
  88. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  89. asIScriptFunction* function = getFunction(declaration);
  90. if (!function)
  91. {
  92. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  93. return;
  94. }
  95. subscribeToEvent(eventType, EVENT_HANDLER_USERDATA(ScriptFile, handleScriptEvent, (void*)function));
  96. }
  97. void ScriptFile::addEventHandler(EventListener* sender, StringHash eventType, const std::string& handlerName)
  98. {
  99. if (!mCompiled)
  100. return;
  101. if (!sender)
  102. {
  103. LOGERROR("Null event sender for event " + toString(eventType));
  104. return;
  105. }
  106. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  107. asIScriptFunction* function = getFunction(declaration);
  108. if (!function)
  109. {
  110. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  111. return;
  112. }
  113. subscribeToEvent(sender, eventType, EVENT_HANDLER_USERDATA(ScriptFile, handleSpecificScriptEvent, (void*)function));
  114. }
  115. bool ScriptFile::execute(const std::string& declaration, const std::vector<Variant>& parameters, bool unprepare)
  116. {
  117. asIScriptFunction* function = getFunction(declaration);
  118. if (!function)
  119. {
  120. LOGERROR("Function " + declaration + " not found in " + getName());
  121. return false;
  122. }
  123. return execute(getFunction(declaration), parameters, unprepare);
  124. }
  125. bool ScriptFile::execute(asIScriptFunction* function, const std::vector<Variant>& parameters, bool unprepare)
  126. {
  127. PROFILE(Script_ExecuteFunction);
  128. if ((!mCompiled) || (!function))
  129. return false;
  130. // Prevent endless loop by nested script execution
  131. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  132. {
  133. LOGERROR("Maximum script execution nesting level exceeded");
  134. return false;
  135. }
  136. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  137. if (context->Prepare(function->GetId()) < 0)
  138. return false;
  139. setParameters(context, function, parameters);
  140. ++scriptNestingLevel;
  141. bool success = context->Execute() >= 0;
  142. if (unprepare)
  143. context->Unprepare();
  144. --scriptNestingLevel;
  145. return success;
  146. }
  147. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, const std::vector<Variant>& parameters, bool unprepare)
  148. {
  149. asIScriptFunction* method = getMethod(object, declaration);
  150. if (!method)
  151. {
  152. LOGERROR("Method " + declaration + " not found in " + getName());
  153. return false;
  154. }
  155. return execute(object, method, parameters, unprepare);
  156. }
  157. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, const std::vector<Variant>& parameters, bool unprepare)
  158. {
  159. PROFILE(Script_ExecuteMethod);
  160. if ((!mCompiled) || (!object) || (!method))
  161. return false;
  162. // Prevent endless loop by nested script execution
  163. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  164. {
  165. LOGERROR("Maximum script execution nesting level exceeded");
  166. return false;
  167. }
  168. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  169. // If context is active, allocate a temp context to allow nested execution.
  170. if (context->Prepare(method->GetId()) < 0)
  171. return false;
  172. context->SetObject(object);
  173. setParameters(context, method, parameters);
  174. ++scriptNestingLevel;
  175. bool success = context->Execute() >= 0;
  176. if (unprepare)
  177. context->Unprepare();
  178. --scriptNestingLevel;
  179. return success;
  180. }
  181. asIScriptObject* ScriptFile::createObject(const std::string& className)
  182. {
  183. PROFILE(Script_CreateObject);
  184. if (!isCompiled())
  185. return 0;
  186. // Prevent endless loop by nested script execution
  187. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  188. {
  189. LOGERROR("Maximum script execution nesting level exceeded, can not create object");
  190. return 0;
  191. }
  192. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  193. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  194. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  195. if (!type)
  196. return 0;
  197. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  198. bool found = false;
  199. std::map<asIObjectType*, bool>::const_iterator i = mCheckedClasses.find(type);
  200. if (i != mCheckedClasses.end())
  201. found = i->second;
  202. else
  203. {
  204. unsigned numInterfaces = type->GetInterfaceCount();
  205. for (unsigned j = 0; j < numInterfaces; ++j)
  206. {
  207. asIObjectType* interfaceType = type->GetInterface(j);
  208. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  209. {
  210. found = true;
  211. break;
  212. }
  213. }
  214. mCheckedClasses[type] = found;
  215. }
  216. if (!found)
  217. {
  218. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  219. return 0;
  220. }
  221. // Get the factory function id from the object type
  222. std::string factoryName = className + "@ " + className + "()";
  223. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  224. if (factoryId < 0)
  225. return 0;
  226. if (context->Prepare(factoryId) < 0)
  227. return 0;
  228. if (context->Execute() < 0)
  229. return 0;
  230. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  231. if (obj)
  232. obj->AddRef();
  233. return obj;
  234. }
  235. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration)
  236. {
  237. if (!mCompiled)
  238. return 0;
  239. std::map<std::string, asIScriptFunction*>::const_iterator i = mFunctions.find(declaration);
  240. if (i != mFunctions.end())
  241. return i->second;
  242. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  243. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  244. mFunctions[declaration] = function;
  245. return function;
  246. }
  247. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration)
  248. {
  249. if ((!mCompiled) || (!object))
  250. return 0;
  251. asIObjectType* type = object->GetObjectType();
  252. if (!type)
  253. return 0;
  254. std::map<asIObjectType*, std::map<std::string, asIScriptFunction*> >::const_iterator i = mMethods.find(type);
  255. if (i != mMethods.end())
  256. {
  257. std::map<std::string, asIScriptFunction*>::const_iterator j = i->second.find(declaration);
  258. if (j != i->second.end())
  259. return j->second;
  260. }
  261. int id = type->GetMethodIdByDecl(declaration.c_str());
  262. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  263. mMethods[type][declaration] = function;
  264. return function;
  265. }
  266. void ScriptFile::addScriptInstance(ScriptInstance* instance)
  267. {
  268. mScriptInstances.push_back(instance);
  269. }
  270. void ScriptFile::removeScriptInstance(ScriptInstance* instance)
  271. {
  272. for (std::vector<ScriptInstance*>::iterator i = mScriptInstances.begin(); i != mScriptInstances.end(); ++i)
  273. {
  274. if ((*i) == instance)
  275. {
  276. mScriptInstances.erase(i);
  277. break;
  278. }
  279. }
  280. }
  281. void ScriptFile::addScriptSection(asIScriptEngine* engine, Deserializer& source, ResourceCache* cache)
  282. {
  283. unsigned dataSize = source.getSize();
  284. SharedArrayPtr<char> buffer(new char[dataSize]);
  285. source.read((void*)buffer.getPtr(), dataSize);
  286. // Pre-parse for includes
  287. // Adapted from Angelscript's scriptbuilder add-on
  288. std::vector<std::string> includeFiles;
  289. unsigned pos = 0;
  290. while(pos < dataSize)
  291. {
  292. int len;
  293. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  294. if ((t == asTC_COMMENT) || (t == asTC_WHITESPACE))
  295. {
  296. pos += len;
  297. continue;
  298. }
  299. // Is this a preprocessor directive?
  300. if (buffer[pos] == '#')
  301. {
  302. int start = pos++;
  303. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  304. if (t == asTC_IDENTIFIER)
  305. {
  306. std::string token(&buffer[pos], len);
  307. if (token == "include")
  308. {
  309. pos += len;
  310. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  311. if (t == asTC_WHITESPACE)
  312. {
  313. pos += len;
  314. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  315. }
  316. if ((t == asTC_VALUE) && (len > 2) && (buffer[pos] == '"'))
  317. {
  318. // Get the include file
  319. std::string includeFile(&buffer[pos+1], len - 2);
  320. pos += len;
  321. // If the file is not found as it is, add the path of current file
  322. if (!cache->exists(includeFile))
  323. includeFile = getPath(getName()) + includeFile;
  324. std::string includeFileLower = toLower(includeFile);
  325. // If not included yet, store it for later processing
  326. if (mAllIncludeFiles.find(includeFileLower) == mAllIncludeFiles.end())
  327. {
  328. mAllIncludeFiles.insert(includeFileLower);
  329. includeFiles.push_back(includeFile);
  330. }
  331. // Overwrite the include directive with space characters to avoid compiler error
  332. memset(&buffer[start], ' ', pos - start);
  333. }
  334. }
  335. }
  336. }
  337. // Don't search includes within statement blocks or between tokens in statements
  338. else
  339. {
  340. int len;
  341. // Skip until ; or { whichever comes first
  342. while ((pos < dataSize) && (buffer[pos] != ';') && (buffer[pos] != '{' ))
  343. {
  344. engine->ParseToken(&buffer[pos], 0, &len);
  345. pos += len;
  346. }
  347. // Skip entire statement block
  348. if ((pos < dataSize) && (buffer[pos] == '{' ))
  349. {
  350. ++pos;
  351. // Find the end of the statement block
  352. int level = 1;
  353. while ((level > 0) && (pos < dataSize))
  354. {
  355. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  356. if (t == asTC_KEYWORD)
  357. {
  358. if (buffer[pos] == '{')
  359. level++;
  360. else if(buffer[pos] == '}')
  361. level--;
  362. }
  363. pos += len;
  364. }
  365. }
  366. else
  367. ++pos;
  368. }
  369. }
  370. // Process includes first
  371. for (unsigned i = 0; i < includeFiles.size(); ++i)
  372. {
  373. SharedPtr<File> file = cache->getFile(includeFiles[i]);
  374. addScriptSection(engine, *file, cache);
  375. }
  376. // Then add this section
  377. if (mScriptModule->AddScriptSection(source.getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  378. EXCEPTION("Failed to add script section " + source.getName());
  379. setMemoryUse(getMemoryUse() + dataSize);
  380. }
  381. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  382. {
  383. unsigned paramCount = function->GetParamCount();
  384. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  385. {
  386. int paramType = function->GetParamTypeId(i);
  387. switch (paramType)
  388. {
  389. case asTYPEID_BOOL:
  390. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  391. break;
  392. case asTYPEID_INT8:
  393. case asTYPEID_UINT8:
  394. context->SetArgByte(i, parameters[i].getInt());
  395. break;
  396. case asTYPEID_INT16:
  397. case asTYPEID_UINT16:
  398. context->SetArgWord(i, parameters[i].getInt());
  399. break;
  400. case asTYPEID_INT32:
  401. case asTYPEID_UINT32:
  402. context->SetArgDWord(i, parameters[i].getInt());
  403. break;
  404. case asTYPEID_FLOAT:
  405. context->SetArgFloat(i, parameters[i].getFloat());
  406. break;
  407. default:
  408. if (paramType & asTYPEID_APPOBJECT)
  409. {
  410. switch (parameters[i].getType())
  411. {
  412. case VAR_VECTOR2:
  413. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  414. break;
  415. case VAR_VECTOR3:
  416. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  417. break;
  418. case VAR_VECTOR4:
  419. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  420. break;
  421. case VAR_QUATERNION:
  422. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  423. break;
  424. case VAR_STRING:
  425. context->SetArgObject(i, (void *)&parameters[i].getString());
  426. break;
  427. case VAR_PTR:
  428. context->SetArgObject(i, (void *)parameters[i].getPtr());
  429. break;
  430. }
  431. }
  432. break;
  433. }
  434. }
  435. }
  436. void ScriptFile::releaseModule()
  437. {
  438. if (mScriptModule)
  439. {
  440. // Release script instances if any exist
  441. std::vector<ScriptInstance*> instances = mScriptInstances;
  442. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  443. (*i)->releaseObject();
  444. // Clear search caches, event handlers and function-to-file mappings
  445. mAllIncludeFiles.clear();
  446. mCheckedClasses.clear();
  447. mFunctions.clear();
  448. mMethods.clear();
  449. removeAllEventHandlers();
  450. // Perform a full garbage collection cycle now
  451. mScriptEngine->garbageCollect(true);
  452. // Remove the module
  453. moduleToFile.erase(mScriptModule);
  454. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  455. engine->DiscardModule(getName().c_str());
  456. mScriptModule = 0;
  457. mCompiled = false;
  458. setMemoryUse(0);
  459. }
  460. }
  461. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  462. {
  463. if (!mCompiled)
  464. return;
  465. std::vector<Variant> parameters;
  466. parameters.push_back(Variant((void*)&eventType));
  467. parameters.push_back(Variant((void*)&eventData));
  468. execute(static_cast<asIScriptFunction*>(getInvoker()->getUserData()), parameters);
  469. }
  470. void ScriptFile::handleSpecificScriptEvent(StringHash eventType, VariantMap& eventData)
  471. {
  472. if (!mCompiled)
  473. return;
  474. std::vector<Variant> parameters;
  475. parameters.push_back(Variant((void*)&eventType));
  476. parameters.push_back(Variant((void*)&eventData));
  477. execute(static_cast<asIScriptFunction*>(getInvoker()->getUserData()), parameters);
  478. }
  479. ScriptFile* getScriptContextFile()
  480. {
  481. asIScriptFunction* function = asGetActiveContext()->GetFunction();
  482. asIScriptModule* module = function->GetEngine()->GetModule(function->GetModuleName());
  483. std::map<asIScriptModule*, ScriptFile*>::const_iterator i = moduleToFile.find(module);
  484. if (i != moduleToFile.end())
  485. return i->second;
  486. else
  487. return 0;
  488. }
  489. unsigned getScriptNestingLevel()
  490. {
  491. return scriptNestingLevel;
  492. }