Script.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. //
  2. // Copyright (c) 2008-2014 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 "File.h"
  27. #include "FileSystem.h"
  28. #include "Log.h"
  29. #include "Profiler.h"
  30. #include "Scene.h"
  31. #include "Script.h"
  32. #include "ScriptAPI.h"
  33. #include "ScriptFile.h"
  34. #include "ScriptInstance.h"
  35. #include <angelscript.h>
  36. #include "DebugNew.h"
  37. namespace Urho3D
  38. {
  39. /// %Object property info for scripting API dump.
  40. struct PropertyInfo
  41. {
  42. /// Construct.
  43. PropertyInfo() :
  44. read_(false),
  45. write_(false),
  46. indexed_(false)
  47. {
  48. }
  49. /// Property name.
  50. String name_;
  51. /// Property data type.
  52. String type_;
  53. /// Reading supported flag.
  54. bool read_;
  55. /// Writing supported flag.
  56. bool write_;
  57. /// Indexed flag.
  58. bool indexed_;
  59. };
  60. void ExtractPropertyInfo(const String& functionName, const String& declaration, Vector<PropertyInfo>& propertyInfos)
  61. {
  62. String propertyName = functionName.Substring(4);
  63. PropertyInfo* info = 0;
  64. for (unsigned k = 0; k < propertyInfos.Size(); ++k)
  65. {
  66. if (propertyInfos[k].name_ == propertyName)
  67. {
  68. info = &propertyInfos[k];
  69. break;
  70. }
  71. }
  72. if (!info)
  73. {
  74. propertyInfos.Resize(propertyInfos.Size() + 1);
  75. info = &propertyInfos.Back();
  76. info->name_ = propertyName;
  77. }
  78. if (functionName.Contains("get_"))
  79. {
  80. info->read_ = true;
  81. // Extract type from the return value
  82. Vector<String> parts = declaration.Split(' ');
  83. if (parts.Size())
  84. {
  85. if (parts[0] != "const")
  86. info->type_ = parts[0];
  87. else if (parts.Size() > 1)
  88. info->type_ = parts[1];
  89. }
  90. // If get method has parameters, it is indexed
  91. if (!declaration.Contains("()"))
  92. {
  93. info->indexed_ = true;
  94. info->type_ += "[]";
  95. }
  96. // Sanitate the reference operator away
  97. info->type_.Replace("&", "");
  98. }
  99. if (functionName.Contains("set_"))
  100. {
  101. info->write_ = true;
  102. if (info->type_.Empty())
  103. {
  104. // Extract type from parameters
  105. unsigned begin = declaration.Find(',');
  106. if (begin == String::NPOS)
  107. begin = declaration.Find('(');
  108. else
  109. info->indexed_ = true;
  110. if (begin != String::NPOS)
  111. {
  112. ++begin;
  113. unsigned end = declaration.Find(')');
  114. if (end != String::NPOS)
  115. {
  116. info->type_ = declaration.Substring(begin, end - begin);
  117. // Sanitate const & reference operator away
  118. info->type_.Replace("const ", "");
  119. info->type_.Replace("&in", "");
  120. info->type_.Replace("&", "");
  121. }
  122. }
  123. }
  124. }
  125. }
  126. bool ComparePropertyStrings(const String& lhs, const String& rhs)
  127. {
  128. int spaceLhs = lhs.Find(' ');
  129. int spaceRhs = rhs.Find(' ');
  130. if (spaceLhs != String::NPOS && spaceRhs != String::NPOS)
  131. return String::Compare(lhs.CString() + spaceLhs, rhs.CString() + spaceRhs, true) < 0;
  132. else
  133. return String::Compare(lhs.CString(), rhs.CString(), true) < 0;
  134. }
  135. bool ComparePropertyInfos(const PropertyInfo& lhs, const PropertyInfo& rhs)
  136. {
  137. return String::Compare(lhs.name_.CString(), rhs.name_.CString(), true) < 0;
  138. }
  139. Script::Script(Context* context) :
  140. Object(context),
  141. scriptEngine_(0),
  142. immediateContext_(0),
  143. scriptNestingLevel_(0)
  144. {
  145. scriptEngine_ = asCreateScriptEngine(ANGELSCRIPT_VERSION);
  146. if (!scriptEngine_)
  147. {
  148. LOGERROR("Could not create AngelScript engine");
  149. return;
  150. }
  151. scriptEngine_->SetUserData(this);
  152. scriptEngine_->SetEngineProperty(asEP_USE_CHARACTER_LITERALS, true);
  153. scriptEngine_->SetEngineProperty(asEP_ALLOW_UNSAFE_REFERENCES, true);
  154. scriptEngine_->SetEngineProperty(asEP_ALLOW_IMPLICIT_HANDLE_TYPES, true);
  155. scriptEngine_->SetEngineProperty(asEP_BUILD_WITHOUT_LINE_CUES, true);
  156. scriptEngine_->SetMessageCallback(asMETHOD(Script, MessageCallback), this, asCALL_THISCALL);
  157. // Create the context for immediate execution
  158. immediateContext_ = scriptEngine_->CreateContext();
  159. immediateContext_->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  160. // Register Script library object factories
  161. RegisterScriptLibrary(context_);
  162. // Register the Array, String & Dictionary API
  163. RegisterArray(scriptEngine_);
  164. RegisterString(scriptEngine_);
  165. RegisterDictionary(scriptEngine_);
  166. // Register the rest of the script API
  167. RegisterMathAPI(scriptEngine_);
  168. RegisterCoreAPI(scriptEngine_);
  169. RegisterIOAPI(scriptEngine_);
  170. RegisterResourceAPI(scriptEngine_);
  171. RegisterSceneAPI(scriptEngine_);
  172. RegisterGraphicsAPI(scriptEngine_);
  173. RegisterInputAPI(scriptEngine_);
  174. RegisterAudioAPI(scriptEngine_);
  175. RegisterUIAPI(scriptEngine_);
  176. RegisterNetworkAPI(scriptEngine_);
  177. RegisterPhysicsAPI(scriptEngine_);
  178. RegisterNavigationAPI(scriptEngine_);
  179. RegisterUrho2DAPI(scriptEngine_);
  180. RegisterScriptAPI(scriptEngine_);
  181. RegisterEngineAPI(scriptEngine_);
  182. // Subscribe to console commands
  183. SubscribeToEvent(E_CONSOLECOMMAND, HANDLER(Script, HandleConsoleCommand));
  184. }
  185. Script::~Script()
  186. {
  187. if (immediateContext_)
  188. {
  189. immediateContext_->Release();
  190. immediateContext_ = 0;
  191. }
  192. for (unsigned i = 0 ; i < scriptFileContexts_.Size(); ++i)
  193. scriptFileContexts_[i]->Release();
  194. if (scriptEngine_)
  195. {
  196. scriptEngine_->Release();
  197. scriptEngine_ = 0;
  198. }
  199. }
  200. bool Script::Execute(const String& line)
  201. {
  202. // Note: compiling code each time is slow. Not to be used for performance-critical or repeating activity
  203. PROFILE(ExecuteImmediate);
  204. ClearObjectTypeCache();
  205. String wrappedLine = "void f(){\n" + line + ";\n}";
  206. // If no immediate mode script file set, create a dummy module for compiling the line
  207. asIScriptModule* module = 0;
  208. if (defaultScriptFile_)
  209. module = defaultScriptFile_->GetScriptModule();
  210. if (!module)
  211. module = scriptEngine_->GetModule("ExecuteImmediate", asGM_CREATE_IF_NOT_EXISTS);
  212. if (!module)
  213. return false;
  214. asIScriptFunction *function = 0;
  215. if (module->CompileFunction("", wrappedLine.CString(), -1, 0, &function) < 0)
  216. return false;
  217. if (immediateContext_->Prepare(function) < 0)
  218. {
  219. function->Release();
  220. return false;
  221. }
  222. bool success = immediateContext_->Execute() >= 0;
  223. immediateContext_->Unprepare();
  224. function->Release();
  225. return success;
  226. }
  227. void Script::SetDefaultScriptFile(ScriptFile* file)
  228. {
  229. defaultScriptFile_ = file;
  230. }
  231. void Script::SetDefaultScene(Scene* scene)
  232. {
  233. defaultScene_ = scene;
  234. }
  235. void Script::DumpAPI(DumpMode mode)
  236. {
  237. // Does not use LOGRAW macro here to ensure the messages are always dumped regardless of ENABLE_LOGGING compiler directive and of Log subsystem availability
  238. if (mode == DOXYGEN)
  239. Log::WriteRaw("namespace Urho3D\n{\n\n/**\n\\page ScriptAPI Scripting API\n\n");
  240. else if (mode == C_HEADER)
  241. Log::WriteRaw("// Script API header intended to be 'force included' in IDE for AngelScript content assist / code completion\n\n"
  242. "#define int8 signed char\n"
  243. "#define int16 signed short\n"
  244. "#define int64 long\n"
  245. "#define uint8 unsigned char\n"
  246. "#define uint16 unsigned short\n"
  247. "#define uint64 unsigned long\n"
  248. "#define null 0\n");
  249. if (mode == DOXYGEN)
  250. Log::WriteRaw("\\section ScriptAPI_Classes Classes\n");
  251. else if (mode == C_HEADER)
  252. Log::WriteRaw("\n// Classes\n");
  253. unsigned types = scriptEngine_->GetObjectTypeCount();
  254. Vector<Pair<String, unsigned> > sortedTypes;
  255. for (unsigned i = 0; i < types; ++i)
  256. {
  257. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(i);
  258. if (type)
  259. {
  260. String typeName(type->GetName());
  261. sortedTypes.Push(MakePair(typeName, i));
  262. }
  263. }
  264. Sort(sortedTypes.Begin(), sortedTypes.End());
  265. for (unsigned i = 0; i < sortedTypes.Size(); ++i)
  266. {
  267. asIObjectType* type = scriptEngine_->GetObjectTypeByIndex(sortedTypes[i].second_);
  268. if (type)
  269. {
  270. String typeName(type->GetName());
  271. Vector<String> methodDeclarations;
  272. Vector<PropertyInfo> propertyInfos;
  273. if (mode == DOXYGEN)
  274. Log::WriteRaw("\n### " + typeName + "\n");
  275. else if (mode == C_HEADER)
  276. {
  277. ///\todo Find a cleaner way to do this instead of hardcoding
  278. if (typeName == "Array")
  279. Log::WriteRaw("\ntemplate <class T> class " + typeName + "\n{\n");
  280. else
  281. Log::WriteRaw("\nclass " + typeName + "\n{\n");
  282. }
  283. unsigned methods = type->GetMethodCount();
  284. for (unsigned j = 0; j < methods; ++j)
  285. {
  286. asIScriptFunction* method = type->GetMethodByIndex(j);
  287. String methodName(method->GetName());
  288. String declaration(method->GetDeclaration());
  289. if (methodName.Contains("get_") || methodName.Contains("set_"))
  290. ExtractPropertyInfo(methodName, declaration, propertyInfos);
  291. else
  292. {
  293. // Sanitate the method name. \todo For now, skip the operators
  294. if (!declaration.Contains("::op"))
  295. {
  296. String prefix(typeName + "::");
  297. declaration.Replace(prefix, "");
  298. ///\todo Is there a better way to mark deprecated API bindings for AngelScript?
  299. unsigned posBegin = declaration.FindLast("const String&in = \"deprecated:");
  300. if (posBegin != String::NPOS)
  301. {
  302. // Assume this 'mark' is added as the last parameter
  303. unsigned posEnd = declaration.Find(')', posBegin);
  304. if (posBegin != String::NPOS)
  305. {
  306. declaration.Replace(posBegin, posEnd - posBegin, "");
  307. posBegin = declaration.Find(", ", posBegin - 2);
  308. if (posBegin != String::NPOS)
  309. declaration.Replace(posBegin, 2, "");
  310. if (mode == DOXYGEN)
  311. declaration += " // deprecated";
  312. else if (mode == C_HEADER)
  313. declaration = "/* deprecated */\n" + declaration;
  314. }
  315. }
  316. methodDeclarations.Push(declaration);
  317. }
  318. }
  319. }
  320. // Assume that the same property is never both an accessor property, and a direct one
  321. unsigned properties = type->GetPropertyCount();
  322. for (unsigned j = 0; j < properties; ++j)
  323. {
  324. const char* propertyName;
  325. const char* propertyDeclaration;
  326. int typeId;
  327. type->GetProperty(j, &propertyName, &typeId);
  328. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  329. PropertyInfo newInfo;
  330. newInfo.name_ = String(propertyName);
  331. newInfo.type_ = String(propertyDeclaration);
  332. newInfo.read_ = newInfo.write_ = true;
  333. propertyInfos.Push(newInfo);
  334. }
  335. Sort(methodDeclarations.Begin(), methodDeclarations.End(), ComparePropertyStrings);
  336. Sort(propertyInfos.Begin(), propertyInfos.End(), ComparePropertyInfos);
  337. if (!methodDeclarations.Empty())
  338. {
  339. if (mode == DOXYGEN)
  340. Log::WriteRaw("\nMethods:\n\n");
  341. else if (mode == C_HEADER)
  342. Log::WriteRaw("// Methods:\n");
  343. for (unsigned j = 0; j < methodDeclarations.Size(); ++j)
  344. OutputAPIRow(mode, methodDeclarations[j]);
  345. }
  346. if (!propertyInfos.Empty())
  347. {
  348. if (mode == DOXYGEN)
  349. Log::WriteRaw("\nProperties:\n\n");
  350. else if (mode == C_HEADER)
  351. Log::WriteRaw("\n// Properties:\n");
  352. for (unsigned j = 0; j < propertyInfos.Size(); ++j)
  353. {
  354. String remark;
  355. String cppdoc;
  356. if (!propertyInfos[j].write_)
  357. remark = "readonly";
  358. else if (!propertyInfos[j].read_)
  359. remark = "writeonly";
  360. if (!remark.Empty())
  361. {
  362. if (mode == DOXYGEN)
  363. {
  364. remark = " // " + remark;
  365. }
  366. else if (mode == C_HEADER)
  367. {
  368. cppdoc = "/* " + remark + " */\n";
  369. remark.Clear();
  370. }
  371. }
  372. OutputAPIRow(mode, cppdoc + propertyInfos[j].type_ + " " + propertyInfos[j].name_ + remark);
  373. }
  374. }
  375. if (mode == DOXYGEN)
  376. Log::WriteRaw("\n");
  377. else if (mode == C_HEADER)
  378. Log::WriteRaw("};\n");
  379. }
  380. }
  381. Vector<PropertyInfo> globalPropertyInfos;
  382. Vector<String> globalFunctions;
  383. unsigned functions = scriptEngine_->GetGlobalFunctionCount();
  384. for (unsigned i = 0; i < functions; ++i)
  385. {
  386. asIScriptFunction* function = scriptEngine_->GetGlobalFunctionByIndex(i);
  387. String functionName(function->GetName());
  388. String declaration(function->GetDeclaration());
  389. if (functionName.Contains("set_") || functionName.Contains("get_"))
  390. ExtractPropertyInfo(functionName, declaration, globalPropertyInfos);
  391. else
  392. globalFunctions.Push(declaration);
  393. }
  394. Sort(globalFunctions.Begin(), globalFunctions.End(), ComparePropertyStrings);
  395. Sort(globalPropertyInfos.Begin(), globalPropertyInfos.End(), ComparePropertyInfos);
  396. if (mode == DOXYGEN)
  397. Log::WriteRaw("\\section ScriptAPI_Enums Enumerations\n");
  398. else if (mode == C_HEADER)
  399. Log::WriteRaw("\n// Enumerations\n");
  400. unsigned enums = scriptEngine_->GetEnumCount();
  401. Vector<Pair<String, unsigned> > sortedEnums;
  402. for (unsigned i = 0; i < enums; ++i)
  403. {
  404. int typeId;
  405. sortedEnums.Push(MakePair(String(scriptEngine_->GetEnumByIndex(i, &typeId)), i));
  406. }
  407. Sort(sortedEnums.Begin(), sortedEnums.End());
  408. for (unsigned i = 0; i < sortedEnums.Size(); ++i)
  409. {
  410. int typeId;
  411. if (mode == DOXYGEN)
  412. Log::WriteRaw("\n### " + String(scriptEngine_->GetEnumByIndex(sortedEnums[i].second_, &typeId)) + "\n\n");
  413. else if (mode == C_HEADER)
  414. Log::WriteRaw("\nenum " + String(scriptEngine_->GetEnumByIndex(sortedEnums[i].second_, &typeId)) + "\n{\n");
  415. for (unsigned j = 0; j < (unsigned)scriptEngine_->GetEnumValueCount(typeId); ++j)
  416. {
  417. int value = 0;
  418. const char* name = scriptEngine_->GetEnumValueByIndex(typeId, j, &value);
  419. OutputAPIRow(mode, String(name), false, ",");
  420. }
  421. if (mode == DOXYGEN)
  422. Log::WriteRaw("\n");
  423. else if (mode == C_HEADER)
  424. Log::WriteRaw("};\n");
  425. }
  426. if (mode == DOXYGEN)
  427. Log::WriteRaw("\\section ScriptAPI_GlobalFunctions Global functions\n");
  428. else if (mode == C_HEADER)
  429. Log::WriteRaw("\n// Global functions\n");
  430. for (unsigned i = 0; i < globalFunctions.Size(); ++i)
  431. OutputAPIRow(mode, globalFunctions[i]);
  432. if (mode == DOXYGEN)
  433. Log::WriteRaw("\\section ScriptAPI_GlobalProperties Global properties\n");
  434. else if (mode == C_HEADER)
  435. Log::WriteRaw("\n// Global properties\n");
  436. for (unsigned i = 0; i < globalPropertyInfos.Size(); ++i)
  437. OutputAPIRow(mode, globalPropertyInfos[i].type_ + " " + globalPropertyInfos[i].name_, true);
  438. if (mode == DOXYGEN)
  439. Log::WriteRaw("\\section ScriptAPI_GlobalConstants Global constants\n");
  440. else if (mode == C_HEADER)
  441. Log::WriteRaw("\n// Global constants\n");
  442. Vector<String> globalConstants;
  443. unsigned properties = scriptEngine_->GetGlobalPropertyCount();
  444. for (unsigned i = 0; i < properties; ++i)
  445. {
  446. const char* propertyName;
  447. const char* propertyDeclaration;
  448. int typeId;
  449. scriptEngine_->GetGlobalPropertyByIndex(i, &propertyName, 0, &typeId);
  450. propertyDeclaration = scriptEngine_->GetTypeDeclaration(typeId);
  451. String type(propertyDeclaration);
  452. globalConstants.Push(type + " " + String(propertyName));
  453. }
  454. Sort(globalConstants.Begin(), globalConstants.End(), ComparePropertyStrings);
  455. for (unsigned i = 0; i < globalConstants.Size(); ++i)
  456. OutputAPIRow(mode, globalConstants[i], true);
  457. // Dump event descriptions in Doxygen mode. This means going through the header files, as the information is not
  458. // available otherwise
  459. if (mode == DOXYGEN)
  460. {
  461. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  462. Vector<String> headerFiles;
  463. String path = fileSystem->GetProgramDir();
  464. path.Replace("/Bin", "/Source/Engine");
  465. fileSystem->ScanDir(headerFiles, path, "*.h", SCAN_FILES, true);
  466. if (!headerFiles.Empty())
  467. {
  468. Log::WriteRaw("\n\\page EventList Event list\n");
  469. Sort(headerFiles.Begin(), headerFiles.End());
  470. }
  471. for (unsigned i = 0; i < headerFiles.Size(); ++i)
  472. {
  473. if (headerFiles[i].EndsWith("Events.h"))
  474. {
  475. SharedPtr<File> file(new File(context_, path + headerFiles[i], FILE_READ));
  476. if (!file->IsOpen())
  477. continue;
  478. unsigned start = headerFiles[i].Find('/') + 1;
  479. unsigned end = headerFiles[i].Find("Events.h");
  480. Log::WriteRaw("\n## %" + headerFiles[i].Substring(start, end - start) + " events\n");
  481. while (!file->IsEof())
  482. {
  483. String line = file->ReadLine();
  484. if (line.StartsWith("EVENT"))
  485. {
  486. Vector<String> parts = line.Split(',');
  487. if (parts.Size() == 2)
  488. Log::WriteRaw("\n### " + parts[1].Substring(0, parts[1].Length() - 1).Trimmed() + "\n");
  489. }
  490. if (line.Contains("PARAM"))
  491. {
  492. Vector<String> parts = line.Split(',');
  493. if (parts.Size() == 2)
  494. {
  495. String paramName = parts[1].Substring(0, parts[1].Find(')')).Trimmed();
  496. String paramType = parts[1].Substring(parts[1].Find("// ") + 3);
  497. if (!paramName.Empty() && !paramType.Empty())
  498. Log::WriteRaw("- %" + paramName + " : " + paramType + "\n");
  499. }
  500. }
  501. }
  502. }
  503. }
  504. if (!headerFiles.Empty())
  505. Log::WriteRaw("\n");
  506. }
  507. if (mode == DOXYGEN)
  508. Log::WriteRaw("*/\n\n}\n");
  509. }
  510. void Script::MessageCallback(const asSMessageInfo* msg)
  511. {
  512. String message;
  513. message.AppendWithFormat("%s:%d,%d %s", msg->section, msg->row, msg->col, msg->message);
  514. switch (msg->type)
  515. {
  516. case asMSGTYPE_ERROR:
  517. LOGERROR(message);
  518. break;
  519. case asMSGTYPE_WARNING:
  520. LOGWARNING(message);
  521. break;
  522. default:
  523. LOGINFO(message);
  524. break;
  525. }
  526. }
  527. void Script::ExceptionCallback(asIScriptContext* context)
  528. {
  529. String message;
  530. message.AppendWithFormat("- Exception '%s' in '%s'\n%s", context->GetExceptionString(), context->GetExceptionFunction()->GetDeclaration(), GetCallStack(context).CString());
  531. asSMessageInfo msg;
  532. msg.row = context->GetExceptionLineNumber(&msg.col, &msg.section);
  533. msg.type = asMSGTYPE_ERROR;
  534. msg.message = message.CString();
  535. MessageCallback(&msg);
  536. }
  537. String Script::GetCallStack(asIScriptContext* context)
  538. {
  539. String str("AngelScript callstack:\n");
  540. // Append the call stack
  541. for (asUINT i = 0; i < context->GetCallstackSize(); i++)
  542. {
  543. asIScriptFunction* func;
  544. const char* scriptSection;
  545. int line, column;
  546. func = context->GetFunction(i);
  547. line = context->GetLineNumber(i, &column, &scriptSection);
  548. str.AppendWithFormat("\t%s:%s:%d,%d\n", scriptSection, func->GetDeclaration(), line, column);
  549. }
  550. return str;
  551. }
  552. ScriptFile* Script::GetDefaultScriptFile() const
  553. {
  554. return defaultScriptFile_;
  555. }
  556. Scene* Script::GetDefaultScene() const
  557. {
  558. return defaultScene_;
  559. }
  560. void Script::ClearObjectTypeCache()
  561. {
  562. objectTypes_.Clear();
  563. }
  564. asIObjectType* Script::GetObjectType(const char* declaration)
  565. {
  566. HashMap<const char*, asIObjectType*>::ConstIterator i = objectTypes_.Find(declaration);
  567. if (i != objectTypes_.End())
  568. return i->second_;
  569. asIObjectType* type = scriptEngine_->GetObjectTypeById(scriptEngine_->GetTypeIdByDecl(declaration));
  570. objectTypes_[declaration] = type;
  571. return type;
  572. }
  573. asIScriptContext* Script::GetScriptFileContext()
  574. {
  575. while (scriptNestingLevel_ >= scriptFileContexts_.Size())
  576. {
  577. asIScriptContext* newContext = scriptEngine_->CreateContext();
  578. newContext->SetExceptionCallback(asMETHOD(Script, ExceptionCallback), this, asCALL_THISCALL);
  579. scriptFileContexts_.Push(newContext);
  580. }
  581. return scriptFileContexts_[scriptNestingLevel_];
  582. }
  583. void Script::OutputAPIRow(DumpMode mode, const String& row, bool removeReference, String separator)
  584. {
  585. String out(row);
  586. ///\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.
  587. // Commenting out to temporary fix property name like 'doubleClickInterval' from being wrongly replaced.
  588. // Fortunately, there is no occurence of type 'double' in the API at the moment.
  589. //out.Replace("double", "float"); // s/\bdouble\b/float/g
  590. out.Replace("&in", "&");
  591. out.Replace("&out", "&");
  592. if (removeReference)
  593. out.Replace("&", "");
  594. if (mode == DOXYGEN)
  595. Log::WriteRaw("- " + out + "\n");
  596. else if (mode == C_HEADER)
  597. {
  598. out.Replace("@", "");
  599. out.Replace("?&", "void*");
  600. // s/(\w+)\[\]/Array<\1>/g
  601. unsigned posBegin = String::NPOS;
  602. while (1) // Loop to cater for array of array of T
  603. {
  604. unsigned posEnd = out.Find("[]");
  605. if (posEnd == String::NPOS)
  606. break;
  607. if (posBegin > posEnd)
  608. posBegin = posEnd - 1;
  609. while (posBegin < posEnd && isalnum(out[posBegin]))
  610. --posBegin;
  611. ++posBegin;
  612. out.Replace(posBegin, posEnd - posBegin + 2, "Array<" + out.Substring(posBegin, posEnd - posBegin) + ">");
  613. }
  614. Log::WriteRaw(out + separator + "\n");
  615. }
  616. }
  617. void Script::HandleConsoleCommand(StringHash eventType, VariantMap& eventData)
  618. {
  619. using namespace ConsoleCommand;
  620. Execute(eventData[P_COMMAND].GetString());
  621. }
  622. void RegisterScriptLibrary(Context* context)
  623. {
  624. ScriptFile::RegisterObject(context);
  625. ScriptInstance::RegisterObject(context);
  626. }
  627. }