Script.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  79. // Create the context for immediate execution
  80. immediateContext_ = scriptEngine_->CreateContext();
  81. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  82. // Register Script library object factories
  83. RegisterScriptLibrary(context_);
  84. // Register the Array, String & Dictionary API
  85. RegisterArray(scriptEngine_);
  86. RegisterString(scriptEngine_);
  87. RegisterDictionary(scriptEngine_);
  88. RegisterScriptInterfaceAPI(scriptEngine_);
  89. // Register the rest of the script API
  90. RegisterMathAPI(scriptEngine_);
  91. RegisterCoreAPI(scriptEngine_);
  92. RegisterIOAPI(scriptEngine_);
  93. RegisterResourceAPI(scriptEngine_);
  94. RegisterSceneAPI(scriptEngine_);
  95. RegisterGraphicsAPI(scriptEngine_);
  96. RegisterInputAPI(scriptEngine_);
  97. RegisterAudioAPI(scriptEngine_);
  98. RegisterUIAPI(scriptEngine_);
  99. #ifdef URHO3D_NETWORK
  100. RegisterNetworkAPI(scriptEngine_);
  101. #endif
  102. #ifdef URHO3D_DATABASE
  103. RegisterDatabaseAPI(scriptEngine_);
  104. #endif
  105. #ifdef URHO3D_PHYSICS
  106. RegisterPhysicsAPI(scriptEngine_);
  107. #endif
  108. #ifdef URHO3D_NAVIGATION
  109. RegisterNavigationAPI(scriptEngine_);
  110. #endif
  111. #ifdef URHO3D_URHO2D
  112. RegisterUrho2DAPI(scriptEngine_);
  113. #endif
  114. RegisterScriptAPI(scriptEngine_);
  115. RegisterEngineAPI(scriptEngine_);
  116. // Subscribe to console commands
  117. SetExecuteConsoleCommands(true);
  118. // Create and register resource router for checking for compiled AngelScript files
  119. ResourceCache* cache = GetSubsystem<ResourceCache>();
  120. if (cache)
  121. {
  122. router_ = new ScriptResourceRouter(context_);
  123. cache->AddResourceRouter(router_);
  124. }
  125. }
  126. Script::~Script()
  127. {
  128. if (immediateContext_)
  129. {
  130. immediateContext_->Release();
  131. immediateContext_ = 0;
  132. }
  133. for (unsigned i = 0; i < scriptFileContexts_.Size(); ++i)
  134. scriptFileContexts_[i]->Release();
  135. if (scriptEngine_)
  136. {
  137. scriptEngine_->Release();
  138. scriptEngine_ = 0;
  139. }
  140. ResourceCache* cache = GetSubsystem<ResourceCache>();
  141. if (cache)
  142. cache->RemoveResourceRouter(router_);
  143. }
  144. bool Script::Execute(const String& line)
  145. {
  146. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  147. URHO3D_PROFILE(ExecuteImmediate);
  148. ClearObjectTypeCache();
  149. String wrappedLine = "void f(){\n" + line + ";\n}";
  150. // If no immediate mode script file set, create a dummy module for compiling the line
  151. asIScriptModule* module = 0;
  152. if (defaultScriptFile_)
  153. module = defaultScriptFile_->GetScriptModule();
  154. if (!module)
  155. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  156. if (!module)
  157. return false;
  158. asIScriptFunction* function = 0;
  159. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  160. return false;
  161. if (immediateContext_->Prepare(function) < 0)
  162. {
  163. function->Release();
  164. return false;
  165. }
  166. bool success = immediateContext_->Execute() >= 0;
  167. immediateContext_->Unprepare();
  168. function->Release();
  169. return success;
  170. }
  171. void Script::SetDefaultScriptFile(ScriptFile* file)
  172. {
  173. defaultScriptFile_ = file;
  174. }
  175. void Script::SetDefaultScene(Scene* scene)
  176. {
  177. defaultScene_ = scene;
  178. }
  179. void Script::SetExecuteConsoleCommands(bool enable)
  180. {
  181. if (enable == executeConsoleCommands_)
  182. return;
  183. executeConsoleCommands_ = enable;
  184. if (enable)
  185. SubscribeToEvent(E_CONSOLECOMMAND, URHO3D_HANDLER(Script, HandleConsoleCommand));
  186. else
  187. UnsubscribeFromEvent(E_CONSOLECOMMAND);
  188. }
  189. void Script::MessageCallback(const asSMessageInfo* msg)
  190. {
  191. String message;
  192. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  193. switch (msg->type)
  194. {
  195. case asMSGTYPE_ERROR:
  196. URHO3D_LOGERROR(message);
  197. break;
  198. case asMSGTYPE_WARNING:
  199. URHO3D_LOGWARNING(message);
  200. break;
  201. default:
  202. URHO3D_LOGINFO(message);
  203. break;
  204. }
  205. }
  206. void Script::ExceptionCallback(asIScriptContext* context)
  207. {
  208. String message;
  209. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(),
  210. context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  211. asSMessageInfo msg;
  212. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  213. msg.type = asMSGTYPE_ERROR;
  214. msg.message = message.CString();
  215. MessageCallback(&msg);
  216. }
  217. String Script::GetCallStack(asIScriptContext* context)
  218. {
  219. String str("AngelScript callstack:\n");
  220. // Append the call stack
  221. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  222. {
  223. asIScriptFunction* func;
  224. const char* scriptSection;
  225. int line, column;
  226. func = context->GetFunction(i);
  227. line = context->GetLineNumber(i, &column, &scriptSection);
  228. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  229. }
  230. return str;
  231. }
  232. ScriptFile* Script::GetDefaultScriptFile() const
  233. {
  234. return defaultScriptFile_;
  235. }
  236. Scene* Script::GetDefaultScene() const
  237. {
  238. return defaultScene_;
  239. }
  240. void Script::ClearObjectTypeCache()
  241. {
  242. objectTypes_.Clear();
  243. }
  244. asIObjectType* Script::GetObjectType(const char* declaration)
  245. {
  246. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  247. if (i != objectTypes_.End())
  248. return i->second_;
  249. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  250. objectTypes_[declaration] = type;
  251. return type;
  252. }
  253. asIScriptContext* Script::GetScriptFileContext()
  254. {
  255. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  256. {
  257. asIScriptContext* newContext = scriptEngine_->CreateContext();
  258. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  259. scriptFileContexts_.Push(newContext);
  260. }
  261. return scriptFileContexts_[scriptNestingLevel_];
  262. }
  263. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  264. {
  265. using namespace ConsoleCommand;
  266. if (eventData[P_ID].GetString() == GetTypeName())
  267. Execute(eventData[P_COMMAND].GetString());
  268. }
  269. void RegisterScriptLibrary(Context* context)
  270. {
  271. ScriptFile::RegisterObject(context);
  272. ScriptInstance::RegisterObject(context);
  273. }
  274. }