ScriptFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. //
  2. // Copyright (c) 2008-2013 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "Precompiled.h"
  23. #include "ArrayPtr.h"
  24. #include "Context.h"
  25. #include "FileSystem.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "ResourceCache.h"
  29. #include "Script.h"
  30. #include "ScriptFile.h"
  31. #include "ScriptInstance.h"
  32. #include <angelscript.h>
  33. #include <cstring>
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. OBJECTTYPESTATIC(ScriptFile);
  38. ScriptFile::ScriptFile(Context* context) :
  39. Resource(context),
  40. script_(GetSubsystem<Script>()),
  41. scriptModule_(0),
  42. compiled_(false)
  43. {
  44. }
  45. ScriptFile::~ScriptFile()
  46. {
  47. ReleaseModule();
  48. }
  49. void ScriptFile::RegisterObject(Context* context)
  50. {
  51. context->RegisterFactory<ScriptFile>();
  52. }
  53. bool ScriptFile::Load(Deserializer& source)
  54. {
  55. PROFILE(LoadScript);
  56. ReleaseModule();
  57. // Create the module. Discard previous module if there was one
  58. asIScriptEngine* engine = script_->GetScriptEngine();
  59. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  60. if (!scriptModule_)
  61. {
  62. LOGERROR("Failed to create script module " + GetName());
  63. return false;
  64. }
  65. // Add the initial section and check for includes
  66. if (!AddScriptSection(engine, source))
  67. return false;
  68. // Compile. Set script engine logging to retained mode so that potential exceptions can show all error info
  69. ScriptLogMode oldLogMode = script_->GetLogMode();
  70. script_->SetLogMode(LOGMODE_RETAINED);
  71. script_->ClearLogMessages();
  72. int result = scriptModule_->Build();
  73. String errors = script_->GetLogMessages();
  74. script_->SetLogMode(oldLogMode);
  75. if (result < 0)
  76. {
  77. LOGERROR("Failed to compile script module " + GetName() + ":\n" + errors);
  78. ResourceCache* cache = GetSubsystem<ResourceCache>();
  79. // if a script is compiled error we also tell resource cache do not
  80. // remove it from resource group if auto reload is true.
  81. return cache->GetAutoReloadResources();
  82. }
  83. if (!errors.Empty())
  84. LOGWARNING(errors);
  85. LOGINFO("Compiled script module " + GetName());
  86. compiled_ = true;
  87. // Map script module to script resource with userdata
  88. scriptModule_->SetUserData(this);
  89. return true;
  90. }
  91. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  92. {
  93. if (!compiled_)
  94. return;
  95. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  96. asIScriptFunction* function = GetFunction(declaration);
  97. if (!function)
  98. {
  99. declaration = "void " + handlerName + "()";
  100. function = GetFunction(declaration);
  101. if (!function)
  102. {
  103. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  104. return;
  105. }
  106. }
  107. SubscribeToEvent(eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  108. }
  109. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  110. {
  111. if (!compiled_)
  112. return;
  113. if (!sender)
  114. {
  115. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  116. return;
  117. }
  118. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  119. asIScriptFunction* function = GetFunction(declaration);
  120. if (!function)
  121. {
  122. declaration = "void " + handlerName + "()";
  123. function = GetFunction(declaration);
  124. if (!function)
  125. {
  126. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  127. return;
  128. }
  129. }
  130. SubscribeToEvent(sender, eventType, HANDLER_USERDATA(ScriptFile, HandleScriptEvent, (void*)function));
  131. }
  132. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  133. {
  134. asIScriptFunction* function = GetFunction(declaration);
  135. if (!function)
  136. {
  137. LOGERROR("Function " + declaration + " not found in " + GetName());
  138. return false;
  139. }
  140. return Execute(function, parameters, unprepare);
  141. }
  142. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  143. {
  144. PROFILE(ExecuteFunction);
  145. if (!compiled_ || !function)
  146. return false;
  147. // It is possible that executing the function causes us to unload. Therefore do not rely on member variables
  148. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  149. Script* scriptSystem = script_;
  150. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  151. if (context->Prepare(function) < 0)
  152. return false;
  153. SetParameters(context, function, parameters);
  154. scriptSystem->IncScriptNestingLevel();
  155. bool success = context->Execute() >= 0;
  156. if (unprepare)
  157. context->Unprepare();
  158. scriptSystem->DecScriptNestingLevel();
  159. return success;
  160. }
  161. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  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, parameters, unprepare);
  170. }
  171. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  172. {
  173. PROFILE(ExecuteMethod);
  174. if (!compiled_ || !object || !method)
  175. return false;
  176. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  177. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  178. Script* scriptSystem = script_;
  179. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  180. if (context->Prepare(method) < 0)
  181. return false;
  182. context->SetObject(object);
  183. SetParameters(context, method, parameters);
  184. scriptSystem->IncScriptNestingLevel();
  185. bool success = context->Execute() >= 0;
  186. if (unprepare)
  187. context->Unprepare();
  188. scriptSystem->DecScriptNestingLevel();
  189. return success;
  190. }
  191. asIScriptObject* ScriptFile::CreateObject(const String& className)
  192. {
  193. PROFILE(CreateObject);
  194. if (!compiled_)
  195. return 0;
  196. asIScriptContext* context = script_->GetScriptFileContext();
  197. asIScriptEngine* engine = script_->GetScriptEngine();
  198. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  199. if (!type)
  200. return 0;
  201. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  202. bool found = false;
  203. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  204. if (i != validClasses_.End())
  205. found = i->second_;
  206. else
  207. {
  208. unsigned numInterfaces = type->GetInterfaceCount();
  209. for (unsigned j = 0; j < numInterfaces; ++j)
  210. {
  211. asIObjectType* interfaceType = type->GetInterface(j);
  212. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  213. {
  214. found = true;
  215. break;
  216. }
  217. }
  218. validClasses_[type] = found;
  219. }
  220. if (!found)
  221. {
  222. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  223. return 0;
  224. }
  225. // Get the factory function id from the object type
  226. String factoryName = className + "@ " + className + "()";
  227. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  228. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  229. return 0;
  230. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  231. if (obj)
  232. obj->AddRef();
  233. return obj;
  234. }
  235. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  236. {
  237. if (!compiled_)
  238. return 0;
  239. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  240. if (i != functions_.End())
  241. return i->second_;
  242. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  243. functions_[declaration] = function;
  244. return function;
  245. }
  246. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  247. {
  248. if (!compiled_ || !object)
  249. return 0;
  250. asIObjectType* type = object->GetObjectType();
  251. if (!type)
  252. return 0;
  253. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  254. if (i != methods_.End())
  255. {
  256. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  257. if (j != i->second_.End())
  258. return j->second_;
  259. }
  260. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  261. methods_[type][declaration] = function;
  262. return function;
  263. }
  264. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  265. {
  266. ResourceCache* cache = GetSubsystem<ResourceCache>();
  267. unsigned dataSize = source.GetSize();
  268. SharedArrayPtr<char> buffer(new char[dataSize]);
  269. source.Read((void*)buffer.Get(), dataSize);
  270. // Pre-parse for includes
  271. // Adapted from Angelscript's scriptbuilder add-on
  272. Vector<String> includeFiles;
  273. unsigned pos = 0;
  274. while(pos < dataSize)
  275. {
  276. int len;
  277. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  278. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  279. {
  280. pos += len;
  281. continue;
  282. }
  283. // Is this a preprocessor directive?
  284. if (buffer[pos] == '#')
  285. {
  286. int start = pos++;
  287. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  288. if (t == asTC_IDENTIFIER)
  289. {
  290. String token(&buffer[pos], len);
  291. if (token == "include")
  292. {
  293. pos += len;
  294. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  295. if (t == asTC_WHITESPACE)
  296. {
  297. pos += len;
  298. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  299. }
  300. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  301. {
  302. // Get the include file
  303. String includeFile(&buffer[pos+1], len - 2);
  304. pos += len;
  305. // If the file is not found as it is, add the path of current file
  306. if (!cache->Exists(includeFile))
  307. includeFile = GetPath(GetName()) + includeFile;
  308. String includeFileLower = includeFile.ToLower();
  309. // If not included yet, store it for later processing
  310. if (!includeFiles_.Contains(includeFileLower))
  311. {
  312. includeFiles_.Insert(includeFileLower);
  313. includeFiles.Push(includeFile);
  314. }
  315. // Overwrite the include directive with space characters to avoid compiler error
  316. memset(&buffer[start], ' ', pos - start);
  317. }
  318. }
  319. }
  320. }
  321. // Don't search includes within statement blocks or between tokens in statements
  322. else
  323. {
  324. int len;
  325. // Skip until ; or { whichever comes first
  326. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  327. {
  328. engine->ParseToken(&buffer[pos], 0, &len);
  329. pos += len;
  330. }
  331. // Skip entire statement block
  332. if (pos < dataSize && buffer[pos] == '{')
  333. {
  334. ++pos;
  335. // Find the end of the statement block
  336. int level = 1;
  337. while (level > 0 && pos < dataSize)
  338. {
  339. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  340. if (t == asTC_KEYWORD)
  341. {
  342. if (buffer[pos] == '{')
  343. ++level;
  344. else if(buffer[pos] == '}')
  345. --level;
  346. }
  347. pos += len;
  348. }
  349. }
  350. else
  351. ++pos;
  352. }
  353. }
  354. // Process includes first
  355. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  356. {
  357. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  358. if (file)
  359. {
  360. if (!AddScriptSection(engine, *file))
  361. return false;
  362. }
  363. else
  364. return false;
  365. }
  366. // Then add this section
  367. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  368. {
  369. LOGERROR("Failed to add script section " + source.GetName());
  370. return false;
  371. }
  372. SetMemoryUse(GetMemoryUse() + dataSize);
  373. return true;
  374. }
  375. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  376. {
  377. unsigned paramCount = function->GetParamCount();
  378. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  379. {
  380. int paramType = function->GetParamTypeId(i);
  381. switch (paramType)
  382. {
  383. case asTYPEID_BOOL:
  384. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  385. break;
  386. case asTYPEID_INT8:
  387. case asTYPEID_UINT8:
  388. context->SetArgByte(i, parameters[i].GetInt());
  389. break;
  390. case asTYPEID_INT16:
  391. case asTYPEID_UINT16:
  392. context->SetArgWord(i, parameters[i].GetInt());
  393. break;
  394. case asTYPEID_INT32:
  395. case asTYPEID_UINT32:
  396. context->SetArgDWord(i, parameters[i].GetInt());
  397. break;
  398. case asTYPEID_FLOAT:
  399. context->SetArgFloat(i, parameters[i].GetFloat());
  400. break;
  401. default:
  402. if (paramType & asTYPEID_APPOBJECT)
  403. {
  404. switch (parameters[i].GetType())
  405. {
  406. case VAR_VECTOR2:
  407. context->SetArgObject(i, (void *)&parameters[i].GetVector2());
  408. break;
  409. case VAR_VECTOR3:
  410. context->SetArgObject(i, (void *)&parameters[i].GetVector3());
  411. break;
  412. case VAR_VECTOR4:
  413. context->SetArgObject(i, (void *)&parameters[i].GetVector4());
  414. break;
  415. case VAR_QUATERNION:
  416. context->SetArgObject(i, (void *)&parameters[i].GetQuaternion());
  417. break;
  418. case VAR_STRING:
  419. context->SetArgObject(i, (void *)&parameters[i].GetString());
  420. break;
  421. case VAR_PTR:
  422. context->SetArgObject(i, (void *)parameters[i].GetPtr());
  423. break;
  424. default:
  425. break;
  426. }
  427. }
  428. break;
  429. }
  430. }
  431. }
  432. void ScriptFile::ReleaseModule()
  433. {
  434. if (scriptModule_)
  435. {
  436. script_->ClearObjectTypeCache();
  437. // Clear search caches and event handlers
  438. includeFiles_.Clear();
  439. validClasses_.Clear();
  440. functions_.Clear();
  441. methods_.Clear();
  442. UnsubscribeFromAllEventsWithUserData();
  443. // Remove the module
  444. scriptModule_->SetUserData(0);
  445. asIScriptEngine* engine = script_->GetScriptEngine();
  446. engine->DiscardModule(GetName().CString());
  447. scriptModule_ = 0;
  448. compiled_ = false;
  449. SetMemoryUse(0);
  450. }
  451. }
  452. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  453. {
  454. if (!compiled_)
  455. return;
  456. asIScriptFunction* function = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  457. VariantVector parameters;
  458. if (function->GetParamCount() > 0)
  459. {
  460. parameters.Push(Variant((void*)&eventType));
  461. parameters.Push(Variant((void*)&eventData));
  462. }
  463. Execute(function, parameters);
  464. }
  465. ScriptFile* GetScriptContextFile()
  466. {
  467. asIScriptContext* context = asGetActiveContext();
  468. asIScriptFunction* function = context ? context->GetFunction() : 0;
  469. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  470. if (module)
  471. return static_cast<ScriptFile*>(module->GetUserData());
  472. else
  473. return 0;
  474. }
  475. }