Script.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. //
  2. // Copyright (c) 2008-2013 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 "Addons.h"
  24. #include "Context.h"
  25. #include "EngineEvents.h"
  26. #include "Log.h"
  27. #include "Profiler.h"
  28. #include "Scene.h"
  29. #include "Script.h"
  30. #include "ScriptAPI.h"
  31. #include "ScriptFile.h"
  32. #include "ScriptInstance.h"
  33. #include <angelscript.h>
  34. #include "DebugNew.h"
  35. namespace Urho3D
  36. {
  37. /// %Object property info for scripting API dump.
  38. struct PropertyInfo
  39. {
  40. /// Construct.
  41. PropertyInfo() :
  42. read_(false),
  43. write_(false),
  44. indexed_(false)
  45. {
  46. }
  47. /// Property name.
  48. String name_;
  49. /// Property data type.
  50. String type_;
  51. /// Reading supported flag.
  52. bool read_;
  53. /// Writing supported flag.
  54. bool write_;
  55. /// Indexed flag.
  56. bool indexed_;
  57. };
  58. void ExtractPropertyInfo(const String& functionName, const String& declaration, Vector<PropertyInfo>& propertyInfos)
  59. {
  60. String propertyName = functionName.Substring(4);
  61. PropertyInfo* info = 0;
  62. for (unsigned k = 0; k < propertyInfos.Size(); ++k)
  63. {
  64. if (propertyInfos[k].name_ == propertyName)
  65. {
  66. info = &propertyInfos[k];
  67. break;
  68. }
  69. }
  70. if (!info)
  71. {
  72. propertyInfos.Resize(propertyInfos.Size() + 1);
  73. info = &propertyInfos.Back();
  74. info->name_ = propertyName;
  75. }
  76. if (functionName.Contains("get_"))
  77. {
  78. info->read_ = true;
  79. // Extract type from the return value
  80. Vector<String> parts = declaration.Split(' ');
  81. if (parts.Size())
  82. {
  83. if (parts[0] != "const")
  84. info->type_ = parts[0];
  85. else if (parts.Size() > 1)
  86. info->type_ = parts[1];
  87. }
  88. // If get method has parameters, it is indexed
  89. if (!declaration.Contains("()"))
  90. {
  91. info->indexed_ = true;
  92. info->type_ += "[]";
  93. }
  94. // Sanitate the reference operator away
  95. info->type_.Replace("&", "");
  96. }
  97. if (functionName.Contains("set_"))
  98. {
  99. info->write_ = true;
  100. if (info->type_.Empty())
  101. {
  102. // Extract type from parameters
  103. unsigned begin = declaration.Find(',');
  104. if (begin == String::NPOS)
  105. begin = declaration.Find('(');
  106. else
  107. info->indexed_ = true;
  108. if (begin != String::NPOS)
  109. {
  110. ++begin;
  111. unsigned end = declaration.Find(')');
  112. if (end != String::NPOS)
  113. {
  114. info->type_ = declaration.Substring(begin, end - begin);
  115. // Sanitate const & reference operator away
  116. info->type_.Replace("const ", "");
  117. info->type_.Replace("&in", "");
  118. info->type_.Replace("&", "");
  119. }
  120. }
  121. }
  122. }
  123. }
  124. Script::Script(Context* context) :
  125. Object(context),
  126. scriptEngine_(0),
  127. immediateContext_(0),
  128. scriptNestingLevel_(0)
  129. {
  130. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  131. if (!scriptEngine_)
  132. {
  133. LOGERROR("Could not create AngelScript engine");
  134. return;
  135. }
  136. scriptEngine_->SetUserData(this);
  137. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  138. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  139. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  140. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  141. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  142. // Create the context for immediate execution
  143. immediateContext_ = scriptEngine_->CreateContext();
  144. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  145. // Register Script library object factories
  146. RegisterScriptLibrary(context_);
  147. // Register the Array & String API
  148. RegisterArray(scriptEngine_);
  149. RegisterString(scriptEngine_);
  150. // Register the rest of the script API
  151. RegisterMathAPI(scriptEngine_);
  152. RegisterCoreAPI(scriptEngine_);
  153. RegisterIOAPI(scriptEngine_);
  154. RegisterResourceAPI(scriptEngine_);
  155. RegisterSceneAPI(scriptEngine_);
  156. RegisterGraphicsAPI(scriptEngine_);
  157. RegisterInputAPI(scriptEngine_);
  158. RegisterAudioAPI(scriptEngine_);
  159. RegisterUIAPI(scriptEngine_);
  160. RegisterNetworkAPI(scriptEngine_);
  161. RegisterPhysicsAPI(scriptEngine_);
  162. RegisterNavigationAPI(scriptEngine_);
  163. RegisterScriptAPI(scriptEngine_);
  164. RegisterEngineAPI(scriptEngine_);
  165. // Subscribe to console commands
  166. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(Script, HandleConsoleCommand));
  167. }
  168. Script::~Script()
  169. {
  170. if (immediateContext_)
  171. {
  172. immediateContext_->Release();
  173. immediateContext_ = 0;
  174. }
  175. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  176. scriptFileContexts_[i]->Release();
  177. if (scriptEngine_)
  178. {
  179. scriptEngine_->Release();
  180. scriptEngine_ = 0;
  181. }
  182. }
  183. bool Script::Execute(const String& line)
  184. {
  185. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  186. PROFILE(ExecuteImmediate);
  187. ClearObjectTypeCache();
  188. String wrappedLine = "void f(){\n" + line + ";\n}";
  189. // If no immediate mode script file set, create a dummy module for compiling the line
  190. asIScriptModule* module = 0;
  191. if (defaultScriptFile_)
  192. module = defaultScriptFile_->GetScriptModule();
  193. if (!module)
  194. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  195. if (!module)
  196. return false;
  197. asIScriptFunction *function = 0;
  198. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  199. return false;
  200. if (immediateContext_->Prepare(function) < 0)
  201. {
  202. function->Release();
  203. return false;
  204. }
  205. bool success = immediateContext_->Execute() >= 0;
  206. immediateContext_->Unprepare();
  207. function->Release();
  208. return success;
  209. }
  210. void Script::SetDefaultScriptFile(ScriptFile* file)
  211. {
  212. defaultScriptFile_ = file;
  213. }
  214. void Script::SetDefaultScene(Scene* scene)
  215. {
  216. defaultScene_ = scene;
  217. }
  218. void Script::DumpAPI()
  219. {
  220. // Does not use LOGRAW macro here to ensure the messages are always dumped regardless of ENABLE_LOGGING compiler directive and of Log subsystem availability
  221. Log::WriteRaw("namespace Urho3D\n{\n\n/**\n\\page ScriptAPI Scripting API\n\n");
  222. Vector<PropertyInfo> globalPropertyInfos;
  223. Vector<String> globalFunctions;
  224. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  225. for (unsigned i = 0; i < functions; ++i)
  226. {
  227. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  228. String functionName(function->GetName());
  229. String declaration(function->GetDeclaration());
  230. if (functionName.Contains("set_") || functionName.Contains("get_"))
  231. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  232. else
  233. globalFunctions.Push(declaration);
  234. }
  235. Log::WriteRaw("\\section ScriptAPI_GlobalFunctions Global functions\n");
  236. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  237. OutputAPIRow(globalFunctions[i]);
  238. Log::WriteRaw("\\section ScriptAPI_GlobalProperties Global properties\n");
  239. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  240. OutputAPIRow(globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  241. Log::WriteRaw("\\section ScriptAPI_GlobalConstants Global constants\n");
  242. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  243. for (unsigned i = 0; i < properties; ++i)
  244. {
  245. const char* propertyName;
  246. const char* propertyDeclaration;
  247. int typeId;
  248. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  249. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  250. String type(propertyDeclaration);
  251. OutputAPIRow(type + " " + String(propertyName), true);
  252. }
  253. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  254. unsigned types = scriptEngine_->GetObjectTypeCount();
  255. for (unsigned i = 0; i < types; ++i)
  256. {
  257. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  258. if (type)
  259. {
  260. String typeName(type->GetName());
  261. Vector<String> methodDeclarations;
  262. Vector<PropertyInfo> propertyInfos;
  263. Log::WriteRaw("\n" + typeName + "\n");
  264. unsigned methods = type->GetMethodCount();
  265. for (unsigned j = 0; j < methods; ++j)
  266. {
  267. asIScriptFunction* method = type->GetMethodByIndex(j);
  268. String methodName(method->GetName());
  269. String declaration(method->GetDeclaration());
  270. if (methodName.Contains("get_") || methodName.Contains("set_"))
  271. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  272. else
  273. {
  274. // Sanitate the method name. \todo For now, skip the operators
  275. if (!declaration.Contains("::op"))
  276. {
  277. String prefix(typeName + "::");
  278. declaration.Replace(prefix, "");
  279. methodDeclarations.Push(declaration);
  280. }
  281. }
  282. }
  283. // Assume that the same property is never both an accessor property, and a direct one
  284. unsigned properties = type->GetPropertyCount();
  285. for (unsigned j = 0; j < properties; ++j)
  286. {
  287. const char* propertyName;
  288. const char* propertyDeclaration;
  289. int typeId;
  290. type->GetProperty(j, &propertyName, &typeId);
  291. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  292. PropertyInfo newInfo;
  293. newInfo.name_ = String(propertyName);
  294. newInfo.type_ = String(propertyDeclaration);
  295. newInfo.read_ = newInfo.write_ = true;
  296. propertyInfos.Push(newInfo);
  297. }
  298. if (!methodDeclarations.Empty())
  299. {
  300. Log::WriteRaw("\nMethods:<br>\n");
  301. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  302. OutputAPIRow(methodDeclarations[j]);
  303. }
  304. if (!propertyInfos.Empty())
  305. {
  306. Log::WriteRaw("\nProperties:<br>\n");
  307. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  308. {
  309. String remark;
  310. if (!propertyInfos[j].write_)
  311. remark = " (readonly)";
  312. else if (!propertyInfos[j].read_)
  313. remark = " (writeonly)";
  314. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  315. }
  316. }
  317. Log::WriteRaw("\n");
  318. }
  319. }
  320. Log::WriteRaw("*/\n\n}\n");
  321. }
  322. void Script::MessageCallback(const asSMessageInfo* msg)
  323. {
  324. String message;
  325. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  326. switch (msg->type)
  327. {
  328. case asMSGTYPE_ERROR:
  329. LOGERROR(message);
  330. break;
  331. case asMSGTYPE_WARNING:
  332. LOGWARNING(message);
  333. break;
  334. default:
  335. LOGINFO(message);
  336. break;
  337. }
  338. }
  339. void Script::ExceptionCallback(asIScriptContext* context)
  340. {
  341. String message;
  342. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  343. asSMessageInfo msg;
  344. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  345. msg.type = asMSGTYPE_ERROR;
  346. msg.message = message.CString();
  347. MessageCallback(&msg);
  348. }
  349. String Script::GetCallStack(asIScriptContext* context)
  350. {
  351. String str("AngelScript callstack:\n");
  352. // Append the call stack
  353. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  354. {
  355. asIScriptFunction* func;
  356. const char* scriptSection;
  357. int line, column;
  358. func = context->GetFunction(i);
  359. line = context->GetLineNumber(i, &column, &scriptSection);
  360. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  361. }
  362. return str;
  363. }
  364. ScriptFile* Script::GetDefaultScriptFile() const
  365. {
  366. return defaultScriptFile_;
  367. }
  368. Scene* Script::GetDefaultScene() const
  369. {
  370. return defaultScene_;
  371. }
  372. void Script::ClearObjectTypeCache()
  373. {
  374. objectTypes_.Clear();
  375. }
  376. asIObjectType* Script::GetObjectType(const char* declaration)
  377. {
  378. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  379. if (i != objectTypes_.End())
  380. return i->second_;
  381. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  382. objectTypes_[declaration] = type;
  383. return type;
  384. }
  385. asIScriptContext* Script::GetScriptFileContext()
  386. {
  387. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  388. {
  389. asIScriptContext* newContext = scriptEngine_->CreateContext();
  390. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  391. scriptFileContexts_.Push(newContext);
  392. }
  393. return scriptFileContexts_[scriptNestingLevel_];
  394. }
  395. void Script::OutputAPIRow(const String& row, bool removeReference)
  396. {
  397. String out = row;
  398. ///\todo We need Regex capability in String class to handle whole-word replacement correctly.
  399. // Temporary fix to prevent property name like 'doubleClickInterval' from being wrongly replaced.
  400. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  401. //out.Replace("double", "float");
  402. out.Replace("&in", "&");
  403. out.Replace("&out", "&");
  404. if (removeReference)
  405. out.Replace("&", "");
  406. Log::WriteRaw("- " + out + "\n");
  407. }
  408. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  409. {
  410. using namespace ConsoleCommand;
  411. Execute(eventData[P_COMMAND].GetString());
  412. }
  413. void RegisterScriptLibrary(Context* context)
  414. {
  415. ScriptFile::RegisterObject(context);
  416. ScriptInstance::RegisterObject(context);
  417. }
  418. }