ScriptFile.cpp 18 KB

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