ScriptFile.cpp 18 KB

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