ScriptFile.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876
  1. //
  2. // Copyright (c) 2008-2014 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 "Context.h"
  24. #include "CoreEvents.h"
  25. #include "FileSystem.h"
  26. #include "Log.h"
  27. #include "MemoryBuffer.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. namespace Urho3D
  37. {
  38. /// Helper class for saving AngelScript bytecode.
  39. class ByteCodeSerializer : public asIBinaryStream
  40. {
  41. public:
  42. /// Construct.
  43. ByteCodeSerializer(Serializer& dest) :
  44. dest_(dest)
  45. {
  46. }
  47. /// Read from stream (no-op).
  48. virtual void Read(void* ptr, asUINT size)
  49. {
  50. // No-op, can not read from a Serializer
  51. }
  52. /// Write to stream.
  53. virtual void Write(const void* ptr, asUINT size)
  54. {
  55. dest_.Write(ptr, size);
  56. }
  57. private:
  58. /// Destination stream.
  59. Serializer& dest_;
  60. };
  61. /// Helper class for loading AngelScript bytecode.
  62. class ByteCodeDeserializer : public asIBinaryStream
  63. {
  64. public:
  65. /// Construct.
  66. ByteCodeDeserializer(MemoryBuffer& source) :
  67. source_(source)
  68. {
  69. }
  70. /// Read from stream.
  71. virtual void Read(void* ptr, asUINT size)
  72. {
  73. source_.Read(ptr, size);
  74. }
  75. /// Write to stream (no-op).
  76. virtual void Write(const void* ptr, asUINT size)
  77. {
  78. }
  79. private:
  80. /// Source stream.
  81. MemoryBuffer& source_;
  82. };
  83. ScriptFile::ScriptFile(Context* context) :
  84. Resource(context),
  85. script_(GetSubsystem<Script>()),
  86. scriptModule_(0),
  87. compiled_(false),
  88. subscribed_(false)
  89. {
  90. }
  91. ScriptFile::~ScriptFile()
  92. {
  93. ReleaseModule();
  94. }
  95. void ScriptFile::RegisterObject(Context* context)
  96. {
  97. context->RegisterFactory<ScriptFile>();
  98. }
  99. bool ScriptFile::BeginLoad(Deserializer& source)
  100. {
  101. ReleaseModule();
  102. loadByteCode_.Reset();
  103. asIScriptEngine* engine = script_->GetScriptEngine();
  104. {
  105. MutexLock lock(script_->GetModuleMutex());
  106. // Create the module. Discard previous module if there was one
  107. scriptModule_ = engine->GetModule(GetName().CString(), asGM_ALWAYS_CREATE);
  108. if (!scriptModule_)
  109. {
  110. LOGERROR("Failed to create script module " + GetName());
  111. return false;
  112. }
  113. }
  114. // Check if this file is precompiled bytecode
  115. if (source.ReadFileID() == "ASBC")
  116. {
  117. // Perform actual parsing in EndLoad(); read data now
  118. loadByteCodeSize_ = source.GetSize() - source.GetPosition();
  119. loadByteCode_ = new unsigned char[loadByteCodeSize_];
  120. source.Read(loadByteCode_.Get(), loadByteCodeSize_);
  121. return true;
  122. }
  123. else
  124. source.Seek(0);
  125. // Not bytecode: add the initial section and check for includes.
  126. // Perform actual building during EndLoad(), as AngelScript can not multithread module compilation,
  127. // and static initializers may access arbitrary engine functionality which may not be thread-safe
  128. return AddScriptSection(engine, source);
  129. }
  130. bool ScriptFile::EndLoad()
  131. {
  132. bool success = false;
  133. // Load from bytecode if available, else compile
  134. if (loadByteCode_)
  135. {
  136. MemoryBuffer buffer(loadByteCode_.Get(), loadByteCodeSize_);
  137. ByteCodeDeserializer deserializer = ByteCodeDeserializer(buffer);
  138. if (scriptModule_->LoadByteCode(&deserializer) >= 0)
  139. {
  140. LOGINFO("Loaded script module " + GetName() + " from bytecode");
  141. success = true;
  142. }
  143. }
  144. else
  145. {
  146. int result = scriptModule_->Build();
  147. if (result >= 0)
  148. {
  149. LOGINFO("Compiled script module " + GetName());
  150. success = true;
  151. }
  152. else
  153. LOGERROR("Failed to compile script module " + GetName());
  154. }
  155. if (success)
  156. {
  157. compiled_ = true;
  158. // Map script module to script resource with userdata
  159. scriptModule_->SetUserData(this);
  160. }
  161. loadByteCode_.Reset();
  162. return success;
  163. }
  164. void ScriptFile::AddEventHandler(StringHash eventType, const String& handlerName)
  165. {
  166. if (!compiled_)
  167. return;
  168. AddEventHandlerInternal(0, eventType, handlerName);
  169. }
  170. void ScriptFile::AddEventHandler(Object* sender, StringHash eventType, const String& handlerName)
  171. {
  172. if (!compiled_)
  173. return;
  174. if (!sender)
  175. {
  176. LOGERROR("Null event sender for event " + String(eventType) + ", handler " + handlerName);
  177. return;
  178. }
  179. AddEventHandlerInternal(sender, eventType, handlerName);
  180. }
  181. void ScriptFile::RemoveEventHandler(StringHash eventType)
  182. {
  183. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  184. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  185. if (i != eventInvokers_.End())
  186. {
  187. i->second_->UnsubscribeFromEvent(eventType);
  188. // If no longer have any subscribed events, remove the event invoker object
  189. if (!i->second_->HasEventHandlers())
  190. eventInvokers_.Erase(i);
  191. }
  192. }
  193. void ScriptFile::RemoveEventHandler(Object* sender, StringHash eventType)
  194. {
  195. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  196. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  197. if (i != eventInvokers_.End())
  198. {
  199. i->second_->UnsubscribeFromEvent(sender, eventType);
  200. if (!i->second_->HasEventHandlers())
  201. eventInvokers_.Erase(i);
  202. }
  203. }
  204. void ScriptFile::RemoveEventHandlers(Object* sender)
  205. {
  206. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  207. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  208. if (i != eventInvokers_.End())
  209. {
  210. i->second_->UnsubscribeFromEvents(sender);
  211. if (!i->second_->HasEventHandlers())
  212. eventInvokers_.Erase(i);
  213. }
  214. }
  215. void ScriptFile::RemoveEventHandlers()
  216. {
  217. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  218. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  219. if (i != eventInvokers_.End())
  220. {
  221. i->second_->UnsubscribeFromAllEvents();
  222. if (!i->second_->HasEventHandlers())
  223. eventInvokers_.Erase(i);
  224. }
  225. }
  226. void ScriptFile::RemoveEventHandlersExcept(const PODVector<StringHash>& exceptions)
  227. {
  228. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  229. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  230. if (i != eventInvokers_.End())
  231. {
  232. i->second_->UnsubscribeFromAllEventsExcept(exceptions, true);
  233. if (!i->second_->HasEventHandlers())
  234. eventInvokers_.Erase(i);
  235. }
  236. }
  237. bool ScriptFile::Execute(const String& declaration, const VariantVector& parameters, bool unprepare)
  238. {
  239. asIScriptFunction* function = GetFunction(declaration);
  240. if (!function)
  241. {
  242. LOGERROR("Function " + declaration + " not found in " + GetName());
  243. return false;
  244. }
  245. return Execute(function, parameters, unprepare);
  246. }
  247. bool ScriptFile::Execute(asIScriptFunction* function, const VariantVector& parameters, bool unprepare)
  248. {
  249. PROFILE(ExecuteFunction);
  250. if (!compiled_ || !function)
  251. return false;
  252. // It is possible that executing the function causes us to unload. Therefore do not rely on member variables
  253. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  254. Script* scriptSystem = script_;
  255. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  256. if (context->Prepare(function) < 0)
  257. return false;
  258. SetParameters(context, function, parameters);
  259. scriptSystem->IncScriptNestingLevel();
  260. bool success = context->Execute() >= 0;
  261. if (unprepare)
  262. context->Unprepare();
  263. scriptSystem->DecScriptNestingLevel();
  264. return success;
  265. }
  266. bool ScriptFile::Execute(asIScriptObject* object, const String& declaration, const VariantVector& parameters, bool unprepare)
  267. {
  268. asIScriptFunction* method = GetMethod(object, declaration);
  269. if (!method)
  270. {
  271. LOGERROR("Method " + declaration + " not found in " + GetName());
  272. return false;
  273. }
  274. return Execute(object, method, parameters, unprepare);
  275. }
  276. bool ScriptFile::Execute(asIScriptObject* object, asIScriptFunction* method, const VariantVector& parameters, bool unprepare)
  277. {
  278. PROFILE(ExecuteMethod);
  279. if (!compiled_ || !object || !method)
  280. return false;
  281. // It is possible that executing the method causes us to unload. Therefore do not rely on member variables
  282. // However, we are not prepared for the whole script system getting destroyed during execution (should never happen)
  283. Script* scriptSystem = script_;
  284. asIScriptContext* context = scriptSystem->GetScriptFileContext();
  285. if (context->Prepare(method) < 0)
  286. return false;
  287. context->SetObject(object);
  288. SetParameters(context, method, parameters);
  289. scriptSystem->IncScriptNestingLevel();
  290. bool success = context->Execute() >= 0;
  291. if (unprepare)
  292. context->Unprepare();
  293. scriptSystem->DecScriptNestingLevel();
  294. return success;
  295. }
  296. void ScriptFile::DelayedExecute(float delay, bool repeat, const String& declaration, const VariantVector& parameters)
  297. {
  298. DelayedCall call;
  299. call.period_ = call.delay_ = Max(delay, 0.0f);
  300. call.repeat_ = repeat;
  301. call.declaration_ = declaration;
  302. call.parameters_ = parameters;
  303. delayedCalls_.Push(call);
  304. // Make sure we are registered to the application update event, because delayed calls are executed there
  305. if (!subscribed_)
  306. {
  307. SubscribeToEvent(E_UPDATE, HANDLER(ScriptFile, HandleUpdate));
  308. subscribed_ = true;
  309. }
  310. }
  311. void ScriptFile::ClearDelayedExecute(const String& declaration)
  312. {
  313. if (declaration.Empty())
  314. delayedCalls_.Clear();
  315. else
  316. {
  317. for (Vector<DelayedCall>::Iterator i = delayedCalls_.Begin(); i != delayedCalls_.End();)
  318. {
  319. if (declaration == i->declaration_)
  320. i = delayedCalls_.Erase(i);
  321. else
  322. ++i;
  323. }
  324. }
  325. }
  326. asIScriptObject* ScriptFile::CreateObject(const String& className)
  327. {
  328. PROFILE(CreateObject);
  329. if (!compiled_)
  330. return 0;
  331. asIScriptContext* context = script_->GetScriptFileContext();
  332. asIScriptEngine* engine = script_->GetScriptEngine();
  333. asIObjectType *type = engine->GetObjectTypeById(scriptModule_->GetTypeIdByDecl(className.CString()));
  334. if (!type)
  335. return 0;
  336. // Ensure that the type implements the "ScriptObject" interface, so it can be returned to script properly
  337. bool found = false;
  338. HashMap<asIObjectType*, bool>::ConstIterator i = validClasses_.Find(type);
  339. if (i != validClasses_.End())
  340. found = i->second_;
  341. else
  342. {
  343. unsigned numInterfaces = type->GetInterfaceCount();
  344. for (unsigned j = 0; j < numInterfaces; ++j)
  345. {
  346. asIObjectType* interfaceType = type->GetInterface(j);
  347. if (!strcmp(interfaceType->GetName(), "ScriptObject"))
  348. {
  349. found = true;
  350. break;
  351. }
  352. }
  353. validClasses_[type] = found;
  354. }
  355. if (!found)
  356. {
  357. LOGERROR("Script class " + className + " does not implement the ScriptObject interface");
  358. return 0;
  359. }
  360. // Get the factory function id from the object type
  361. String factoryName = className + "@ " + className + "()";
  362. asIScriptFunction* factory = type->GetFactoryByDecl(factoryName.CString());
  363. if (!factory || context->Prepare(factory) < 0 || context->Execute() < 0)
  364. return 0;
  365. asIScriptObject* obj = *(static_cast<asIScriptObject**>(context->GetAddressOfReturnValue()));
  366. if (obj)
  367. obj->AddRef();
  368. return obj;
  369. }
  370. bool ScriptFile::SaveByteCode(Serializer& dest)
  371. {
  372. if (compiled_)
  373. {
  374. dest.WriteFileID("ASBC");
  375. ByteCodeSerializer serializer = ByteCodeSerializer(dest);
  376. return scriptModule_->SaveByteCode(&serializer, true) >= 0;
  377. }
  378. else
  379. return false;
  380. }
  381. asIScriptFunction* ScriptFile::GetFunction(const String& declaration)
  382. {
  383. if (!compiled_)
  384. return 0;
  385. HashMap<String, asIScriptFunction*>::ConstIterator i = functions_.Find(declaration);
  386. if (i != functions_.End())
  387. return i->second_;
  388. asIScriptFunction* function = scriptModule_->GetFunctionByDecl(declaration.CString());
  389. functions_[declaration] = function;
  390. return function;
  391. }
  392. asIScriptFunction* ScriptFile::GetMethod(asIScriptObject* object, const String& declaration)
  393. {
  394. if (!compiled_ || !object)
  395. return 0;
  396. asIObjectType* type = object->GetObjectType();
  397. if (!type)
  398. return 0;
  399. HashMap<asIObjectType*, HashMap<String, asIScriptFunction*> >::ConstIterator i = methods_.Find(type);
  400. if (i != methods_.End())
  401. {
  402. HashMap<String, asIScriptFunction*>::ConstIterator j = i->second_.Find(declaration);
  403. if (j != i->second_.End())
  404. return j->second_;
  405. }
  406. asIScriptFunction* function = type->GetMethodByDecl(declaration.CString());
  407. methods_[type][declaration] = function;
  408. return function;
  409. }
  410. void ScriptFile::CleanupEventInvoker(asIScriptObject* object)
  411. {
  412. eventInvokers_.Erase(object);
  413. }
  414. void ScriptFile::AddEventHandlerInternal(Object* sender, StringHash eventType, const String& handlerName)
  415. {
  416. String declaration = "void " + handlerName + "(StringHash, VariantMap&)";
  417. asIScriptFunction* function = 0;
  418. asIScriptObject* receiver = static_cast<asIScriptObject*>(asGetActiveContext()->GetThisPointer());
  419. if (receiver)
  420. function = GetMethod(receiver, declaration);
  421. else
  422. function = GetFunction(declaration);
  423. if (!function)
  424. {
  425. declaration = "void " + handlerName + "()";
  426. if (receiver)
  427. function = GetMethod(receiver, declaration);
  428. else
  429. function = GetFunction(declaration);
  430. if (!function)
  431. {
  432. LOGERROR("Event handler function " + handlerName + " not found in " + GetName());
  433. return;
  434. }
  435. }
  436. HashMap<asIScriptObject*, SharedPtr<ScriptEventInvoker> >::Iterator i = eventInvokers_.Find(receiver);
  437. // Remove previous handler in case an object pointer gets reused
  438. if (i != eventInvokers_.End() && !i->second_->IsObjectAlive())
  439. {
  440. eventInvokers_.Erase(i);
  441. i = eventInvokers_.End();
  442. }
  443. if (i == eventInvokers_.End())
  444. i = eventInvokers_.Insert(MakePair(receiver, SharedPtr<ScriptEventInvoker>(new ScriptEventInvoker(this, receiver))));
  445. if (!sender)
  446. {
  447. i->second_->SubscribeToEvent(eventType, new EventHandlerImpl<ScriptEventInvoker>
  448. (i->second_, &ScriptEventInvoker::HandleScriptEvent, (void*)function));
  449. }
  450. else
  451. {
  452. i->second_->SubscribeToEvent(sender, eventType, new EventHandlerImpl<ScriptEventInvoker>
  453. (i->second_, &ScriptEventInvoker::HandleScriptEvent, (void*)function));
  454. }
  455. }
  456. bool ScriptFile::AddScriptSection(asIScriptEngine* engine, Deserializer& source)
  457. {
  458. ResourceCache* cache = GetSubsystem<ResourceCache>();
  459. unsigned dataSize = source.GetSize();
  460. SharedArrayPtr<char> buffer(new char[dataSize]);
  461. source.Read((void*)buffer.Get(), dataSize);
  462. // Pre-parse for includes
  463. // Adapted from Angelscript's scriptbuilder add-on
  464. Vector<String> includeFiles;
  465. unsigned pos = 0;
  466. while(pos < dataSize)
  467. {
  468. int len;
  469. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  470. if (t == asTC_COMMENT || t == asTC_WHITESPACE)
  471. {
  472. pos += len;
  473. continue;
  474. }
  475. // Is this a preprocessor directive?
  476. if (buffer[pos] == '#')
  477. {
  478. int start = pos++;
  479. asETokenClass t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  480. if (t == asTC_IDENTIFIER)
  481. {
  482. String token(&buffer[pos], len);
  483. if (token == "include")
  484. {
  485. pos += len;
  486. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  487. if (t == asTC_WHITESPACE)
  488. {
  489. pos += len;
  490. t = engine->ParseToken(&buffer[pos], dataSize - pos, &len);
  491. }
  492. if (t == asTC_VALUE && len > 2 && buffer[pos] == '"')
  493. {
  494. // Get the include file
  495. String includeFile(&buffer[pos+1], len - 2);
  496. pos += len;
  497. // If the file is not found as it is, add the path of current file but only if it is found there
  498. if (!cache->Exists(includeFile))
  499. {
  500. String prefixedIncludeFile = GetPath(GetName()) + includeFile;
  501. if (cache->Exists(prefixedIncludeFile))
  502. includeFile = prefixedIncludeFile;
  503. }
  504. String includeFileLower = includeFile.ToLower();
  505. // If not included yet, store it for later processing
  506. if (!includeFiles_.Contains(includeFileLower))
  507. {
  508. includeFiles_.Insert(includeFileLower);
  509. includeFiles.Push(includeFile);
  510. }
  511. // Overwrite the include directive with space characters to avoid compiler error
  512. memset(&buffer[start], ' ', pos - start);
  513. }
  514. }
  515. }
  516. }
  517. // Don't search includes within statement blocks or between tokens in statements
  518. else
  519. {
  520. int len;
  521. // Skip until ; or { whichever comes first
  522. while (pos < dataSize && buffer[pos] != ';' && buffer[pos] != '{')
  523. {
  524. engine->ParseToken(&buffer[pos], 0, &len);
  525. pos += len;
  526. }
  527. // Skip entire statement block
  528. if (pos < dataSize && buffer[pos] == '{')
  529. {
  530. ++pos;
  531. // Find the end of the statement block
  532. int level = 1;
  533. while (level > 0 && pos < dataSize)
  534. {
  535. asETokenClass t = engine->ParseToken(&buffer[pos], 0, &len);
  536. if (t == asTC_KEYWORD)
  537. {
  538. if (buffer[pos] == '{')
  539. ++level;
  540. else if(buffer[pos] == '}')
  541. --level;
  542. }
  543. pos += len;
  544. }
  545. }
  546. else
  547. ++pos;
  548. }
  549. }
  550. // Process includes first
  551. for (unsigned i = 0; i < includeFiles.Size(); ++i)
  552. {
  553. cache->StoreResourceDependency(this, includeFiles[i]);
  554. SharedPtr<File> file = cache->GetFile(includeFiles[i]);
  555. if (file)
  556. {
  557. if (!AddScriptSection(engine, *file))
  558. return false;
  559. }
  560. else
  561. {
  562. LOGERROR("Could not process all the include directives in " + GetName() + ": missing " + includeFiles[i]);
  563. return false;
  564. }
  565. }
  566. // Then add this section
  567. if (scriptModule_->AddScriptSection(source.GetName().CString(), (const char*)buffer.Get(), dataSize) < 0)
  568. {
  569. LOGERROR("Failed to add script section " + source.GetName());
  570. return false;
  571. }
  572. SetMemoryUse(GetMemoryUse() + dataSize);
  573. return true;
  574. }
  575. void ScriptFile::SetParameters(asIScriptContext* context, asIScriptFunction* function, const VariantVector& parameters)
  576. {
  577. unsigned paramCount = function->GetParamCount();
  578. for (unsigned i = 0; i < parameters.Size() && i < paramCount; ++i)
  579. {
  580. int paramTypeId;
  581. function->GetParam(i, &paramTypeId);
  582. switch (paramTypeId)
  583. {
  584. case asTYPEID_BOOL:
  585. context->SetArgByte(i, (unsigned char)parameters[i].GetBool());
  586. break;
  587. case asTYPEID_INT8:
  588. case asTYPEID_UINT8:
  589. context->SetArgByte(i, parameters[i].GetInt());
  590. break;
  591. case asTYPEID_INT16:
  592. case asTYPEID_UINT16:
  593. context->SetArgWord(i, parameters[i].GetInt());
  594. break;
  595. case asTYPEID_INT32:
  596. case asTYPEID_UINT32:
  597. context->SetArgDWord(i, parameters[i].GetInt());
  598. break;
  599. case asTYPEID_FLOAT:
  600. context->SetArgFloat(i, parameters[i].GetFloat());
  601. break;
  602. default:
  603. if (paramTypeId & asTYPEID_APPOBJECT)
  604. {
  605. switch (parameters[i].GetType())
  606. {
  607. case VAR_VECTOR2:
  608. context->SetArgObject(i, (void*)&parameters[i].GetVector2());
  609. break;
  610. case VAR_VECTOR3:
  611. context->SetArgObject(i, (void*)&parameters[i].GetVector3());
  612. break;
  613. case VAR_VECTOR4:
  614. context->SetArgObject(i, (void*)&parameters[i].GetVector4());
  615. break;
  616. case VAR_QUATERNION:
  617. context->SetArgObject(i, (void*)&parameters[i].GetQuaternion());
  618. break;
  619. case VAR_STRING:
  620. context->SetArgObject(i, (void*)&parameters[i].GetString());
  621. break;
  622. case VAR_VOIDPTR:
  623. context->SetArgObject(i, parameters[i].GetVoidPtr());
  624. break;
  625. case VAR_PTR:
  626. context->SetArgObject(i, (void*)parameters[i].GetPtr());
  627. break;
  628. default:
  629. break;
  630. }
  631. }
  632. break;
  633. }
  634. }
  635. }
  636. void ScriptFile::ReleaseModule()
  637. {
  638. if (scriptModule_)
  639. {
  640. // Clear search caches and event handlers
  641. includeFiles_.Clear();
  642. validClasses_.Clear();
  643. functions_.Clear();
  644. methods_.Clear();
  645. delayedCalls_.Clear();
  646. eventInvokers_.Clear();
  647. asIScriptEngine* engine = script_->GetScriptEngine();
  648. scriptModule_->SetUserData(0);
  649. // Remove the module
  650. {
  651. MutexLock lock(script_->GetModuleMutex());
  652. script_->ClearObjectTypeCache();
  653. engine->DiscardModule(GetName().CString());
  654. }
  655. scriptModule_ = 0;
  656. compiled_ = false;
  657. SetMemoryUse(0);
  658. ResourceCache* cache = GetSubsystem<ResourceCache>();
  659. cache->ResetDependencies(this);
  660. }
  661. }
  662. void ScriptFile::HandleUpdate(StringHash eventType, VariantMap& eventData)
  663. {
  664. if (!compiled_)
  665. return;
  666. using namespace Update;
  667. float timeStep = eventData[P_TIMESTEP].GetFloat();
  668. // Execute delayed calls
  669. for (unsigned i = 0; i < delayedCalls_.Size();)
  670. {
  671. DelayedCall& call = delayedCalls_[i];
  672. bool remove = false;
  673. call.delay_ -= timeStep;
  674. if (call.delay_ <= 0.0f)
  675. {
  676. if (!call.repeat_)
  677. remove = true;
  678. else
  679. call.delay_ += call.period_;
  680. Execute(call.declaration_, call.parameters_);
  681. }
  682. if (remove)
  683. delayedCalls_.Erase(i);
  684. else
  685. ++i;
  686. }
  687. }
  688. ScriptEventInvoker::ScriptEventInvoker(ScriptFile* file, asIScriptObject* object) :
  689. Object(file->GetContext()),
  690. file_(file),
  691. sharedBool_(0),
  692. object_(object)
  693. {
  694. if (object_)
  695. {
  696. sharedBool_ = object_->GetEngine()->GetWeakRefFlagOfScriptObject(object_, object_->GetObjectType());
  697. if (sharedBool_)
  698. sharedBool_->AddRef();
  699. }
  700. }
  701. ScriptEventInvoker::~ScriptEventInvoker()
  702. {
  703. if (sharedBool_)
  704. sharedBool_->Release();
  705. sharedBool_ = 0;
  706. object_ = 0;
  707. }
  708. bool ScriptEventInvoker::IsObjectAlive() const
  709. {
  710. if (sharedBool_)
  711. {
  712. // Return inverse as Get returns true when an asIScriptObject is dead.
  713. return !sharedBool_->Get();
  714. }
  715. return true;
  716. }
  717. void ScriptEventInvoker::HandleScriptEvent(StringHash eventType, VariantMap& eventData)
  718. {
  719. if (!file_->IsCompiled())
  720. return;
  721. asIScriptFunction* method = static_cast<asIScriptFunction*>(GetEventHandler()->GetUserData());
  722. if (object_ && !IsObjectAlive())
  723. {
  724. file_->CleanupEventInvoker(object_);
  725. return;
  726. }
  727. VariantVector parameters;
  728. if (method->GetParamCount() > 0)
  729. {
  730. parameters.Push(Variant((void*)&eventType));
  731. parameters.Push(Variant((void*)&eventData));
  732. }
  733. if (object_)
  734. file_->Execute(object_, method, parameters);
  735. else
  736. file_->Execute(method, parameters);
  737. }
  738. ScriptFile* GetScriptContextFile()
  739. {
  740. asIScriptContext* context = asGetActiveContext();
  741. asIScriptFunction* function = context ? context->GetFunction() : 0;
  742. asIScriptModule* module = function ? function->GetEngine()->GetModule(function->GetModuleName()) : 0;
  743. if (module)
  744. return static_cast<ScriptFile*>(module->GetUserData());
  745. else
  746. return 0;
  747. }
  748. }