Script.cpp 14 KB

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