ScriptFile.cpp 19 KB

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