ScriptFile.cpp 18 KB

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