Script.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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_Enums Enumerations\n");
  254. unsigned enums = scriptEngine_->GetEnumCount();
  255. for (unsigned i = 0; i < enums; ++i)
  256. {
  257. int typeId;
  258. Log::WriteRaw("\n### " + String(scriptEngine_->GetEnumByIndex(i, &typeId)) + "\n\n");
  259. for (unsigned j = 0; j < (unsigned)scriptEngine_->GetEnumValueCount(typeId); ++j)
  260. {
  261. int value = 0;
  262. const char* name = scriptEngine_->GetEnumValueByIndex(typeId, j, &value);
  263. OutputAPIRow(String(name));
  264. }
  265. Log::WriteRaw("\n");
  266. }
  267. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  268. unsigned types = scriptEngine_->GetObjectTypeCount();
  269. for (unsigned i = 0; i < types; ++i)
  270. {
  271. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  272. if (type)
  273. {
  274. String typeName(type->GetName());
  275. Vector<String> methodDeclarations;
  276. Vector<PropertyInfo> propertyInfos;
  277. Log::WriteRaw("\n### " + typeName + "\n");
  278. unsigned methods = type->GetMethodCount();
  279. for (unsigned j = 0; j < methods; ++j)
  280. {
  281. asIScriptFunction* method = type->GetMethodByIndex(j);
  282. String methodName(method->GetName());
  283. String declaration(method->GetDeclaration());
  284. if (methodName.Contains("get_") || methodName.Contains("set_"))
  285. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  286. else
  287. {
  288. // Sanitate the method name. \todo For now, skip the operators
  289. if (!declaration.Contains("::op"))
  290. {
  291. String prefix(typeName + "::");
  292. declaration.Replace(prefix, "");
  293. methodDeclarations.Push(declaration);
  294. }
  295. }
  296. }
  297. // Assume that the same property is never both an accessor property, and a direct one
  298. unsigned properties = type->GetPropertyCount();
  299. for (unsigned j = 0; j < properties; ++j)
  300. {
  301. const char* propertyName;
  302. const char* propertyDeclaration;
  303. int typeId;
  304. type->GetProperty(j, &propertyName, &typeId);
  305. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  306. PropertyInfo newInfo;
  307. newInfo.name_ = String(propertyName);
  308. newInfo.type_ = String(propertyDeclaration);
  309. newInfo.read_ = newInfo.write_ = true;
  310. propertyInfos.Push(newInfo);
  311. }
  312. if (!methodDeclarations.Empty())
  313. {
  314. Log::WriteRaw("\nMethods:\n\n");
  315. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  316. OutputAPIRow(methodDeclarations[j]);
  317. }
  318. if (!propertyInfos.Empty())
  319. {
  320. Log::WriteRaw("\nProperties:\n\n");
  321. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  322. {
  323. String remark;
  324. if (!propertyInfos[j].write_)
  325. remark = " (readonly)";
  326. else if (!propertyInfos[j].read_)
  327. remark = " (writeonly)";
  328. OutputAPIRow(propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  329. }
  330. }
  331. Log::WriteRaw("\n");
  332. }
  333. }
  334. Log::WriteRaw("*/\n\n}\n");
  335. }
  336. void Script::MessageCallback(const asSMessageInfo* msg)
  337. {
  338. String message;
  339. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  340. switch (msg->type)
  341. {
  342. case asMSGTYPE_ERROR:
  343. LOGERROR(message);
  344. break;
  345. case asMSGTYPE_WARNING:
  346. LOGWARNING(message);
  347. break;
  348. default:
  349. LOGINFO(message);
  350. break;
  351. }
  352. }
  353. void Script::ExceptionCallback(asIScriptContext* context)
  354. {
  355. String message;
  356. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  357. asSMessageInfo msg;
  358. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  359. msg.type = asMSGTYPE_ERROR;
  360. msg.message = message.CString();
  361. MessageCallback(&msg);
  362. }
  363. String Script::GetCallStack(asIScriptContext* context)
  364. {
  365. String str("AngelScript callstack:\n");
  366. // Append the call stack
  367. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  368. {
  369. asIScriptFunction* func;
  370. const char* scriptSection;
  371. int line, column;
  372. func = context->GetFunction(i);
  373. line = context->GetLineNumber(i, &column, &scriptSection);
  374. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  375. }
  376. return str;
  377. }
  378. ScriptFile* Script::GetDefaultScriptFile() const
  379. {
  380. return defaultScriptFile_;
  381. }
  382. Scene* Script::GetDefaultScene() const
  383. {
  384. return defaultScene_;
  385. }
  386. void Script::ClearObjectTypeCache()
  387. {
  388. objectTypes_.Clear();
  389. }
  390. asIObjectType* Script::GetObjectType(const char* declaration)
  391. {
  392. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  393. if (i != objectTypes_.End())
  394. return i->second_;
  395. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  396. objectTypes_[declaration] = type;
  397. return type;
  398. }
  399. asIScriptContext* Script::GetScriptFileContext()
  400. {
  401. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  402. {
  403. asIScriptContext* newContext = scriptEngine_->CreateContext();
  404. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  405. scriptFileContexts_.Push(newContext);
  406. }
  407. return scriptFileContexts_[scriptNestingLevel_];
  408. }
  409. void Script::OutputAPIRow(const String& row, bool removeReference)
  410. {
  411. String out = row;
  412. ///\todo We need Regex capability in String class to handle whole-word replacement correctly.
  413. // Temporary fix to prevent property name like 'doubleClickInterval' from being wrongly replaced.
  414. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  415. //out.Replace("double", "float");
  416. out.Replace("&in", "&");
  417. out.Replace("&out", "&");
  418. if (removeReference)
  419. out.Replace("&", "");
  420. Log::WriteRaw("- " + out + "\n");
  421. }
  422. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  423. {
  424. using namespace ConsoleCommand;
  425. Execute(eventData[P_COMMAND].GetString());
  426. }
  427. void RegisterScriptLibrary(Context* context)
  428. {
  429. ScriptFile::RegisterObject(context);
  430. ScriptInstance::RegisterObject(context);
  431. }
  432. }