Script.cpp 26 KB

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