ScriptFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  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 int scriptNestingLevel = 0;
  37. ScriptFile* lastScriptFile = 0;
  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. if (mScriptModule)
  50. {
  51. // Release script instances if any exist
  52. std::vector<ScriptInstance*> instances = mScriptInstances;
  53. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  54. (*i)->releaseObject();
  55. // Remove the module
  56. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  57. engine->DiscardModule(getName().c_str());
  58. mScriptModule = 0;
  59. // Perform a full garbage collection cycle
  60. mScriptEngine->garbageCollect(true);
  61. }
  62. if (lastScriptFile == this)
  63. lastScriptFile = 0;
  64. }
  65. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  66. {
  67. PROFILE(Script_Load);
  68. // If script instances have created objects from this file, release them now
  69. // Make a copy of the vector because the script instances will remove themselves from the member vector
  70. std::vector<ScriptInstance*> instances = mScriptInstances;
  71. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  72. (*i)->releaseObject();
  73. // Clear search caches
  74. mCompiled = false;
  75. mAllIncludeFiles.clear();
  76. mCheckedClasses.clear();
  77. mFunctions.clear();
  78. mMethods.clear();
  79. setMemoryUse(0);
  80. removeAllEventHandlers();
  81. // Create the module. Discard previous module if there was one
  82. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  83. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  84. if (!mScriptModule)
  85. EXCEPTION("Failed to create script module " + getName());
  86. // Add the initial section and check for includes
  87. addScriptSection(engine, source, cache);
  88. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  89. mScriptEngine->setLogMode(LOGMODE_RETAINED);
  90. mScriptEngine->clearLogMessages();
  91. int result = mScriptModule->Build();
  92. mScriptEngine->setLogMode(LOGMODE_IMMEDIATE);
  93. if (result < 0)
  94. {
  95. std::string errors = mScriptEngine->getLogMessages();
  96. EXCEPTION("Failed to compile script module " + getName() + ":\n" + errors);
  97. }
  98. LOGINFO("Compiled script module " + getName());
  99. mCompiled = true;
  100. // Now let the script instances recreate their objects
  101. for (std::vector<ScriptInstance*>::iterator i = instances.begin(); i != instances.end(); ++i)
  102. (*i)->createObject();
  103. }
  104. void ScriptFile::addEventHandler(StringHash eventType, const std::string& handlerName)
  105. {
  106. if (!mCompiled)
  107. return;
  108. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  109. asIScriptFunction* function = getFunction(declaration);
  110. if (!function)
  111. {
  112. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  113. return;
  114. }
  115. subscribeToEvent(eventType, EVENT_HANDLER(ScriptFile, handleScriptEvent));
  116. mEventHandlers[eventType] = function;
  117. }
  118. bool ScriptFile::execute(const std::string& declaration, const std::vector<Variant>& parameters)
  119. {
  120. asIScriptFunction* function = getFunction(declaration);
  121. if (!function)
  122. {
  123. LOGERROR("Function " + declaration + " not found in " + getName());
  124. return false;
  125. }
  126. return execute(getFunction(declaration), parameters);
  127. }
  128. bool ScriptFile::execute(asIScriptFunction* function, const std::vector<Variant>& parameters)
  129. {
  130. PROFILE(Script_ExecuteFunction);
  131. if ((!mCompiled) || (!function))
  132. return false;
  133. // Prevent endless loop by nested script execution
  134. if (scriptNestingLevel >= MAX_SCRIPT_NESTING_LEVEL)
  135. {
  136. LOGERROR("Maximum script execution nesting level exceeded");
  137. return false;
  138. }
  139. asIScriptContext* context = mScriptEngine->getScriptFileContext(scriptNestingLevel);
  140. if (context->Prepare(function->GetId()) < 0)
  141. return false;
  142. lastScriptFile = this;
  143. setParameters(context, function, parameters);
  144. ++scriptNestingLevel;
  145. bool success = context->Execute() >= 0;
  146. --scriptNestingLevel;
  147. return success;
  148. }
  149. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, const std::vector<Variant>& parameters)
  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);
  158. }
  159. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, const std::vector<Variant>& parameters)
  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. --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::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  437. {
  438. if (!mCompiled)
  439. return;
  440. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  441. if (i == mEventHandlers.end())
  442. return;
  443. std::vector<Variant> parameters;
  444. parameters.push_back(Variant((void*)&eventType));
  445. parameters.push_back(Variant((void*)&eventData));
  446. execute(i->second, parameters);
  447. }
  448. ScriptFile* getLastScriptFile()
  449. {
  450. return lastScriptFile;
  451. }
  452. unsigned getScriptNestingLevel()
  453. {
  454. return scriptNestingLevel;
  455. }