ScriptFile.cpp 19 KB

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