ScriptFile.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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(ScriptFile, handleScriptEvent));
  96. mEventHandlers[eventType] = function;
  97. }
  98. void ScriptFile::addEventHandler(EventListener* sender, StringHash eventType, const std::string& handlerName)
  99. {
  100. if (!mCompiled)
  101. return;
  102. if (!sender)
  103. {
  104. LOGERROR("Null event sender for event " + toString(eventType));
  105. return;
  106. }
  107. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  108. asIScriptFunction* function = getFunction(declaration);
  109. if (!function)
  110. {
  111. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  112. return;
  113. }
  114. subscribeToEvent(sender, eventType, EVENT_HANDLER(ScriptFile, handleSpecificScriptEvent));
  115. mSpecificEventHandlers[std::make_pair(sender, eventType)] = function;
  116. }
  117. bool ScriptFile::execute(const std::string& declaration, const std::vector<Variant>& parameters, bool unprepare)
  118. {
  119. asIScriptFunction* function = getFunction(declaration);
  120. if (!function)
  121. {
  122. LOGERROR("Function " + declaration + " not found in " + getName());
  123. return false;
  124. }
  125. return execute(getFunction(declaration), parameters, unprepare);
  126. }
  127. bool ScriptFile::execute(asIScriptFunction* function, const std::vector<Variant>& parameters, bool unprepare)
  128. {
  129. PROFILE(Script_ExecuteFunction);
  130. if ((!mCompiled) || (!function))
  131. return false;
  132. // Prevent endless loop by nested script execution
  133. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  134. {
  135. LOGERROR("Maximum script execution nesting level exceeded");
  136. return false;
  137. }
  138. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  139. if (context->Prepare(function->GetId()) < 0)
  140. return false;
  141. setParameters(context, function, parameters);
  142. ++scriptNestingLevel;
  143. bool success = context->Execute() >= 0;
  144. if (unprepare)
  145. context->Unprepare();
  146. --scriptNestingLevel;
  147. return success;
  148. }
  149. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, const std::vector<Variant>& parameters, bool unprepare)
  150. {
  151. asIScriptFunction* method = getMethod(object, declaration);
  152. if (!method)
  153. {
  154. LOGERROR("Method " + declaration + " not found in " + getName());
  155. return false;
  156. }
  157. return execute(object, method, parameters, unprepare);
  158. }
  159. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, const std::vector<Variant>& parameters, bool unprepare)
  160. {
  161. PROFILE(Script_ExecuteMethod);
  162. if ((!mCompiled) || (!object) || (!method))
  163. return false;
  164. // Prevent endless loop by nested script execution
  165. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  166. {
  167. LOGERROR("Maximum script execution nesting level exceeded");
  168. return false;
  169. }
  170. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  171. // If context is active, allocate a temp context to allow nested execution.
  172. if (context->Prepare(method->GetId()) < 0)
  173. return false;
  174. context->SetObject(object);
  175. setParameters(context, method, parameters);
  176. ++scriptNestingLevel;
  177. bool success = context->Execute() >= 0;
  178. if (unprepare)
  179. context->Unprepare();
  180. --scriptNestingLevel;
  181. return success;
  182. }
  183. asIScriptObject* ScriptFile::createObject(const std::string& className)
  184. {
  185. PROFILE(Script_CreateObject);
  186. if (!isCompiled())
  187. return 0;
  188. // Prevent endless loop by nested script execution
  189. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  190. {
  191. LOGERROR("Maximum script execution nesting level exceeded, can not create object");
  192. return 0;
  193. }
  194. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  195. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  196. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  197. if (!type)
  198. return 0;
  199. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  200. bool found = false;
  201. std::map<asIObjectType*, bool>::const_iterator i = mCheckedClasses.find(type);
  202. if (i != mCheckedClasses.end())
  203. found = i->second;
  204. else
  205. {
  206. unsigned numInterfaces = type->GetInterfaceCount();
  207. for (unsigned j = 0; j < numInterfaces; ++j)
  208. {
  209. asIObjectType* interfaceType = type->GetInterface(j);
  210. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  211. {
  212. found = true;
  213. break;
  214. }
  215. }
  216. mCheckedClasses[type] = found;
  217. }
  218. if (!found)
  219. {
  220. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  221. return 0;
  222. }
  223. // Get the factory function id from the object type
  224. std::string factoryName = className + "@ " + className + "()";
  225. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  226. if (factoryId < 0)
  227. return 0;
  228. if (context->Prepare(factoryId) < 0)
  229. return 0;
  230. if (context->Execute() < 0)
  231. return 0;
  232. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  233. if (obj)
  234. obj->AddRef();
  235. return obj;
  236. }
  237. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration)
  238. {
  239. if (!mCompiled)
  240. return 0;
  241. std::map<std::string, asIScriptFunction*>::const_iterator i = mFunctions.find(declaration);
  242. if (i != mFunctions.end())
  243. return i->second;
  244. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  245. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  246. mFunctions[declaration] = function;
  247. return function;
  248. }
  249. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration)
  250. {
  251. if ((!mCompiled) || (!object))
  252. return 0;
  253. asIObjectType* type = object->GetObjectType();
  254. if (!type)
  255. return 0;
  256. std::map<asIObjectType*, std::map<std::string, asIScriptFunction*> >::const_iterator i = mMethods.find(type);
  257. if (i != mMethods.end())
  258. {
  259. std::map<std::string, asIScriptFunction*>::const_iterator j = i->second.find(declaration);
  260. if (j != i->second.end())
  261. return j->second;
  262. }
  263. int id = type->GetMethodIdByDecl(declaration.c_str());
  264. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  265. mMethods[type][declaration] = function;
  266. return function;
  267. }
  268. void ScriptFile::addScriptInstance(ScriptInstance* instance)
  269. {
  270. mScriptInstances.push_back(instance);
  271. }
  272. void ScriptFile::removeScriptInstance(ScriptInstance* instance)
  273. {
  274. for (std::vector<ScriptInstance*>::iterator i = mScriptInstances.begin(); i != mScriptInstances.end(); ++i)
  275. {
  276. if ((*i) == instance)
  277. {
  278. mScriptInstances.erase(i);
  279. break;
  280. }
  281. }
  282. }
  283. void ScriptFile::addScriptSection(asIScriptEngine* engine, Deserializer& source, ResourceCache* cache)
  284. {
  285. unsigned dataSize = source.getSize();
  286. SharedArrayPtr<char> buffer(new char[dataSize]);
  287. source.read((void*)buffer.getPtr(), dataSize);
  288. // Pre-parse for includes
  289. // Adapted from Angelscript's scriptbuilder add-on
  290. std::vector<std::string> includeFiles;
  291. unsigned pos = 0;
  292. while(pos < dataSize)
  293. {
  294. int len;
  295. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  296. if ((t == asTC_COMMENT) || (t == asTC_WHITESPACE))
  297. {
  298. pos += len;
  299. continue;
  300. }
  301. // Is this a preprocessor directive?
  302. if (buffer[pos] == '#')
  303. {
  304. int start = pos++;
  305. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  306. if (t == asTC_IDENTIFIER)
  307. {
  308. std::string token(&buffer[pos], len);
  309. if (token == "include")
  310. {
  311. pos += len;
  312. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  313. if (t == asTC_WHITESPACE)
  314. {
  315. pos += len;
  316. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  317. }
  318. if ((t == asTC_VALUE) && (len > 2) && (buffer[pos] == '"'))
  319. {
  320. // Get the include file
  321. std::string includeFile(&buffer[pos+1], len - 2);
  322. pos += len;
  323. // If the file is not found as it is, add the path of current file
  324. if (!cache->exists(includeFile))
  325. includeFile = getPath(getName()) + includeFile;
  326. std::string includeFileLower = toLower(includeFile);
  327. // If not included yet, store it for later processing
  328. if (mAllIncludeFiles.find(includeFileLower) == mAllIncludeFiles.end())
  329. {
  330. mAllIncludeFiles.insert(includeFileLower);
  331. includeFiles.push_back(includeFile);
  332. }
  333. // Overwrite the include directive with space characters to avoid compiler error
  334. memset(&buffer[start], ' ', pos - start);
  335. }
  336. }
  337. }
  338. }
  339. // Don't search includes within statement blocks or between tokens in statements
  340. else
  341. {
  342. int len;
  343. // Skip until ; or { whichever comes first
  344. while ((pos < dataSize) && (buffer[pos] != ';') && (buffer[pos] != '{' ))
  345. {
  346. engine->ParseToken(&buffer[pos], 0, &len);
  347. pos += len;
  348. }
  349. // Skip entire statement block
  350. if ((pos < dataSize) && (buffer[pos] == '{' ))
  351. {
  352. ++pos;
  353. // Find the end of the statement block
  354. int level = 1;
  355. while ((level > 0) && (pos < dataSize))
  356. {
  357. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  358. if (t == asTC_KEYWORD)
  359. {
  360. if (buffer[pos] == '{')
  361. level++;
  362. else if(buffer[pos] == '}')
  363. level--;
  364. }
  365. pos += len;
  366. }
  367. }
  368. else
  369. ++pos;
  370. }
  371. }
  372. // Process includes first
  373. for (unsigned i = 0; i < includeFiles.size(); ++i)
  374. {
  375. SharedPtr<File> file = cache->getFile(includeFiles[i]);
  376. addScriptSection(engine, *file, cache);
  377. }
  378. // Then add this section
  379. if (mScriptModule->AddScriptSection(source.getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  380. EXCEPTION("Failed to add script section " + source.getName());
  381. setMemoryUse(getMemoryUse() + dataSize);
  382. }
  383. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  384. {
  385. unsigned paramCount = function->GetParamCount();
  386. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  387. {
  388. int paramType = function->GetParamTypeId(i);
  389. switch (paramType)
  390. {
  391. case asTYPEID_BOOL:
  392. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  393. break;
  394. case asTYPEID_INT8:
  395. case asTYPEID_UINT8:
  396. context->SetArgByte(i, parameters[i].getInt());
  397. break;
  398. case asTYPEID_INT16:
  399. case asTYPEID_UINT16:
  400. context->SetArgWord(i, parameters[i].getInt());
  401. break;
  402. case asTYPEID_INT32:
  403. case asTYPEID_UINT32:
  404. context->SetArgDWord(i, parameters[i].getInt());
  405. break;
  406. case asTYPEID_FLOAT:
  407. context->SetArgFloat(i, parameters[i].getFloat());
  408. break;
  409. default:
  410. if (paramType & asTYPEID_APPOBJECT)
  411. {
  412. switch (parameters[i].getType())
  413. {
  414. case VAR_VECTOR2:
  415. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  416. break;
  417. case VAR_VECTOR3:
  418. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  419. break;
  420. case VAR_VECTOR4:
  421. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  422. break;
  423. case VAR_QUATERNION:
  424. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  425. break;
  426. case VAR_STRING:
  427. context->SetArgObject(i, (void *)&parameters[i].getString());
  428. break;
  429. case VAR_PTR:
  430. context->SetArgObject(i, (void *)parameters[i].getPtr());
  431. break;
  432. }
  433. }
  434. break;
  435. }
  436. }
  437. }
  438. void ScriptFile::releaseModule()
  439. {
  440. if (mScriptModule)
  441. {
  442. // Release script instances if any exist
  443. std::vector<ScriptInstance*> instances = mScriptInstances;
  444. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  445. (*i)->releaseObject();
  446. // Clear search caches, event handlers and function-to-file mappings
  447. mAllIncludeFiles.clear();
  448. mCheckedClasses.clear();
  449. mFunctions.clear();
  450. mMethods.clear();
  451. removeAllEventHandlers();
  452. // Perform a full garbage collection cycle now
  453. mScriptEngine->garbageCollect(true);
  454. // Remove the module
  455. moduleToFile.erase(mScriptModule);
  456. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  457. engine->DiscardModule(getName().c_str());
  458. mScriptModule = 0;
  459. mCompiled = false;
  460. setMemoryUse(0);
  461. }
  462. }
  463. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  464. {
  465. if (!mCompiled)
  466. return;
  467. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  468. if (i == mEventHandlers.end())
  469. return;
  470. std::vector<Variant> parameters;
  471. parameters.push_back(Variant((void*)&eventType));
  472. parameters.push_back(Variant((void*)&eventData));
  473. execute(i->second, parameters);
  474. }
  475. void ScriptFile::handleSpecificScriptEvent(StringHash eventType, VariantMap& eventData)
  476. {
  477. if (!mCompiled)
  478. return;
  479. std::map<std::pair<EventListener*, StringHash>, asIScriptFunction*>::iterator i = mSpecificEventHandlers.find(std::make_pair(
  480. getEventSender(), eventType));
  481. if (i == mSpecificEventHandlers.end())
  482. return;
  483. std::vector<Variant> parameters;
  484. parameters.push_back(Variant((void*)&eventType));
  485. parameters.push_back(Variant((void*)&eventData));
  486. execute(i->second, parameters);
  487. }
  488. ScriptFile* getScriptContextFile()
  489. {
  490. asIScriptFunction* function = asGetActiveContext()->GetFunction();
  491. asIScriptModule* module = function->GetEngine()->GetModule(function->GetModuleName());
  492. std::map<asIScriptModule*, ScriptFile*>::const_iterator i = moduleToFile.find(module);
  493. if (i != moduleToFile.end())
  494. return i->second;
  495. else
  496. return 0;
  497. }
  498. unsigned getScriptNestingLevel()
  499. {
  500. return scriptNestingLevel;
  501. }