ScriptFile.cpp 18 KB

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