ScriptFile.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. static unsigned highestScriptNestingLevel = 0;
  38. ScriptFile* lastScriptFile = 0;
  39. ScriptFile::ScriptFile(ScriptEngine* scriptEngine, const std::string& name) :
  40. Resource(name),
  41. mScriptEngine(scriptEngine),
  42. mScriptModule(0),
  43. mCompiled(false)
  44. {
  45. if (!mScriptEngine)
  46. EXCEPTION("Null script engine for ScriptFile");
  47. }
  48. ScriptFile::~ScriptFile()
  49. {
  50. if (mScriptModule)
  51. {
  52. // Release script instances if any exist
  53. std::vector<ScriptInstance*> instances = mScriptInstances;
  54. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  55. (*i)->releaseObject();
  56. // Perform a full garbage collection cycle, also clean up contexts which might still refer to the module's functions
  57. mScriptEngine->garbageCollect(true);
  58. // Remove the module
  59. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  60. engine->DiscardModule(getName().c_str());
  61. mScriptModule = 0;
  62. }
  63. if (lastScriptFile == this)
  64. lastScriptFile = 0;
  65. }
  66. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  67. {
  68. PROFILE(Script_Load);
  69. // If script instances have created objects from this file, release them now
  70. // Make a copy of the vector because the script instances will remove themselves from the member vector
  71. std::vector<ScriptInstance*> instances = mScriptInstances;
  72. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  73. (*i)->releaseObject();
  74. // Clear search caches
  75. mCompiled = false;
  76. mAllIncludeFiles.clear();
  77. mCheckedClasses.clear();
  78. mFunctions.clear();
  79. mMethods.clear();
  80. setMemoryUse(0);
  81. removeAllEventHandlers();
  82. // Create the module. Discard previous module if there was one
  83. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  84. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  85. if (!mScriptModule)
  86. EXCEPTION("Failed to create script module " + getName());
  87. // Add the initial section and check for includes
  88. addScriptSection(engine, source, cache);
  89. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  90. mScriptEngine->setLogMode(LOGMODE_RETAINED);
  91. mScriptEngine->clearLogMessages();
  92. int result = mScriptModule->Build();
  93. std::string errors = mScriptEngine->getLogMessages();
  94. mScriptEngine->setLogMode(LOGMODE_IMMEDIATE);
  95. if (result < 0)
  96. EXCEPTION("Failed to compile script module " + getName() + ":\n" + errors);
  97. if (!errors.empty())
  98. LOGWARNING(errors);
  99. LOGINFO("Compiled script module " + getName());
  100. mCompiled = true;
  101. // Now let the script instances recreate their objects
  102. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  103. (*i)->createObject();
  104. }
  105. void ScriptFile::addEventHandler(StringHash eventType, const std::string& handlerName)
  106. {
  107. if (!mCompiled)
  108. return;
  109. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  110. asIScriptFunction* function = getFunction(declaration);
  111. if (!function)
  112. {
  113. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  114. return;
  115. }
  116. subscribeToEvent(eventType, EVENT_HANDLER(ScriptFile, handleScriptEvent));
  117. mEventHandlers[eventType] = function;
  118. }
  119. bool ScriptFile::execute(const std::string& declaration, const std::vector<Variant>& parameters)
  120. {
  121. asIScriptFunction* function = getFunction(declaration);
  122. if (!function)
  123. {
  124. LOGERROR("Function " + declaration + " not found in " + getName());
  125. return false;
  126. }
  127. return execute(getFunction(declaration), parameters);
  128. }
  129. bool ScriptFile::execute(asIScriptFunction* function, const std::vector<Variant>& parameters)
  130. {
  131. PROFILE(Script_ExecuteFunction);
  132. if ((!mCompiled) || (!function))
  133. return false;
  134. // Prevent endless loop by nested script execution
  135. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  136. {
  137. LOGERROR("Maximum script execution nesting level exceeded");
  138. return false;
  139. }
  140. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  141. if (context->Prepare(function->GetId()) < 0)
  142. return false;
  143. lastScriptFile = this;
  144. setParameters(context, function, parameters);
  145. ++scriptNestingLevel;
  146. if (scriptNestingLevel > highestScriptNestingLevel)
  147. highestScriptNestingLevel = scriptNestingLevel;
  148. bool success = context->Execute() >= 0;
  149. --scriptNestingLevel;
  150. return success;
  151. }
  152. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, const std::vector<Variant>& parameters)
  153. {
  154. asIScriptFunction* method = getMethod(object, declaration);
  155. if (!method)
  156. {
  157. LOGERROR("Method " + declaration + " not found in " + getName());
  158. return false;
  159. }
  160. return execute(object, method, parameters);
  161. }
  162. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, const std::vector<Variant>& parameters)
  163. {
  164. PROFILE(Script_ExecuteMethod);
  165. if ((!mCompiled) || (!object) || (!method))
  166. return false;
  167. // Prevent endless loop by nested script execution
  168. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  169. {
  170. LOGERROR("Maximum script execution nesting level exceeded");
  171. return false;
  172. }
  173. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  174. // If context is active, allocate a temp context to allow nested execution.
  175. if (context->Prepare(method->GetId()) < 0)
  176. return false;
  177. context->SetObject(object);
  178. setParameters(context, method, parameters);
  179. ++scriptNestingLevel;
  180. if (scriptNestingLevel > highestScriptNestingLevel)
  181. highestScriptNestingLevel = scriptNestingLevel;
  182. bool success = context->Execute() >= 0;
  183. --scriptNestingLevel;
  184. return success;
  185. }
  186. asIScriptObject* ScriptFile::createObject(const std::string& className)
  187. {
  188. PROFILE(Script_CreateObject);
  189. if (!isCompiled())
  190. return 0;
  191. // Prevent endless loop by nested script execution
  192. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  193. {
  194. LOGERROR("Maximum script execution nesting level exceeded, can not create object");
  195. return 0;
  196. }
  197. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  198. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  199. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  200. if (!type)
  201. return 0;
  202. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  203. bool found = false;
  204. std::map<asIObjectType*, bool>::const_iterator i = mCheckedClasses.find(type);
  205. if (i != mCheckedClasses.end())
  206. found = i->second;
  207. else
  208. {
  209. unsigned numInterfaces = type->GetInterfaceCount();
  210. for (unsigned j = 0; j < numInterfaces; ++j)
  211. {
  212. asIObjectType* interfaceType = type->GetInterface(j);
  213. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  214. {
  215. found = true;
  216. break;
  217. }
  218. }
  219. mCheckedClasses[type] = found;
  220. }
  221. if (!found)
  222. {
  223. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  224. return 0;
  225. }
  226. // Get the factory function id from the object type
  227. std::string factoryName = className + "@ " + className + "()";
  228. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  229. if (factoryId < 0)
  230. return 0;
  231. if (context->Prepare(factoryId) < 0)
  232. return 0;
  233. if (context->Execute() < 0)
  234. return 0;
  235. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  236. if (obj)
  237. obj->AddRef();
  238. return obj;
  239. }
  240. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration)
  241. {
  242. if (!mCompiled)
  243. return 0;
  244. std::map<std::string, asIScriptFunction*>::const_iterator i = mFunctions.find(declaration);
  245. if (i != mFunctions.end())
  246. return i->second;
  247. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  248. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  249. mFunctions[declaration] = function;
  250. return function;
  251. }
  252. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration)
  253. {
  254. if ((!mCompiled) || (!object))
  255. return 0;
  256. asIObjectType* type = object->GetObjectType();
  257. if (!type)
  258. return 0;
  259. std::map<asIObjectType*, std::map<std::string, asIScriptFunction*> >::const_iterator i = mMethods.find(type);
  260. if (i != mMethods.end())
  261. {
  262. std::map<std::string, asIScriptFunction*>::const_iterator j = i->second.find(declaration);
  263. if (j != i->second.end())
  264. return j->second;
  265. }
  266. int id = type->GetMethodIdByDecl(declaration.c_str());
  267. asIScriptFunction* function = mScriptModule->GetFunctionDescriptorById(id);
  268. mMethods[type][declaration] = function;
  269. return function;
  270. }
  271. void ScriptFile::addScriptInstance(ScriptInstance* instance)
  272. {
  273. mScriptInstances.push_back(instance);
  274. }
  275. void ScriptFile::removeScriptInstance(ScriptInstance* instance)
  276. {
  277. for (std::vector<ScriptInstance*>::iterator i = mScriptInstances.begin(); i != mScriptInstances.end(); ++i)
  278. {
  279. if ((*i) == instance)
  280. {
  281. mScriptInstances.erase(i);
  282. break;
  283. }
  284. }
  285. }
  286. void ScriptFile::addScriptSection(asIScriptEngine* engine, Deserializer& source, ResourceCache* cache)
  287. {
  288. unsigned dataSize = source.getSize();
  289. SharedArrayPtr<char> buffer(new char[dataSize]);
  290. source.read((void*)buffer.getPtr(), dataSize);
  291. // Pre-parse for includes
  292. // Adapted from Angelscript's scriptbuilder add-on
  293. std::vector<std::string> includeFiles;
  294. unsigned pos = 0;
  295. while(pos < dataSize)
  296. {
  297. int len;
  298. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  299. if ((t == asTC_COMMENT) || (t == asTC_WHITESPACE))
  300. {
  301. pos += len;
  302. continue;
  303. }
  304. // Is this a preprocessor directive?
  305. if (buffer[pos] == '#')
  306. {
  307. int start = pos++;
  308. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  309. if (t == asTC_IDENTIFIER)
  310. {
  311. std::string token(&buffer[pos], len);
  312. if (token == "include")
  313. {
  314. pos += len;
  315. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  316. if (t == asTC_WHITESPACE)
  317. {
  318. pos += len;
  319. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  320. }
  321. if ((t == asTC_VALUE) && (len > 2) && (buffer[pos] == '"'))
  322. {
  323. // Get the include file
  324. std::string includeFile(&buffer[pos+1], len - 2);
  325. pos += len;
  326. // If the file is not found as it is, add the path of current file
  327. if (!cache->exists(includeFile))
  328. includeFile = getPath(getName()) + includeFile;
  329. std::string includeFileLower = toLower(includeFile);
  330. // If not included yet, store it for later processing
  331. if (mAllIncludeFiles.find(includeFileLower) == mAllIncludeFiles.end())
  332. {
  333. mAllIncludeFiles.insert(includeFileLower);
  334. includeFiles.push_back(includeFile);
  335. }
  336. // Overwrite the include directive with space characters to avoid compiler error
  337. memset(&buffer[start], ' ', pos - start);
  338. }
  339. }
  340. }
  341. }
  342. // Don't search includes within statement blocks or between tokens in statements
  343. else
  344. {
  345. int len;
  346. // Skip until ; or { whichever comes first
  347. while ((pos < dataSize) && (buffer[pos] != ';') && (buffer[pos] != '{' ))
  348. {
  349. engine->ParseToken(&buffer[pos], 0, &len);
  350. pos += len;
  351. }
  352. // Skip entire statement block
  353. if ((pos < dataSize) && (buffer[pos] == '{' ))
  354. {
  355. ++pos;
  356. // Find the end of the statement block
  357. int level = 1;
  358. while ((level > 0) && (pos < dataSize))
  359. {
  360. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  361. if (t == asTC_KEYWORD)
  362. {
  363. if (buffer[pos] == '{')
  364. level++;
  365. else if(buffer[pos] == '}')
  366. level--;
  367. }
  368. pos += len;
  369. }
  370. }
  371. else
  372. ++pos;
  373. }
  374. }
  375. // Process includes first
  376. for (unsigned i = 0; i < includeFiles.size(); ++i)
  377. {
  378. SharedPtr<File> file = cache->getFile(includeFiles[i]);
  379. addScriptSection(engine, *file, cache);
  380. }
  381. // Then add this section
  382. if (mScriptModule->AddScriptSection(source.getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  383. EXCEPTION("Failed to add script section " + source.getName());
  384. setMemoryUse(getMemoryUse() + dataSize);
  385. }
  386. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  387. {
  388. unsigned paramCount = function->GetParamCount();
  389. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  390. {
  391. int paramType = function->GetParamTypeId(i);
  392. switch (paramType)
  393. {
  394. case asTYPEID_BOOL:
  395. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  396. break;
  397. case asTYPEID_INT8:
  398. case asTYPEID_UINT8:
  399. context->SetArgByte(i, parameters[i].getInt());
  400. break;
  401. case asTYPEID_INT16:
  402. case asTYPEID_UINT16:
  403. context->SetArgWord(i, parameters[i].getInt());
  404. break;
  405. case asTYPEID_INT32:
  406. case asTYPEID_UINT32:
  407. context->SetArgDWord(i, parameters[i].getInt());
  408. break;
  409. case asTYPEID_FLOAT:
  410. context->SetArgFloat(i, parameters[i].getFloat());
  411. break;
  412. default:
  413. if (paramType & asTYPEID_APPOBJECT)
  414. {
  415. switch (parameters[i].getType())
  416. {
  417. case VAR_VECTOR2:
  418. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  419. break;
  420. case VAR_VECTOR3:
  421. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  422. break;
  423. case VAR_VECTOR4:
  424. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  425. break;
  426. case VAR_QUATERNION:
  427. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  428. break;
  429. case VAR_STRING:
  430. context->SetArgObject(i, (void *)&parameters[i].getString());
  431. break;
  432. case VAR_PTR:
  433. context->SetArgObject(i, (void *)parameters[i].getPtr());
  434. break;
  435. }
  436. }
  437. break;
  438. }
  439. }
  440. }
  441. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  442. {
  443. if (!mCompiled)
  444. return;
  445. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  446. if (i == mEventHandlers.end())
  447. return;
  448. std::vector<Variant> parameters;
  449. parameters.push_back(Variant((void*)&eventType));
  450. parameters.push_back(Variant((void*)&eventData));
  451. execute(i->second, parameters);
  452. }
  453. ScriptFile* getLastScriptFile()
  454. {
  455. return lastScriptFile;
  456. }
  457. unsigned getScriptNestingLevel()
  458. {
  459. return scriptNestingLevel;
  460. }
  461. unsigned getHighestScriptNestingLevel()
  462. {
  463. unsigned ret = highestScriptNestingLevel;
  464. highestScriptNestingLevel = 0;
  465. return ret;
  466. }