Script.cpp 14 KB

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