ScriptFile.cpp 17 KB

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