ScriptComponent.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright (C) 2009-2018, 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. {
  13. ScriptComponent::ScriptComponent(SceneNode* node)
  14. : SceneComponent(CLASS_TYPE, node)
  15. {
  16. }
  17. ScriptComponent::~ScriptComponent()
  18. {
  19. }
  20. Error ScriptComponent::load(CString fname)
  21. {
  22. // Load
  23. ANKI_CHECK(getSceneGraph().getResourceManager().loadResource(fname, m_script));
  24. // Create the env
  25. ANKI_CHECK(getSceneGraph().getScriptManager().newScriptEnvironment(m_env));
  26. // Exec the script
  27. ANKI_CHECK(m_env->evalString(m_script->getSource()));
  28. return Error::NONE;
  29. }
  30. Error ScriptComponent::update(Second prevTime, Second crntTime, Bool& updated)
  31. {
  32. updated = false;
  33. lua_State* lua = &m_env->getLuaState();
  34. // Push function name
  35. lua_getglobal(lua, "update");
  36. // Push args
  37. LuaBinder::pushVariableToTheStack(lua, m_node);
  38. lua_pushnumber(lua, prevTime);
  39. lua_pushnumber(lua, crntTime);
  40. // Do the call (3 arguments, 1 result)
  41. if(lua_pcall(lua, 3, 1, 0) != 0)
  42. {
  43. ANKI_SCENE_LOGE("Error running ScriptComponent's \"update\": %s", lua_tostring(lua, -1));
  44. return Error::USER_DATA;
  45. }
  46. if(!lua_isnumber(lua, -1))
  47. {
  48. ANKI_SCENE_LOGE("ScriptComponent's \"update\" should return a number");
  49. lua_pop(lua, 1);
  50. return Error::USER_DATA;
  51. }
  52. // Get the result
  53. lua_Number result = lua_tonumber(lua, -1);
  54. lua_pop(lua, 1);
  55. if(result < 0)
  56. {
  57. ANKI_SCENE_LOGE("ScriptComponent's \"update\" return an error code");
  58. return Error::USER_DATA;
  59. }
  60. updated = (result != 0);
  61. return Error::NONE;
  62. }
  63. } // end namespace anki