ScriptFile.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 "Deserializer.h"
  25. #include "Log.h"
  26. #include "Profiler.h"
  27. #include "ScriptEngine.h"
  28. #include "ScriptFile.h"
  29. #include "SharedArrayPtr.h"
  30. #include <angelscript.h>
  31. #include "DebugNew.h"
  32. static const int MAX_NESTING_LEVEL = 32;
  33. static int executeNestingLevel = 0;
  34. ScriptFile* lastScriptFile = 0;
  35. ScriptFile::ScriptFile(ScriptEngine* scriptEngine, const std::string& name) :
  36. Resource(name),
  37. mScriptEngine(scriptEngine),
  38. mScriptModule(0),
  39. mScriptContext(0),
  40. mCompiled(false)
  41. {
  42. if (!mScriptEngine)
  43. EXCEPTION("Null script engine for ScriptFile");
  44. }
  45. ScriptFile::~ScriptFile()
  46. {
  47. if (mScriptModule)
  48. {
  49. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  50. engine->DiscardModule(getName().c_str());
  51. mScriptModule = 0;
  52. }
  53. if (mScriptContext)
  54. {
  55. mScriptContext->Release();
  56. mScriptContext = 0;
  57. }
  58. if (lastScriptFile == this)
  59. lastScriptFile = 0;
  60. }
  61. void ScriptFile::load(Deserializer& source, ResourceCache* cache)
  62. {
  63. PROFILE(Script_Load);
  64. unsigned dataSize = source.getSize();
  65. SharedArrayPtr<unsigned char> buffer(new unsigned char[dataSize]);
  66. source.read((void*)buffer.getPtr(), dataSize);
  67. // Discard the previous module if there was one
  68. mCompiled = false;
  69. setMemoryUse(0);
  70. removeAllEventHandlers();
  71. // Create the module
  72. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  73. mScriptModule = engine->GetModule(getName().c_str(), asGM_ALWAYS_CREATE);
  74. if (!mScriptModule)
  75. EXCEPTION("Failed to create script module " + getName());
  76. if (mScriptModule->AddScriptSection(getName().c_str(), (const char*)buffer.getPtr(), dataSize) < 0)
  77. EXCEPTION("Failed to add script section for script module " + getName());
  78. if (mScriptModule->Build() < 0)
  79. EXCEPTION("Failed to build script module " + getName());
  80. LOGINFO("Compiled script module " + getName());
  81. setMemoryUse(dataSize);
  82. mCompiled = true;
  83. }
  84. void ScriptFile::addEventHandler(StringHash eventType, const std::string& handlerName)
  85. {
  86. if (!mCompiled)
  87. return;
  88. std::string declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  89. asIScriptFunction* function = getFunction(declaration);
  90. if (!function)
  91. {
  92. LOGERROR("Event handler function " + declaration + " not found in " + getName());
  93. return;
  94. }
  95. subscribeToEvent(eventType, EVENT_HANDLER(ScriptFile, handleScriptEvent));
  96. mEventHandlers[eventType] = function;
  97. // Create a context for script event handling if does not exist already
  98. if (!mScriptContext)
  99. mScriptContext = mScriptEngine->createScriptContext();
  100. }
  101. bool ScriptFile::execute(const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  102. {
  103. asIScriptFunction* function = getFunction(declaration);
  104. if (!function)
  105. {
  106. LOGERROR("Function " + declaration + " not found in " + getName());
  107. return false;
  108. }
  109. return execute(getFunction(declaration), context, parameters);
  110. }
  111. bool ScriptFile::execute(asIScriptFunction* function, asIScriptContext* context, const std::vector<Variant>& parameters)
  112. {
  113. PROFILE(Script_ExecuteFunction);
  114. if ((!mCompiled) || (!function))
  115. return false;
  116. if (!context)
  117. context = mScriptEngine->getImmediateContext();
  118. if (context->GetState() != asEXECUTION_ACTIVE)
  119. {
  120. if (context->Prepare(function->GetId()) < 0)
  121. return false;
  122. setParameters(context, function, parameters);
  123. return context->Execute() >= 0;
  124. }
  125. else
  126. {
  127. // Prevent endless loop by nested script event handling
  128. if (executeNestingLevel > MAX_NESTING_LEVEL)
  129. {
  130. LOGERROR("Maximum script execution nesting level exceeded");
  131. return false;
  132. }
  133. // If context is active, allocate a temp context to allow nested execution.
  134. // This is not recommended for performance reasons
  135. LOGDEBUG("Executing " + std::string(function->GetDeclaration()) + " in a temporary script context");
  136. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  137. tempContext->SetUserData(context->GetUserData());
  138. if (tempContext->Prepare(function->GetId()) < 0)
  139. {
  140. tempContext->Release();
  141. return false;
  142. }
  143. setParameters(tempContext, function, parameters);
  144. ++executeNestingLevel;
  145. bool success = tempContext->Execute() >= 0;
  146. tempContext->Release();
  147. --executeNestingLevel;
  148. return success;
  149. }
  150. }
  151. bool ScriptFile::execute(asIScriptObject* object, const std::string& declaration, asIScriptContext* context, const std::vector<Variant>& parameters)
  152. {
  153. asIScriptFunction* method = getMethod(object, declaration);
  154. if (!method)
  155. {
  156. LOGERROR("Method " + declaration + " not found in " + getName());
  157. return false;
  158. }
  159. return execute(object, method, context, parameters);
  160. }
  161. bool ScriptFile::execute(asIScriptObject* object, asIScriptFunction* method, asIScriptContext* context,
  162. const std::vector<Variant>& parameters)
  163. {
  164. PROFILE(Script_ExecuteMethod);
  165. if ((!mCompiled) || (!object) || (!method))
  166. return false;
  167. if (!context)
  168. context = mScriptEngine->getImmediateContext();
  169. if (context->GetState() != asEXECUTION_ACTIVE)
  170. {
  171. if (context->Prepare(method->GetId()) < 0)
  172. return false;
  173. context->SetObject(object);
  174. setParameters(context, method, parameters);
  175. return context->Execute() >= 0;
  176. }
  177. else
  178. {
  179. // Prevent endless loop by nested script event handling
  180. if (executeNestingLevel > MAX_NESTING_LEVEL)
  181. {
  182. LOGERROR("Maximum script execution nesting level exceeded");
  183. return false;
  184. }
  185. // If context is active, allocate a temp context to allow nested execution.
  186. // This is not recommended for performance reasons
  187. LOGDEBUG("Executing " + std::string(method->GetDeclaration()) + " in a temporary script context");
  188. asIScriptContext* tempContext = mScriptEngine->createScriptContext();
  189. tempContext->SetUserData(context->GetUserData());
  190. if (tempContext->Prepare(method->GetId()) < 0)
  191. {
  192. tempContext->Release();
  193. return false;
  194. }
  195. tempContext->SetObject(object);
  196. setParameters(tempContext, method, parameters);
  197. ++executeNestingLevel;
  198. bool success = tempContext->Execute() >= 0;
  199. tempContext->Release();
  200. --executeNestingLevel;
  201. return success;
  202. }
  203. }
  204. asIScriptObject* ScriptFile::createObject(const std::string& className, asIScriptContext* context)
  205. {
  206. PROFILE(Script_CreateObject);
  207. if (!isCompiled())
  208. return 0;
  209. if (!context)
  210. context = mScriptEngine->getImmediateContext();
  211. asIScriptEngine* engine = mScriptEngine->getAngelScriptEngine();
  212. asIObjectType *type = engine->GetObjectTypeById(mScriptModule->GetTypeIdByDecl(className.c_str()));
  213. if (!type)
  214. return 0;
  215. // Get the factory function id from the object type
  216. std::string factoryName = className + "@ " + className + "()";
  217. int factoryId = type->GetFactoryIdByDecl(factoryName.c_str());
  218. if (factoryId < 0)
  219. return 0;
  220. if (context->Prepare(factoryId) < 0)
  221. return 0;
  222. if (context->Execute() < 0)
  223. return 0;
  224. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  225. if (obj)
  226. obj->AddRef();
  227. return obj;
  228. }
  229. asIScriptFunction* ScriptFile::getFunction(const std::string& declaration) const
  230. {
  231. if (!mCompiled)
  232. return 0;
  233. int id = mScriptModule->GetFunctionIdByDecl(declaration.c_str());
  234. return mScriptModule->GetFunctionDescriptorById(id);
  235. }
  236. asIScriptFunction* ScriptFile::getMethod(asIScriptObject* object, const std::string& declaration) const
  237. {
  238. if ((!mCompiled) || (!object))
  239. return 0;
  240. asIObjectType* type = object->GetObjectType();
  241. if (!type)
  242. return 0;
  243. int id = type->GetMethodIdByDecl(declaration.c_str());
  244. return mScriptModule->GetFunctionDescriptorById(id);
  245. }
  246. void ScriptFile::setParameters(asIScriptContext* context, asIScriptFunction* function, const std::vector<Variant>& parameters)
  247. {
  248. lastScriptFile = this;
  249. unsigned paramCount = function->GetParamCount();
  250. for (unsigned i = 0; (i < parameters.size()) && (i < paramCount); ++i)
  251. {
  252. int paramType = function->GetParamTypeId(i);
  253. switch (paramType)
  254. {
  255. case asTYPEID_BOOL:
  256. context->SetArgByte(i, (unsigned char)parameters[i].getBool());
  257. break;
  258. case asTYPEID_INT8:
  259. case asTYPEID_UINT8:
  260. context->SetArgByte(i, parameters[i].getInt());
  261. break;
  262. case asTYPEID_INT16:
  263. case asTYPEID_UINT16:
  264. context->SetArgWord(i, parameters[i].getInt());
  265. break;
  266. case asTYPEID_INT32:
  267. case asTYPEID_UINT32:
  268. context->SetArgDWord(i, parameters[i].getInt());
  269. break;
  270. case asTYPEID_FLOAT:
  271. context->SetArgFloat(i, parameters[i].getFloat());
  272. break;
  273. default:
  274. if (paramType & asTYPEID_APPOBJECT)
  275. {
  276. switch (parameters[i].getType())
  277. {
  278. case VAR_VECTOR2:
  279. context->SetArgObject(i, (void *)&parameters[i].getVector2());
  280. break;
  281. case VAR_VECTOR3:
  282. context->SetArgObject(i, (void *)&parameters[i].getVector3());
  283. break;
  284. case VAR_VECTOR4:
  285. context->SetArgObject(i, (void *)&parameters[i].getVector4());
  286. break;
  287. case VAR_QUATERNION:
  288. context->SetArgObject(i, (void *)&parameters[i].getQuaternion());
  289. break;
  290. case VAR_STRING:
  291. context->SetArgObject(i, (void *)&parameters[i].getString());
  292. break;
  293. case VAR_PTR:
  294. context->SetArgObject(i, (void *)parameters[i].getPtr());
  295. break;
  296. }
  297. }
  298. break;
  299. }
  300. }
  301. }
  302. void ScriptFile::handleScriptEvent(StringHash eventType, VariantMap& eventData)
  303. {
  304. if (!mCompiled)
  305. return;
  306. std::map<StringHash, asIScriptFunction*>::iterator i = mEventHandlers.find(eventType);
  307. if (i == mEventHandlers.end())
  308. return;
  309. std::vector<Variant> parameters;
  310. parameters.push_back(Variant((void*)&eventType));
  311. parameters.push_back(Variant((void*)&eventData));
  312. execute(i->second, mScriptContext, parameters);
  313. }
  314. ScriptFile* getLastScriptFile()
  315. {
  316. return lastScriptFile;
  317. }