ScriptFile.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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->Prepare(function) < 0)
  147. return false;
  148. SetParameters(context, function, parameters);
  149. scriptSystem->IncScriptNestingLevel();
  150. bool success = context->Execute() >= 0;
  151. if (unprepare)
  152. context->Unprepare();
  153. scriptSystem->DecScriptNestingLevel();
  154. return success;
  155. }
  156. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  157. {
  158. asIScriptFunction* method = GetMethod(object, declaration);
  159. if (!method)
  160. {
  161. LOGERROR("Method " + declaration + " not found in " + GetName());
  162. return false;
  163. }
  164. return Execute(object, method, parameters, unprepare);
  165. }
  166. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  167. {
  168. PROFILE(ExecuteMethod);
  169. if (!compiled_ || !object || !method)
  170. return false;
  171. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  172. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  173. Script* scriptSystem = script_;
  174. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  175. if (context->Prepare(method) < 0)
  176. return false;
  177. context->SetObject(object);
  178. SetParameters(context, method, parameters);
  179. scriptSystem->IncScriptNestingLevel();
  180. bool success = context->Execute() >= 0;
  181. if (unprepare)
  182. context->Unprepare();
  183. scriptSystem->DecScriptNestingLevel();
  184. return success;
  185. }
  186. asIScriptObject* ScriptFile::CreateObject(const String& className)
  187. {
  188. PROFILE(CreateObject);
  189. if (!IsCompiled())
  190. return 0;
  191. asIScriptContext* context = script_->GetScriptFileContext();
  192. asIScriptEngine* engine = script_->GetScriptEngine();
  193. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  194. if (!type)
  195. return 0;
  196. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  197. bool found = false;
  198. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  199. if (i != validClasses_.End())
  200. found = i->second_;
  201. else
  202. {
  203. unsigned numInterfaces = type->GetInterfaceCount();
  204. for (unsigned j = 0; j < numInterfaces; ++j)
  205. {
  206. asIObjectType* interfaceType = type->GetInterface(j);
  207. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  208. {
  209. found = true;
  210. break;
  211. }
  212. }
  213. validClasses_[type] = found;
  214. }
  215. if (!found)
  216. {
  217. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  218. return 0;
  219. }
  220. // Get the factory function id from the object type
  221. String factoryName = className + "@ " + className + "()";
  222. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  223. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  224. return 0;
  225. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  226. if (obj)
  227. obj->AddRef();
  228. return obj;
  229. }
  230. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  231. {
  232. if (!compiled_)
  233. return 0;
  234. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  235. if (i != functions_.End())
  236. return i->second_;
  237. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  238. functions_[declaration] = function;
  239. return function;
  240. }
  241. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  242. {
  243. if (!compiled_ || !object)
  244. return 0;
  245. asIObjectType* type = object->GetObjectType();
  246. if (!type)
  247. return 0;
  248. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  249. if (i != methods_.End())
  250. {
  251. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  252. if (j != i->second_.End())
  253. return j->second_;
  254. }
  255. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  256. methods_[type][declaration] = function;
  257. return function;
  258. }
  259. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  260. {
  261. ResourceCache* cache = GetSubsystem<ResourceCache>();
  262. unsigned dataSize = source.GetSize();
  263. SharedArrayPtr<char> buffer(new char[dataSize]);
  264. source.Read((void*)buffer.Get(), dataSize);
  265. // Pre-parse for includes
  266. // Adapted from Angelscript's scriptbuilder add-on
  267. Vector<String> includeFiles;
  268. unsigned pos = 0;
  269. while(pos < dataSize)
  270. {
  271. int len;
  272. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  273. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  274. {
  275. pos += len;
  276. continue;
  277. }
  278. // Is this a preprocessor directive?
  279. if (buffer[pos] == '#')
  280. {
  281. int start = pos++;
  282. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  283. if (t == asTC_IDENTIFIER)
  284. {
  285. String token(&buffer[pos], len);
  286. if (token == "include")
  287. {
  288. pos += len;
  289. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  290. if (t == asTC_WHITESPACE)
  291. {
  292. pos += len;
  293. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  294. }
  295. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  296. {
  297. // Get the include file
  298. String includeFile(&buffer[pos+1], len - 2);
  299. pos += len;
  300. // If the file is not found as it is, add the path of current file
  301. if (!cache->Exists(includeFile))
  302. includeFile = GetPath(GetName()) + includeFile;
  303. String includeFileLower = includeFile.ToLower();
  304. // If not included yet, store it for later processing
  305. if (!includeFiles_.Contains(includeFileLower))
  306. {
  307. includeFiles_.Insert(includeFileLower);
  308. includeFiles.Push(includeFile);
  309. }
  310. // Overwrite the include directive with space characters to avoid compiler error
  311. memset(&buffer[start], ' ', pos - start);
  312. }
  313. }
  314. }
  315. }
  316. // Don't search includes within statement blocks or between tokens in statements
  317. else
  318. {
  319. int len;
  320. // Skip until ; or { whichever comes first
  321. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  322. {
  323. engine->ParseToken(&buffer[pos], 0, &len);
  324. pos += len;
  325. }
  326. // Skip entire statement block
  327. if (pos < dataSize && buffer[pos] == '{')
  328. {
  329. ++pos;
  330. // Find the end of the statement block
  331. int level = 1;
  332. while (level > 0 && pos < dataSize)
  333. {
  334. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  335. if (t == asTC_KEYWORD)
  336. {
  337. if (buffer[pos] == '{')
  338. ++level;
  339. else if(buffer[pos] == '}')
  340. --level;
  341. }
  342. pos += len;
  343. }
  344. }
  345. else
  346. ++pos;
  347. }
  348. }
  349. // Process includes first
  350. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  351. {
  352. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  353. if (file)
  354. {
  355. if (!AddScriptSection(engine, *file))
  356. return false;
  357. }
  358. else
  359. return false;
  360. }
  361. // Then add this section
  362. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  363. {
  364. LOGERROR("Failed to add script section " + source.GetName());
  365. return false;
  366. }
  367. SetMemoryUse(GetMemoryUse() + dataSize);
  368. return true;
  369. }
  370. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  371. {
  372. unsigned paramCount = function->GetParamCount();
  373. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  374. {
  375. int paramType = function->GetParamTypeId(i);
  376. switch (paramType)
  377. {
  378. case asTYPEID_BOOL:
  379. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  380. break;
  381. case asTYPEID_INT8:
  382. case asTYPEID_UINT8:
  383. context->SetArgByte(i, parameters[i].GetInt());
  384. break;
  385. case asTYPEID_INT16:
  386. case asTYPEID_UINT16:
  387. context->SetArgWord(i, parameters[i].GetInt());
  388. break;
  389. case asTYPEID_INT32:
  390. case asTYPEID_UINT32:
  391. context->SetArgDWord(i, parameters[i].GetInt());
  392. break;
  393. case asTYPEID_FLOAT:
  394. context->SetArgFloat(i, parameters[i].GetFloat());
  395. break;
  396. default:
  397. if (paramType & asTYPEID_APPOBJECT)
  398. {
  399. switch (parameters[i].GetType())
  400. {
  401. case VAR_VECTOR2:
  402. context->SetArgObject(i, (void *)&parameters[i].GetVector2());
  403. break;
  404. case VAR_VECTOR3:
  405. context->SetArgObject(i, (void *)&parameters[i].GetVector3());
  406. break;
  407. case VAR_VECTOR4:
  408. context->SetArgObject(i, (void *)&parameters[i].GetVector4());
  409. break;
  410. case VAR_QUATERNION:
  411. context->SetArgObject(i, (void *)&parameters[i].GetQuaternion());
  412. break;
  413. case VAR_STRING:
  414. context->SetArgObject(i, (void *)&parameters[i].GetString());
  415. break;
  416. case VAR_PTR:
  417. context->SetArgObject(i, (void *)parameters[i].GetPtr());
  418. break;
  419. default:
  420. break;
  421. }
  422. }
  423. break;
  424. }
  425. }
  426. }
  427. void ScriptFile::ReleaseModule()
  428. {
  429. if (scriptModule_)
  430. {
  431. script_->ClearObjectTypeCache();
  432. // Clear search caches and event handlers
  433. includeFiles_.Clear();
  434. validClasses_.Clear();
  435. functions_.Clear();
  436. methods_.Clear();
  437. UnsubscribeFromAllEventsWithUserData();
  438. // Remove the module
  439. scriptModule_->SetUserData(0);
  440. asIScriptEngine* engine = script_->GetScriptEngine();
  441. engine->DiscardModule(GetName().CString());
  442. scriptModule_ = 0;
  443. compiled_ = false;
  444. SetMemoryUse(0);
  445. }
  446. }
  447. void ScriptFile::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  448. {
  449. if (!compiled_)
  450. return;
  451. asIScriptFunction* function = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  452. VariantVector parameters;
  453. if (function->GetParamCount() > 0)
  454. {
  455. parameters.Push(Variant((void*)&eventType));
  456. parameters.Push(Variant((void*)&eventData));
  457. }
  458. Execute(function, parameters);
  459. }
  460. ScriptFile* GetScriptContextFile()
  461. {
  462. asIScriptContext* context = asGetActiveContext();
  463. asIScriptFunction* function = context ? context->GetFunction() : 0;
  464. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  465. if (module)
  466. return static_cast<ScriptFile*>(module->GetUserData());
  467. else
  468. return 0;
  469. }