Script.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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(DumpMode mode)
  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. if (mode == DOXYGEN)
  222. Log::WriteRaw("namespace Urho3D\n{\n\n/**\n\\page ScriptAPI Scripting API\n\n");
  223. else if (mode == C_HEADER)
  224. Log::WriteRaw("// Script API header for AngelScript content assist / code completion in IDE\n\n#define uint8 uint\n#define uint16 uint\n#define int8 int\n#define int16 int\n#define null 0\n");
  225. if (mode == DOXYGEN)
  226. Log::WriteRaw("\\section ScriptAPI_Enums Enumerations\n");
  227. else if (mode == C_HEADER)
  228. Log::WriteRaw("\n// Enumerations\n");
  229. unsigned enums = scriptEngine_->GetEnumCount();
  230. for (unsigned i = 0; i < enums; ++i)
  231. {
  232. int typeId;
  233. if (mode == DOXYGEN)
  234. Log::WriteRaw("\n### " + String(scriptEngine_->GetEnumByIndex(i, &typeId)) + "\n\n");
  235. else if (mode == C_HEADER)
  236. Log::WriteRaw("\nenum " + String(scriptEngine_->GetEnumByIndex(i, &typeId)) + "\n{\n");
  237. for (unsigned j = 0; j < (unsigned)scriptEngine_->GetEnumValueCount(typeId); ++j)
  238. {
  239. int value = 0;
  240. const char* name = scriptEngine_->GetEnumValueByIndex(typeId, j, &value);
  241. OutputAPIRow(mode, String(name), false, ",");
  242. }
  243. if (mode == DOXYGEN)
  244. Log::WriteRaw("\n");
  245. else if (mode == C_HEADER)
  246. Log::WriteRaw("};\n");
  247. }
  248. if (mode == DOXYGEN)
  249. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  250. else if (mode == C_HEADER)
  251. Log::WriteRaw("\n// Classes\n");
  252. unsigned types = scriptEngine_->GetObjectTypeCount();
  253. for (unsigned i = 0; i < types; ++i)
  254. {
  255. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  256. if (type)
  257. {
  258. String typeName(type->GetName());
  259. Vector<String> methodDeclarations;
  260. Vector<PropertyInfo> propertyInfos;
  261. if (mode == DOXYGEN)
  262. Log::WriteRaw("\n### " + typeName + "\n");
  263. else if (mode == C_HEADER)
  264. {
  265. ///\todo Find a cleaner way to do this instead of hardcoding
  266. if (typeName == "Array")
  267. Log::WriteRaw("\ntemplate <class T> class " + typeName + "\n{\n");
  268. else
  269. Log::WriteRaw("\nclass " + typeName + "\n{\n");
  270. }
  271. unsigned methods = type->GetMethodCount();
  272. for (unsigned j = 0; j < methods; ++j)
  273. {
  274. asIScriptFunction* method = type->GetMethodByIndex(j);
  275. String methodName(method->GetName());
  276. String declaration(method->GetDeclaration());
  277. if (methodName.Contains("get_") || methodName.Contains("set_"))
  278. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  279. else
  280. {
  281. // Sanitate the method name. \todo For now, skip the operators
  282. if (!declaration.Contains("::op"))
  283. {
  284. String prefix(typeName + "::");
  285. declaration.Replace(prefix, "");
  286. methodDeclarations.Push(declaration);
  287. }
  288. }
  289. }
  290. // Assume that the same property is never both an accessor property, and a direct one
  291. unsigned properties = type->GetPropertyCount();
  292. for (unsigned j = 0; j < properties; ++j)
  293. {
  294. const char* propertyName;
  295. const char* propertyDeclaration;
  296. int typeId;
  297. type->GetProperty(j, &propertyName, &typeId);
  298. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  299. PropertyInfo newInfo;
  300. newInfo.name_ = String(propertyName);
  301. newInfo.type_ = String(propertyDeclaration);
  302. newInfo.read_ = newInfo.write_ = true;
  303. propertyInfos.Push(newInfo);
  304. }
  305. if (!methodDeclarations.Empty())
  306. {
  307. if (mode == DOXYGEN)
  308. Log::WriteRaw("\nMethods:\n\n");
  309. else if (mode == C_HEADER)
  310. Log::WriteRaw("// Methods:\n");
  311. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  312. OutputAPIRow(mode, methodDeclarations[j]);
  313. }
  314. if (!propertyInfos.Empty())
  315. {
  316. if (mode == DOXYGEN)
  317. Log::WriteRaw("\nProperties:\n\n");
  318. else if (mode == C_HEADER)
  319. Log::WriteRaw("\n// Properties:\n");
  320. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  321. {
  322. String remark;
  323. String cppdoc;
  324. if (!propertyInfos[j].write_)
  325. remark = " (readonly)";
  326. else if (!propertyInfos[j].read_)
  327. remark = " (writeonly)";
  328. if (mode == C_HEADER && !remark.Empty())
  329. {
  330. cppdoc = "/*" + remark + " */\n";
  331. remark.Clear();
  332. }
  333. OutputAPIRow(mode, cppdoc + propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  334. }
  335. }
  336. if (mode == DOXYGEN)
  337. Log::WriteRaw("\n");
  338. else if (mode == C_HEADER)
  339. Log::WriteRaw("};\n");
  340. }
  341. }
  342. Vector<PropertyInfo> globalPropertyInfos;
  343. Vector<String> globalFunctions;
  344. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  345. for (unsigned i = 0; i < functions; ++i)
  346. {
  347. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  348. String functionName(function->GetName());
  349. String declaration(function->GetDeclaration());
  350. if (functionName.Contains("set_") || functionName.Contains("get_"))
  351. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  352. else
  353. globalFunctions.Push(declaration);
  354. }
  355. if (mode == DOXYGEN)
  356. Log::WriteRaw("\\section ScriptAPI_GlobalFunctions Global functions\n");
  357. else if (mode == C_HEADER)
  358. Log::WriteRaw("\n// Global functions\n");
  359. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  360. OutputAPIRow(mode, globalFunctions[i]);
  361. if (mode == DOXYGEN)
  362. Log::WriteRaw("\\section ScriptAPI_GlobalProperties Global properties\n");
  363. else if (mode == C_HEADER)
  364. Log::WriteRaw("\n// Global properties\n");
  365. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  366. OutputAPIRow(mode, globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  367. if (mode == DOXYGEN)
  368. Log::WriteRaw("\\section ScriptAPI_GlobalConstants Global constants\n");
  369. else if (mode == C_HEADER)
  370. Log::WriteRaw("\n// Global constants\n");
  371. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  372. for (unsigned i = 0; i < properties; ++i)
  373. {
  374. const char* propertyName;
  375. const char* propertyDeclaration;
  376. int typeId;
  377. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  378. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  379. String type(propertyDeclaration);
  380. OutputAPIRow(mode, type + " " + String(propertyName), true);
  381. }
  382. if (mode == DOXYGEN)
  383. Log::WriteRaw("*/\n\n}\n");
  384. }
  385. void Script::MessageCallback(const asSMessageInfo* msg)
  386. {
  387. String message;
  388. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  389. switch (msg->type)
  390. {
  391. case asMSGTYPE_ERROR:
  392. LOGERROR(message);
  393. break;
  394. case asMSGTYPE_WARNING:
  395. LOGWARNING(message);
  396. break;
  397. default:
  398. LOGINFO(message);
  399. break;
  400. }
  401. }
  402. void Script::ExceptionCallback(asIScriptContext* context)
  403. {
  404. String message;
  405. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  406. asSMessageInfo msg;
  407. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  408. msg.type = asMSGTYPE_ERROR;
  409. msg.message = message.CString();
  410. MessageCallback(&msg);
  411. }
  412. String Script::GetCallStack(asIScriptContext* context)
  413. {
  414. String str("AngelScript callstack:\n");
  415. // Append the call stack
  416. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  417. {
  418. asIScriptFunction* func;
  419. const char* scriptSection;
  420. int line, column;
  421. func = context->GetFunction(i);
  422. line = context->GetLineNumber(i, &column, &scriptSection);
  423. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  424. }
  425. return str;
  426. }
  427. ScriptFile* Script::GetDefaultScriptFile() const
  428. {
  429. return defaultScriptFile_;
  430. }
  431. Scene* Script::GetDefaultScene() const
  432. {
  433. return defaultScene_;
  434. }
  435. void Script::ClearObjectTypeCache()
  436. {
  437. objectTypes_.Clear();
  438. }
  439. asIObjectType* Script::GetObjectType(const char* declaration)
  440. {
  441. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  442. if (i != objectTypes_.End())
  443. return i->second_;
  444. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  445. objectTypes_[declaration] = type;
  446. return type;
  447. }
  448. asIScriptContext* Script::GetScriptFileContext()
  449. {
  450. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  451. {
  452. asIScriptContext* newContext = scriptEngine_->CreateContext();
  453. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  454. scriptFileContexts_.Push(newContext);
  455. }
  456. return scriptFileContexts_[scriptNestingLevel_];
  457. }
  458. void Script::OutputAPIRow(DumpMode mode, const String& row, bool removeReference, String separator)
  459. {
  460. String out(row);
  461. ///\todo We need C++11 <regex> in String class to handle REGEX whole-word replacement correctly. Can't do that since we still support VS2008.
  462. // Commenting out to temporary fix property name like 'doubleClickInterval' from being wrongly replaced.
  463. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  464. //out.Replace("double", "float"); // s/\bdouble\b/float/g
  465. out.Replace("&in", "&");
  466. out.Replace("&out", "&");
  467. if (removeReference)
  468. out.Replace("&", "");
  469. if (mode == DOXYGEN)
  470. Log::WriteRaw("- " + out + "\n");
  471. else if (mode == C_HEADER)
  472. {
  473. out.Replace("@", "");
  474. // s/(\w+)\[\]/Array<\1>/g
  475. unsigned posBegin = String::NPOS;
  476. while (1) // Loop to cater for array of array of T
  477. {
  478. unsigned posEnd = out.Find("[]");
  479. if (posEnd == String::NPOS)
  480. break;
  481. if (posBegin > posEnd)
  482. posBegin = posEnd - 1;
  483. while (isalnum(out.Substring(posBegin, 1)[0]) && posBegin < posEnd)
  484. --posBegin;
  485. ++posBegin;
  486. out.Replace(posBegin, posEnd - posBegin + 2, "Array<" + out.Substring(posBegin, posEnd - posBegin) + ">");
  487. }
  488. Log::WriteRaw(out + separator + "\n");
  489. }
  490. }
  491. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  492. {
  493. using namespace ConsoleCommand;
  494. Execute(eventData[P_COMMAND].GetString());
  495. }
  496. void RegisterScriptLibrary(Context* context)
  497. {
  498. ScriptFile::RegisterObject(context);
  499. ScriptInstance::RegisterObject(context);
  500. }
  501. }