ScriptEvent.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Scene/Events/ScriptEvent.h>
  6. #include <AnKi/Util/Filesystem.h>
  7. #include <AnKi/Resource/ScriptResource.h>
  8. #include <AnKi/Script/ScriptEnvironment.h>
  9. #include <AnKi/Script/ScriptManager.h>
  10. #include <AnKi/Scene/SceneGraph.h>
  11. #include <AnKi/Resource/ResourceManager.h>
  12. namespace anki {
  13. ScriptEvent::ScriptEvent(Second startTime, Second duration, CString script)
  14. : Event(startTime, duration)
  15. {
  16. // Do the rest
  17. String extension;
  18. getFilepathExtension(script, extension);
  19. if(!extension.isEmpty() && extension == "lua")
  20. {
  21. // It's a file
  22. if(!ANKI_EXPECT(!ResourceManager::getSingleton().loadResource(script, m_scriptRsrc)))
  23. {
  24. markForDeletion();
  25. return;
  26. }
  27. // Exec the script
  28. if(!ANKI_EXPECT(!m_env.evalString(m_scriptRsrc->getSource())))
  29. {
  30. markForDeletion();
  31. return;
  32. }
  33. }
  34. else
  35. {
  36. // It's a string
  37. m_script = script;
  38. // Exec the script
  39. if(!ANKI_EXPECT(!m_env.evalString(m_script.toCString())))
  40. {
  41. markForDeletion();
  42. return;
  43. }
  44. }
  45. }
  46. ScriptEvent::~ScriptEvent()
  47. {
  48. }
  49. void ScriptEvent::update(Second prevUpdateTime, Second crntTime)
  50. {
  51. lua_State* lua = &m_env.getLuaState();
  52. // Push function name
  53. lua_getglobal(lua, "update");
  54. // Push args
  55. LuaBinder::pushVariableToTheStack(lua, static_cast<Event*>(this));
  56. lua_pushnumber(lua, prevUpdateTime);
  57. lua_pushnumber(lua, crntTime);
  58. // Do the call (3 arguments, no result)
  59. if(lua_pcall(lua, 3, 0, 0) != 0)
  60. {
  61. ANKI_SCENE_LOGE("Error running ScriptEvent's \"update\": %s", lua_tostring(lua, -1));
  62. return;
  63. }
  64. }
  65. void ScriptEvent::onKilled(Second prevUpdateTime, Second crntTime)
  66. {
  67. lua_State* lua = &m_env.getLuaState();
  68. // Push function name
  69. lua_getglobal(lua, "onKilled");
  70. // Push args
  71. LuaBinder::pushVariableToTheStack(lua, static_cast<Event*>(this));
  72. lua_pushnumber(lua, prevUpdateTime);
  73. lua_pushnumber(lua, crntTime);
  74. // Do the call (3 arguments, no result)
  75. if(lua_pcall(lua, 3, 0, 0) != 0)
  76. {
  77. ANKI_SCENE_LOGE("Error running ScriptEvent's \"onKilled\": %s", lua_tostring(lua, -1));
  78. return;
  79. }
  80. }
  81. } // end namespace anki