ScriptFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 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 "ArrayPtr.h"
  25. #include "Context.h"
  26. #include "FileSystem.h"
  27. #include "Log.h"
  28. #include "Profiler.h"
  29. #include "ResourceCache.h"
  30. #include "Script.h"
  31. #include "ScriptFile.h"
  32. #include "ScriptInstance.h"
  33. #include <angelscript.h>
  34. #include <cstring>
  35. #include "DebugNew.h"
  36. namespace Urho3D
  37. {
  38. OBJECTTYPESTATIC(ScriptFile);
  39. ScriptFile::ScriptFile(Context* context) :
  40. Resource(context),
  41. script_(GetSubsystem<Script>()),
  42. scriptModule_(0),
  43. compiled_(false)
  44. {
  45. }
  46. ScriptFile::~ScriptFile()
  47. {
  48. ReleaseModule();
  49. }
  50. void ScriptFile::RegisterObject(Context* context)
  51. {
  52. context->RegisterFactory<ScriptFile>();
  53. }
  54. bool ScriptFile::Load(Deserializer& source)
  55. {
  56. PROFILE(LoadScript);
  57. ReleaseModule();
  58. // Create the module. Discard previous module if there was one
  59. asIScriptEngine* engine = script_->GetScriptEngine();
  60. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  61. if (!scriptModule_)
  62. {
  63. LOGERROR("Failed to create script module " + GetName());
  64. return false;
  65. }
  66. // Add the initial section and check for includes
  67. if (!AddScriptSection(engine, source))
  68. return false;
  69. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  70. script_->SetLogMode(LOGMODE_RETAINED);
  71. script_->ClearLogMessages();
  72. int result = scriptModule_->Build();
  73. String errors = script_->GetLogMessages();
  74. script_->SetLogMode(LOGMODE_IMMEDIATE);
  75. if (result < 0)
  76. {
  77. LOGERROR("Failed to compile script module " + GetName() + ":\n" + errors);
  78. return false;
  79. }
  80. if (!errors.Empty())
  81. LOGWARNING(errors);
  82. LOGINFO("Compiled script module " + GetName());
  83. compiled_ = true;
  84. // Map script module to script resource with userdata
  85. scriptModule_->SetUserData(this);
  86. return true;
  87. }
  88. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  89. {
  90. if (!compiled_)
  91. return;
  92. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  93. asIScriptFunction* function = GetFunction(declaration);
  94. if (!function)
  95. {
  96. declaration = "void " + handlerName + "()";
  97. function = GetFunction(declaration);
  98. if (!function)
  99. {
  100. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  101. return;
  102. }
  103. }
  104. SubscribeToEvent(eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  105. }
  106. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  107. {
  108. if (!compiled_)
  109. return;
  110. if (!sender)
  111. {
  112. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  113. return;
  114. }
  115. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  116. asIScriptFunction* function = GetFunction(declaration);
  117. if (!function)
  118. {
  119. declaration = "void " + handlerName + "()";
  120. function = GetFunction(declaration);
  121. if (!function)
  122. {
  123. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  124. return;
  125. }
  126. }
  127. SubscribeToEvent(sender, eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  128. }
  129. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  130. {
  131. asIScriptFunction* function = GetFunction(declaration);
  132. if (!function)
  133. {
  134. LOGERROR("Function " + declaration + " not found in " + GetName());
  135. return false;
  136. }
  137. return Execute(GetFunction(declaration), parameters, unprepare);
  138. }
  139. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  140. {
  141. PROFILE(ExecuteFunction);
  142. if (!compiled_ || !function)
  143. return false;
  144. // It is possible that executing the function causes us to unload. Therefore do not rely on member variables
  145. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  146. Script* scriptSystem = script_;
  147. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  148. if (context->Prepare(function) < 0)
  149. return false;
  150. SetParameters(context, function, parameters);
  151. scriptSystem->IncScriptNestingLevel();
  152. bool success = context->Execute() >= 0;
  153. if (unprepare)
  154. context->Unprepare();
  155. scriptSystem->DecScriptNestingLevel();
  156. return success;
  157. }
  158. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  159. {
  160. asIScriptFunction* method = GetMethod(object, declaration);
  161. if (!method)
  162. {
  163. LOGERROR("Method " + declaration + " not found in " + GetName());
  164. return false;
  165. }
  166. return Execute(object, method, parameters, unprepare);
  167. }
  168. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  169. {
  170. PROFILE(ExecuteMethod);
  171. if (!compiled_ || !object || !method)
  172. return false;
  173. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  174. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  175. Script* scriptSystem = script_;
  176. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  177. if (context->Prepare(method) < 0)
  178. return false;
  179. context->SetObject(object);
  180. SetParameters(context, method, parameters);
  181. scriptSystem->IncScriptNestingLevel();
  182. bool success = context->Execute() >= 0;
  183. if (unprepare)
  184. context->Unprepare();
  185. scriptSystem->DecScriptNestingLevel();
  186. return success;
  187. }
  188. asIScriptObject* ScriptFile::CreateObject(const String& className)
  189. {
  190. PROFILE(CreateObject);
  191. if (!IsCompiled())
  192. return 0;
  193. asIScriptContext* context = script_->GetScriptFileContext();
  194. asIScriptEngine* engine = script_->GetScriptEngine();
  195. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  196. if (!type)
  197. return 0;
  198. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  199. bool found = false;
  200. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  201. if (i != validClasses_.End())
  202. found = i->second_;
  203. else
  204. {
  205. unsigned numInterfaces = type->GetInterfaceCount();
  206. for (unsigned j = 0; j < numInterfaces; ++j)
  207. {
  208. asIObjectType* interfaceType = type->GetInterface(j);
  209. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  210. {
  211. found = true;
  212. break;
  213. }
  214. }
  215. validClasses_[type] = found;
  216. }
  217. if (!found)
  218. {
  219. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  220. return 0;
  221. }
  222. // Get the factory function id from the object type
  223. String factoryName = className + "@ " + className + "()";
  224. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  225. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  226. return 0;
  227. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  228. if (obj)
  229. obj->AddRef();
  230. return obj;
  231. }
  232. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  233. {
  234. if (!compiled_)
  235. return 0;
  236. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  237. if (i != functions_.End())
  238. return i->second_;
  239. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  240. functions_[declaration] = function;
  241. return function;
  242. }
  243. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  244. {
  245. if (!compiled_ || !object)
  246. return 0;
  247. asIObjectType* type = object->GetObjectType();
  248. if (!type)
  249. return 0;
  250. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  251. if (i != methods_.End())
  252. {
  253. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  254. if (j != i->second_.End())
  255. return j->second_;
  256. }
  257. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  258. methods_[type][declaration] = function;
  259. return function;
  260. }
  261. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  262. {
  263. ResourceCache* cache = GetSubsystem<ResourceCache>();
  264. unsigned dataSize = source.GetSize();
  265. SharedArrayPtr<char> buffer(new char[dataSize]);
  266. source.Read((void*)buffer.Get(), dataSize);
  267. // Pre-parse for includes
  268. // Adapted from Angelscript's scriptbuilder add-on
  269. Vector<String> includeFiles;
  270. unsigned pos = 0;
  271. while(pos < dataSize)
  272. {
  273. int len;
  274. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  275. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  276. {
  277. pos += len;
  278. continue;
  279. }
  280. // Is this a preprocessor directive?
  281. if (buffer[pos] == '#')
  282. {
  283. int start = pos++;
  284. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  285. if (t == asTC_IDENTIFIER)
  286. {
  287. String token(&buffer[pos], len);
  288. if (token == "include")
  289. {
  290. pos += len;
  291. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  292. if (t == asTC_WHITESPACE)
  293. {
  294. pos += len;
  295. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  296. }
  297. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  298. {
  299. // Get the include file
  300. String includeFile(&buffer[pos+1], len - 2);
  301. pos += len;
  302. // If the file is not found as it is, add the path of current file
  303. if (!cache->Exists(includeFile))
  304. includeFile = GetPath(GetName()) + includeFile;
  305. String includeFileLower = includeFile.ToLower();
  306. // If not included yet, store it for later processing
  307. if (!includeFiles_.Contains(includeFileLower))
  308. {
  309. includeFiles_.Insert(includeFileLower);
  310. includeFiles.Push(includeFile);
  311. }
  312. // Overwrite the include directive with space characters to avoid compiler error
  313. memset(&buffer[start], ' ', pos - start);
  314. }
  315. }
  316. }
  317. }
  318. // Don't search includes within statement blocks or between tokens in statements
  319. else
  320. {
  321. int len;
  322. // Skip until ; or { whichever comes first
  323. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  324. {
  325. engine->ParseToken(&buffer[pos], 0, &len);
  326. pos += len;
  327. }
  328. // Skip entire statement block
  329. if (pos < dataSize && buffer[pos] == '{')
  330. {
  331. ++pos;
  332. // Find the end of the statement block
  333. int level = 1;
  334. while (level > 0 && pos < dataSize)
  335. {
  336. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  337. if (t == asTC_KEYWORD)
  338. {
  339. if (buffer[pos] == '{')
  340. ++level;
  341. else if(buffer[pos] == '}')
  342. --level;
  343. }
  344. pos += len;
  345. }
  346. }
  347. else
  348. ++pos;
  349. }
  350. }
  351. // Process includes first
  352. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  353. {
  354. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  355. if (file)
  356. {
  357. if (!AddScriptSection(engine, *file))
  358. return false;
  359. }
  360. else
  361. return false;
  362. }
  363. // Then add this section
  364. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  365. {
  366. LOGERROR("Failed to add script section " + source.GetName());
  367. return false;
  368. }
  369. SetMemoryUse(GetMemoryUse() + dataSize);
  370. return true;
  371. }
  372. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& 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. default:
  422. break;
  423. }
  424. }
  425. break;
  426. }
  427. }
  428. }
  429. void ScriptFile::ReleaseModule()
  430. {
  431. if (scriptModule_)
  432. {
  433. script_->ClearObjectTypeCache();
  434. // Clear search caches and event handlers
  435. includeFiles_.Clear();
  436. validClasses_.Clear();
  437. functions_.Clear();
  438. methods_.Clear();
  439. UnsubscribeFromAllEventsWithUserData();
  440. // Remove the module
  441. scriptModule_->SetUserData(0);
  442. asIScriptEngine* engine = script_->GetScriptEngine();
  443. engine->DiscardModule(GetName().CString());
  444. scriptModule_ = 0;
  445. compiled_ = false;
  446. SetMemoryUse(0);
  447. }
  448. }
  449. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  450. {
  451. if (!compiled_)
  452. return;
  453. asIScriptFunction* function = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  454. VariantVector parameters;
  455. if (function->GetParamCount() > 0)
  456. {
  457. parameters.Push(Variant((void*)&eventType));
  458. parameters.Push(Variant((void*)&eventData));
  459. }
  460. Execute(function, parameters);
  461. }
  462. ScriptFile* GetScriptContextFile()
  463. {
  464. asIScriptContext* context = asGetActiveContext();
  465. asIScriptFunction* function = context ? context->GetFunction() : 0;
  466. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  467. if (module)
  468. return static_cast<ScriptFile*>(module->GetUserData());
  469. else
  470. return 0;
  471. }
  472. }