Script.cpp 14 KB

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