ScriptComponent.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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/Components/ScriptComponent.h>
  6. #include <AnKi/Scene/SceneGraph.h>
  7. #include <AnKi/Resource/ResourceManager.h>
  8. #include <AnKi/Resource/ScriptResource.h>
  9. #include <AnKi/Script/ScriptManager.h>
  10. #include <AnKi/Script/ScriptEnvironment.h>
  11. namespace anki {
  12. ScriptComponent::ScriptComponent(SceneNode* node)
  13. : SceneComponent(node, kClassType)
  14. {
  15. ANKI_ASSERT(node);
  16. }
  17. ScriptComponent::~ScriptComponent()
  18. {
  19. deleteInstance(SceneMemoryPool::getSingleton(), m_env);
  20. }
  21. void ScriptComponent::loadScriptResource(CString fname)
  22. {
  23. // Load
  24. ScriptResourcePtr rsrc;
  25. Error err = ResourceManager::getSingleton().loadResource(fname, rsrc);
  26. // Create the env
  27. ScriptEnvironment* newEnv = nullptr;
  28. if(!err)
  29. {
  30. newEnv = newInstance<ScriptEnvironment>(SceneMemoryPool::getSingleton());
  31. }
  32. // Exec the script
  33. if(!err)
  34. {
  35. err = newEnv->evalString(m_script->getSource());
  36. }
  37. // Error
  38. if(err)
  39. {
  40. ANKI_SCENE_LOGE("Failed to load the script");
  41. deleteInstance(SceneMemoryPool::getSingleton(), newEnv);
  42. }
  43. else
  44. {
  45. m_script = std::move(rsrc);
  46. deleteInstance(SceneMemoryPool::getSingleton(), m_env);
  47. m_env = newEnv;
  48. }
  49. }
  50. void ScriptComponent::update(SceneComponentUpdateInfo& info, Bool& updated)
  51. {
  52. updated = false;
  53. if(m_env == nullptr)
  54. {
  55. return;
  56. }
  57. lua_State* lua = &m_env->getLuaState();
  58. // Push function name
  59. lua_getglobal(lua, "update");
  60. // Push args
  61. LuaBinder::pushVariableToTheStack(lua, info.m_node);
  62. lua_pushnumber(lua, info.m_previousTime);
  63. lua_pushnumber(lua, info.m_currentTime);
  64. // Do the call (3 arguments, no result)
  65. if(lua_pcall(lua, 3, 0, 0) != 0)
  66. {
  67. ANKI_SCENE_LOGE("Error running ScriptComponent's \"update\": %s", lua_tostring(lua, -1));
  68. return;
  69. }
  70. updated = true;
  71. }
  72. } // end namespace anki