Script.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. //
  2. // Copyright (c) 2008-2016 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 "../AngelScript/Addons.h"
  24. #include "../AngelScript/Script.h"
  25. #include "../AngelScript/ScriptAPI.h"
  26. #include "../AngelScript/ScriptFile.h"
  27. #include "../AngelScript/ScriptInstance.h"
  28. #include "../Core/Profiler.h"
  29. #include "../Engine/EngineEvents.h"
  30. #include "../IO/FileSystem.h"
  31. #include "../IO/Log.h"
  32. #include "../Resource/ResourceCache.h"
  33. #include "../Scene/Scene.h"
  34. #include "../DebugNew.h"
  35. namespace Urho3D
  36. {
  37. class ScriptResourceRouter : public ResourceRouter
  38. {
  39. URHO3D_OBJECT(ScriptResourceRouter, ResourceRouter);
  40. /// Construct.
  41. ScriptResourceRouter(Context* context) :
  42. ResourceRouter(context)
  43. {
  44. }
  45. /// Check if request is for an AngelScript file and reroute to compiled version if necessary (.as file not available)
  46. virtual void Route(String& name, ResourceRequest requestType)
  47. {
  48. String extension = GetExtension(name);
  49. if (extension == ".as")
  50. {
  51. String replaced = ReplaceExtension(name, ".asc");
  52. // Note: ResourceCache prevents recursive calls to the resource routers so this is OK, the nested Exists()
  53. // check does not go through the router again
  54. ResourceCache* cache = GetSubsystem<ResourceCache>();
  55. if (!cache->Exists(name) && cache->Exists(replaced))
  56. name = replaced;
  57. }
  58. }
  59. };
  60. Script::Script(Context* context) :
  61. Object(context),
  62. scriptEngine_(0),
  63. immediateContext_(0),
  64. scriptNestingLevel_(0),
  65. executeConsoleCommands_(false)
  66. {
  67. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  68. if (!scriptEngine_)
  69. {
  70. URHO3D_LOGERROR("Could not create AngelScript engine");
  71. return;
  72. }
  73. scriptEngine_->SetUserData(this);
  74. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, (asPWORD)true);
  75. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, (asPWORD)true);
  76. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, (asPWORD)true);
  77. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, (asPWORD)true);
  78. // Use the copy of the original asMETHOD macro in a web build (for some reason it still works, presumably because the signature of the function is known)
  79. #ifdef AS_MAX_PORTABILITY
  80. scriptEngine_->SetMessageCallback(_asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  81. #else
  82. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  83. #endif
  84. // Create the context for immediate execution
  85. immediateContext_ = scriptEngine_->CreateContext();
  86. // Use the copy of the original asMETHOD macro in a web build (for some reason it still works, presumably because the signature of the function is known)
  87. #ifdef AS_MAX_PORTABILITY
  88. immediateContext_->SetExceptionCallback(_asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  89. #else
  90. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  91. #endif
  92. // Register Script library object factories
  93. RegisterScriptLibrary(context_);
  94. // Register the Array, String & Dictionary API
  95. RegisterArray(scriptEngine_);
  96. RegisterString(scriptEngine_);
  97. RegisterDictionary(scriptEngine_);
  98. RegisterScriptInterfaceAPI(scriptEngine_);
  99. // Register the rest of the script API
  100. RegisterMathAPI(scriptEngine_);
  101. RegisterCoreAPI(scriptEngine_);
  102. RegisterIOAPI(scriptEngine_);
  103. RegisterResourceAPI(scriptEngine_);
  104. RegisterSceneAPI(scriptEngine_);
  105. RegisterGraphicsAPI(scriptEngine_);
  106. RegisterInputAPI(scriptEngine_);
  107. RegisterAudioAPI(scriptEngine_);
  108. RegisterUIAPI(scriptEngine_);
  109. #ifdef URHO3D_NETWORK
  110. RegisterNetworkAPI(scriptEngine_);
  111. #endif
  112. #ifdef URHO3D_DATABASE
  113. RegisterDatabaseAPI(scriptEngine_);
  114. #endif
  115. #ifdef URHO3D_PHYSICS
  116. RegisterPhysicsAPI(scriptEngine_);
  117. #endif
  118. #ifdef URHO3D_NAVIGATION
  119. RegisterNavigationAPI(scriptEngine_);
  120. #endif
  121. #ifdef URHO3D_URHO2D
  122. RegisterUrho2DAPI(scriptEngine_);
  123. #endif
  124. RegisterScriptAPI(scriptEngine_);
  125. RegisterEngineAPI(scriptEngine_);
  126. // Subscribe to console commands
  127. SetExecuteConsoleCommands(true);
  128. // Create and register resource router for checking for compiled AngelScript files
  129. ResourceCache* cache = GetSubsystem<ResourceCache>();
  130. if (cache)
  131. {
  132. router_ = new ScriptResourceRouter(context_);
  133. cache->AddResourceRouter(router_);
  134. }
  135. }
  136. Script::~Script()
  137. {
  138. if (immediateContext_)
  139. {
  140. immediateContext_->Release();
  141. immediateContext_ = 0;
  142. }
  143. for (unsigned i = 0; i < scriptFileContexts_.Size(); ++i)
  144. scriptFileContexts_[i]->Release();
  145. if (scriptEngine_)
  146. {
  147. scriptEngine_->Release();
  148. scriptEngine_ = 0;
  149. }
  150. ResourceCache* cache = GetSubsystem<ResourceCache>();
  151. if (cache)
  152. cache->RemoveResourceRouter(router_);
  153. }
  154. bool Script::Execute(const String& line)
  155. {
  156. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  157. URHO3D_PROFILE(ExecuteImmediate);
  158. ClearObjectTypeCache();
  159. String wrappedLine = "void f(){\n" + line + ";\n}";
  160. // If no immediate mode script file set, create a dummy module for compiling the line
  161. asIScriptModule* module = 0;
  162. if (defaultScriptFile_)
  163. module = defaultScriptFile_->GetScriptModule();
  164. if (!module)
  165. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  166. if (!module)
  167. return false;
  168. asIScriptFunction* function = 0;
  169. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  170. return false;
  171. if (immediateContext_->Prepare(function) < 0)
  172. {
  173. function->Release();
  174. return false;
  175. }
  176. bool success = immediateContext_->Execute() >= 0;
  177. immediateContext_->Unprepare();
  178. function->Release();
  179. return success;
  180. }
  181. void Script::SetDefaultScriptFile(ScriptFile* file)
  182. {
  183. defaultScriptFile_ = file;
  184. }
  185. void Script::SetDefaultScene(Scene* scene)
  186. {
  187. defaultScene_ = scene;
  188. }
  189. void Script::SetExecuteConsoleCommands(bool enable)
  190. {
  191. if (enable == executeConsoleCommands_)
  192. return;
  193. executeConsoleCommands_ = enable;
  194. if (enable)
  195. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(Script, HandleConsoleCommand));
  196. else
  197. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  198. }
  199. void Script::MessageCallback(const asSMessageInfo* msg)
  200. {
  201. String message;
  202. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  203. switch (msg->type)
  204. {
  205. case asMSGTYPE_ERROR:
  206. URHO3D_LOGERROR(message);
  207. break;
  208. case asMSGTYPE_WARNING:
  209. URHO3D_LOGWARNING(message);
  210. break;
  211. default:
  212. URHO3D_LOGINFO(message);
  213. break;
  214. }
  215. }
  216. void Script::ExceptionCallback(asIScriptContext* context)
  217. {
  218. String message;
  219. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(),
  220. context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  221. asSMessageInfo msg;
  222. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  223. msg.type = asMSGTYPE_ERROR;
  224. msg.message = message.CString();
  225. MessageCallback(&msg);
  226. }
  227. String Script::GetCallStack(asIScriptContext* context)
  228. {
  229. String str("AngelScript callstack:\n");
  230. // Append the call stack
  231. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  232. {
  233. asIScriptFunction* func;
  234. const char* scriptSection;
  235. int line, column;
  236. func = context->GetFunction(i);
  237. line = context->GetLineNumber(i, &column, &scriptSection);
  238. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  239. }
  240. return str;
  241. }
  242. ScriptFile* Script::GetDefaultScriptFile() const
  243. {
  244. return defaultScriptFile_;
  245. }
  246. Scene* Script::GetDefaultScene() const
  247. {
  248. return defaultScene_;
  249. }
  250. void Script::ClearObjectTypeCache()
  251. {
  252. objectTypes_.Clear();
  253. }
  254. asIObjectType* Script::GetObjectType(const char* declaration)
  255. {
  256. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  257. if (i != objectTypes_.End())
  258. return i->second_;
  259. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  260. objectTypes_[declaration] = type;
  261. return type;
  262. }
  263. asIScriptContext* Script::GetScriptFileContext()
  264. {
  265. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  266. {
  267. asIScriptContext* newContext = scriptEngine_->CreateContext();
  268. // Use the copy of the original asMETHOD macro in a web build (for some reason it still works, presumably because the signature of the function is known)
  269. #ifdef AS_MAX_PORTABILITY
  270. newContext->SetExceptionCallback(_asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  271. #else
  272. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  273. #endif
  274. scriptFileContexts_.Push(newContext);
  275. }
  276. return scriptFileContexts_[scriptNestingLevel_];
  277. }
  278. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  279. {
  280. using namespace ConsoleCommand;
  281. if (eventData[P_ID].GetString() == GetTypeName())
  282. Execute(eventData[P_COMMAND].GetString());
  283. }
  284. void RegisterScriptLibrary(Context* context)
  285. {
  286. ScriptFile::RegisterObject(context);
  287. ScriptInstance::RegisterObject(context);
  288. }
  289. }