ScriptFile.cpp 19 KB

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