ScriptFile.cpp 21 KB

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