Пример #1
0
bool ReadScript::OpenTableIntegers(const int _key)
{
  if (!IsOpen())
  {
    errors.push(ScriptError { ScriptError::FILE_NOT_OPENED, "No script open. Call OpenFile() first." });
    return false;
  }

  // No tables opened, so we need to open globally
  if (open_tables.empty())
  {
    errors.push(ScriptError { ScriptError::TABLE_NOT_FOUND, "Unable to open integer table globally: " + std::to_string(_key) });
    return false;
  }
  else
  {
    LuaRef temp = open_tables.top()[_key];
    if (temp.isTable())
      open_tables.push(temp);
    else
    {
      errors.push(ScriptError { ScriptError::TABLE_NOT_FOUND, "Table not found in script: " + std::to_string(_key) });
      PRINT_WARNING << "Unable to open table (doesn't exist): " << _key << endl;
      return false;
    }
  }
  return true;
}
Пример #2
0
 void ControlSystem::createComponent(luabridge::LuaRef& luaE,
     std::map<std::type_index, std::unique_ptr<IComponent>>& list) {
     using namespace luabridge;
     LuaRef luaComponents = luaE["components"];
     LuaRef luaCC = luaComponents["ControlComponent"];
     if(luaCC.isNil()) return;
     auto* cc = new ControlComponent();
     LuaRef luaControl = luaCC["control"];
     LuaRef luaScriptName = luaCC["scriptName"];
     cc->m_control = luaControl.cast<bool>();
     cc->m_scriptName = luaScriptName.cast<std::string>();
     if(cc->m_scriptName == "") {
         cc->m_script = false;
     } else {
         if(m_scripts.find(cc->m_scriptName) == m_scripts.end()) {
             using namespace luabridge;
             auto* L = m_game.getLuaState();
             std::string file = "assets/data/world/scripts/" + cc->m_scriptName + ".lua";
             if(luaL_loadfile(L, file.c_str()) || lua_pcall(L, 0, 0, 0)) {
                 LogHandler::log<Field>(ERR, "Script \"" + file + "\" not found");
                 cc->m_script = false;
             } else {
                 cc->m_script = true;
                 luabridge::LuaRef& luaOnInput = getGlobal(L, "onInput");
                 m_scripts[cc->m_scriptName] = std::make_shared<LuaRef>(luaOnInput);
             }
         } else {
             cc->m_script = true;
         }
     }
     list[std::type_index(typeid(ControlComponent))] = std::unique_ptr<ControlComponent>(cc);
 }
Пример #3
0
bool ReadScript::OpenTable(const std::string& _table_name)
{
  if (!IsOpen())
  {
    errors.push(ScriptError { ScriptError::FILE_NOT_OPENED, "No script open. Call OpenFile() first." });
    return false;
  }

  // No tables opened, so we need to open globally
  if (open_tables.empty())
  {
    LuaRef temp = getGlobal(L, _table_name.c_str());
    if (temp.isNil())
    {
      errors.push(ScriptError { ScriptError::TABLE_NOT_FOUND, "Table not found in script: " + _table_name });
      return false;
    }
    open_tables.push(temp);
  }
  else
  {
    LuaRef temp = open_tables.top()[_table_name];
    if (temp.isTable())
      open_tables.push(temp);
    else
    {
      errors.push(ScriptError { ScriptError::TABLE_NOT_FOUND, "Table not found in script: " + _table_name });
      return false;
    }
  }
  return true;
}
Пример #4
0
LUA_INLINE bool CppBindClassBase::buildMetaTable(LuaRef& meta, LuaRef& parent, const char* name,
    void* static_id, void* clazz_id, void* const_id, void* super_static_id)
{
    if (buildMetaTable(meta, parent, name, static_id, clazz_id, const_id)) {
        LuaRef registry(parent.state(), LUA_REGISTRYINDEX);
        LuaRef super = registry.rawget<LuaRef>(super_static_id);
        meta.rawset("___super", super);
        meta.rawget<LuaRef>("___class").rawset("___super", super.rawget<LuaRef>("___class"));
        meta.rawget<LuaRef>("___const").rawset("___super", super.rawget<LuaRef>("___const"));
        return true;
    }
    return false;
}
Пример #5
0
void StructEncoder::EncodeStructFieldToBuf(const Field& field,
	const LuaRef& luaTable, uint8_t* pBuf)
{
	assert(pBuf);
	const char* pFieldName = field.name()->c_str();
	const LuaRef luaValue = luaTable.get(pFieldName);
	if (!luaValue)
		ERR_RET("missing struct field " + PopFullName());

	const reflection::Type& type = *field.type();
	uint16_t offset = field.offset();
	uint8_t* pDest = pBuf + offset;
	if (IsEnumType(type))
		return EncodeEnumToBuf(type, luaValue, pDest);

	reflection::BaseType eBaseType = type.base_type();
	if (eBaseType <= reflection::Double)
	{
		EncodeScalarToBuf(eBaseType, luaValue, pDest);
		return;
	}

	assert(eBaseType == reflection::Obj);
	const Object* pFieldObj = Objects()[type.index()];
	assert(pFieldObj);
	assert(pFieldObj->is_struct());
	EncodeStructToBuf(*pFieldObj, luaValue, pDest);
}  // EncodeStructFieldToBuf()
Пример #6
0
void StructEncoder::EncodeEnumToBuf(const reflection::Type& type,
	const LuaRef& luaValue, uint8_t* pDest)
{
	assert(pDest);
	assert(IsEnumType(type));
	using namespace reflection;
	if (luaValue.type() != LuaIntf::LuaTypeID::STRING)
		return EncodeScalarToBuf(type.base_type(), luaValue, pDest);

	int64_t lEnumVal = GetEnumFromLuaStr(type, luaValue);
	if (Bad()) return;
	switch (type.base_type())
	{
	case UType:
	case Bool:
	case UByte: return CopyIntToBuf<uint8_t>(lEnumVal, pDest);
	case Byte: return CopyIntToBuf<int8_t>(lEnumVal, pDest);
	case Short: return CopyIntToBuf<int16_t>(lEnumVal, pDest);
	case UShort: return CopyIntToBuf<uint16_t>(lEnumVal, pDest);
	case Int: return CopyIntToBuf<int32_t>(lEnumVal, pDest);
	case UInt: return CopyIntToBuf<uint32_t>(lEnumVal, pDest);
	case Long: return CopyIntToBuf<int64_t>(lEnumVal, pDest);
	case ULong: return CopyIntToBuf<uint64_t>(lEnumVal, pDest);
	}
	assert(!"Illegal enum type.");
}
Пример #7
0
 bool Content::loadEntities(Game& game, World& world) {
     std::ifstream entityList("assets/data/entityList.json");
     if(entityList.fail()) {
         std::cout << "Failed to load game content\n";
         return false;
     }
     std::stringstream fileEntityList;
     fileEntityList << entityList.rdbuf();
     std::string stringEntityList = fileEntityList.str();
     entityList.close();
     rapidjson::Document documentEntityList;
     if(documentEntityList.Parse<0>(stringEntityList.c_str()).HasParseError()) {
         std::cout << documentEntityList.Parse<0>(stringEntityList.c_str()).GetParseError() << std::endl;
         std::cout << "Failed to parse entity list\n";
         return false;
     }
     const rapidjson::Value& entities = documentEntityList["entities"];
     for(rapidjson::SizeType i = 0; i < entities.Size(); i++) {
         if(entities[i]["type"].GetInt() == 0) {
             Object* object;
             std::string sScript, sTable;
             object = new Object(game, world, entities[i], sScript, sTable);
             if(sScript != "0" && !m_objectUpdateFuncs[object->getId()]) {
                 using namespace luabridge;
                 m_objectUpdateFuncs[object->getId()] = std::shared_ptr<LuaRef>();
                 if(luaL_dofile(L, sScript.c_str()) == 0) {
                     LuaRef table = getGlobal(L, sTable.c_str());
                     if(table.isTable()) {
                         if(table["update"].isFunction()) {
                             m_objectUpdateFuncs[object->getId()] =
                                 std::make_shared<LuaRef>(table["update"]);
                         }
                     }
                 } else {
                     std::cout << "Error, can't open script!" << std::endl;
                 }
             }
             object->setUpdate(m_objectUpdateFuncs[object->getId()]);
             m_objectList[object->getId()] = object;
         } else if(entities[i]["type"].GetInt() == 1) {
             ItemRenderable* itemR;
             itemR = new ItemRenderable(game, world, entities[i]);
             m_itemRenderableList[itemR->getId()] = itemR;
         }
     }
     return true;
 }
Пример #8
0
QString Camera::queryProp(int reg)
{
    std::stringstream command;
    command << "return get_prop(" << reg << ")";

    LuaRef lcon = getLuaRefConnection();

    // Get reference to method "lcon.execwait"
    LuaRef execWait = lcon.get<LuaRef>("execwait");
    qDebug() << "execWait: " << execWait.typeName();

    usleep(30000);

    LuaRef result = execWait.call<LuaRef>(lcon, command.str());

    return QString("%1").arg(result.toValue<int>());
}
Пример #9
0
 virtual void SomeMember()
 {
     if( overide.isFunction() )
         overide();
     else
     {
         cout << "Overide is not a function" << endl;
     }
 }
Пример #10
0
bool ScriptSystem::GetComponents(GameObject* pObj, Components* pComp)
{
	pComp->pScript = Component<ScriptComponent>::GetComponent(pObj);
	if(pComp->pScript != NULL)
	{
		LuaRef& luaRef = (*pComp->pScript->pLuaRef);
		LuaRef init = luaRef["GetComponents"];
		LuaRef run = luaRef["Run"];

		if(init.isFunction() && run.isFunction())
		{
			bool bOk = init((*pComp->pScript->pLuaRef));
			return bOk;
		}
	}
	
	return false;
}
	static void _signal_trampoline(PropertyMap &map, const std::string &k, LuaRef ref, lua_State *l) {
		ref.PushCopyToStack();
		lua_pushlstring(l, k.c_str(), k.size());
		map.PushLuaTable();
		lua_pushvalue(l, -2);
		lua_rawget(l, -2);
		lua_remove(l, -2);
		pi_lua_protected_call(l, 2, 0);
	}
Пример #12
0
void DialogueLoader::loadDialogue() {
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);
	getGlobalNamespace(L)
		.beginClass<DialogueLoader>("Dialogue")
		.addFunction("isNPCState", &DialogueLoader::isNPCState)
		.addFunction("isQuestState", &DialogueLoader::isQuestState)
		.addFunction("isQuestComplete", &DialogueLoader::isQuestComplete)
		.addFunction("createCendricNode", &DialogueLoader::createCendricNode)
		.addFunction("createNPCNode", &DialogueLoader::createNPCNode)
		.addFunction("createChoiceNode", &DialogueLoader::createChoiceNode)
		.addFunction("createTradeNode", &DialogueLoader::createTradeNode)
		.addFunction("addChoice", &DialogueLoader::addChoice)
		.addFunction("changeNPCState", &DialogueLoader::changeNPCState)
		.addFunction("changeQuestState", &DialogueLoader::changeQuestState)
		.addFunction("addQuestProgress", &DialogueLoader::addQuestProgress)
		.addFunction("addItem", &DialogueLoader::addItem)
		.addFunction("removeItem", &DialogueLoader::removeItem)
		.addFunction("addGold", &DialogueLoader::addGold)
		.addFunction("removeGold", &DialogueLoader::removeGold)
		.addFunction("setRoot", &DialogueLoader::setRoot)
		.addFunction("addNode", &DialogueLoader::addNode)
		.endClass();

	if (luaL_dofile(L, m_dialogue.getID().c_str()) != 0) {
		g_logger->logError("DialogeLoader", "Cannot read lua script: " + m_dialogue.getID());
		return;
	}

	LuaRef function = getGlobal(L, "loadDialogue");
	if (!function.isFunction()) {
		g_logger->logError("DialogeLoader", "Lua script: " + m_dialogue.getID() + " has no loadDialogue function.");
		return;
	}

	try {
		function(this);
	}
	catch (LuaException const& e) {
		g_logger->logError("DialogeLoader", "LuaException: " + std::string(e.what()));
	}
}
Пример #13
0
bool LuaRef::operator==(const LuaRef & ref) const {
	if (ref.m_lua != m_lua)
		return false;
	if (ref.m_id == m_id)
		return true;

	ref.PushCopyToStack();
	PushCopyToStack();
	bool return_value = lua_compare(m_lua, -1, -2, LUA_OPEQ);
	lua_pop(m_lua, 2);
	return return_value;
}
Пример #14
0
void Character::loadScript(luabridge::lua_State* L, const std::string& scriptFilename, const std::string& tableName) {
    using namespace luabridge;
    if (luaL_dofile(L, scriptFilename.c_str()) == 0) {
        LuaRef table = getGlobal(L, tableName.c_str());
        if (table.isTable()) {
            if (table["name"].isString()) {
                name = table["name"].cast<std::string>();
            } else {
                name = "Null";
            }

            if (table["interact"].isFunction()) {
                interactFunc = std::make_shared<LuaRef>(table["interact"]);
            } else {
                interactFunc.reset();
            }
        }
    } else {
       std::cout << "Error, can't open script!" << std::endl;
    }
}
Пример #15
0
	 bool LuaRef::operator==( const LuaRef& other ) const
	 {
		 if (this->L != other.L)
			 return false;

		this->pushSelf();
		other.pushSelf();
		int equal = lua_equal(L, -1, -2);
		lua_pop(L, 2);

		return equal==1;
	 }
Пример #16
0
LUA_INLINE CppBindModule CppBindModule::beginModule(const char* name)
{
    LuaRef ref = m_meta.rawget(name);
    if (ref != nullptr) return CppBindModule(ref);

    lua_State* L = state();
    std::string type_name = "module<" + getFullName(m_meta, name) + ">";
    LuaRef module = LuaRef::createTable(L);
    module.setMetaTable(module);

    module.rawset("__index", &CppBindModuleMetaMethod::index);
    module.rawset("__newindex", &CppBindModuleMetaMethod::newIndex);
    module.rawset("___getters", LuaRef::createTable(L));
    module.rawset("___setters", LuaRef::createTable(L));
    module.rawset("___type", type_name);
    module.rawset("___module", m_meta);
    m_meta.rawset(name, module);
    return CppBindModule(module);
}
Пример #17
0
QuestData QuestLoader::loadQuest(const std::string& questID) const
{
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);

	QuestData questData;
	questData.id = "";

	std::string filename = QUEST_FOLDER + questID + ".lua";

	if (luaL_dofile(L, filename.c_str()) != 0)
	{
		g_logger->logError("QuestLoader", "Cannot read lua script: " + filename);
		return questData;
	}

	lua_pcall(L, 0, 0, 0);

	LuaRef title = getGlobal(L, "title");
	LuaRef description = getGlobal(L, "description");
	if (!title.isString() || !description.isString())
	{
		g_logger->logError("QuestLoader", "Quest [" + filename + "] has no title or description tag or of wrong type.");
		return questData;
	}

	questData.title = title.cast<std::string>();
	questData.description = description.cast<std::string>();

	LuaRef targets = getGlobal(L, "targets");
	if (targets.isTable())
	{
		int i = 1; // in lua, the first element is 1, not 0. Like Eiffel haha.
		LuaRef element = targets[i];
		while (!element.isNil())
		{
			LuaRef name = element[1];
			LuaRef amount = element[2];
			if (!name.isString() || !amount.isNumber())
			{
				g_logger->logError("QuestLoader", "Quest [" + filename + "]: target table not resolved, no name or amount or of wrong type.");
				return questData;
			}
			questData.targets.insert({name.cast<std::string>(), amount.cast<int>()});
			i++;
			element = targets[i];
		}
	}

	LuaRef collectibles = getGlobal(L, "collectibles");
	if (collectibles.isTable())
	{
		int i = 1;
		LuaRef element = collectibles[i];
		while (!element.isNil())
		{
			LuaRef id = element[1];
			LuaRef amount = element[2];
			if (!id.isString() || !amount.isNumber())
			{
				g_logger->logError("QuestLoader", "Quest [" + filename + "]: collectibles table not resolved, no id or amount or of wrong type.");
				return questData;
			}
			questData.collectibles.insert({ id.cast<std::string>(), amount.cast<int>() });
			i++;
			element = collectibles[i];
		}
	}

	LuaRef conditions = getGlobal(L, "conditions");
	if (conditions.isTable())
	{
		int i = 1;
		LuaRef element = conditions[i];
		while (element.isString())
		{
			questData.conditions.insert(element.cast<std::string>());
			i++;
			element = targets[i];
		}
	}

	questData.id = questID;
	return questData;
}
Пример #18
0
void		Bot::queue(LuaRef action)
{
  if (!action.isNil() && action.isFunction())
    _queue.push_back(action);
}
Пример #19
0
LUA_INLINE bool CppBindClassBase::buildMetaTable(LuaRef& meta, LuaRef& parent, const char* name,
    void* static_id, void* clazz_id, void* const_id)
{
    LuaRef ref = parent.rawget<LuaRef>(name);
    if (ref != nullptr) {
        meta = ref;
        return false;
    }

    auto L = parent.state();
    std::string type_name = "class<" + CppBindModule::getFullName(parent, name) + ">";

    LuaRef type_const = LuaRef::fromPointer(L, const_id);
    LuaRef type_clazz = LuaRef::fromPointer(L, clazz_id);
    LuaRef type_static = LuaRef::fromPointer(L, static_id);

    LuaRef clazz_const = LuaRef::createTable(L);
    clazz_const.setMetaTable(clazz_const);
    clazz_const.rawset("__index", &CppBindClassMetaMethod::index);
    clazz_const.rawset("__newindex", &CppBindClassMetaMethod::newIndex);
    clazz_const.rawset("___getters", LuaRef::createTable(L));
    clazz_const.rawset("___setters", LuaRef::createTable(L));
    clazz_const.rawset("___type", "const_" + type_name);
    clazz_const.rawset("___const", clazz_const);
    clazz_const.rawset(CppBindClassMetaMethod::signature(), type_const);

    LuaRef clazz = LuaRef::createTable(L);
    clazz.setMetaTable(clazz);
    clazz.rawset("__index", &CppBindClassMetaMethod::index);
    clazz.rawset("__newindex", &CppBindClassMetaMethod::newIndex);
    clazz.rawset("___getters", clazz_const.rawget<LuaRef>("___getters"));
    clazz.rawset("___setters", LuaRef::createTable(L));
    clazz.rawset("___type", type_name);
    clazz.rawset("___const", clazz_const);
    clazz.rawset(CppBindClassMetaMethod::signature(), type_clazz);

    LuaRef clazz_static = LuaRef::createTable(L);
    clazz_static.setMetaTable(clazz_static);
    clazz_static.rawset("__index", &CppBindClassMetaMethod::index);
    clazz_static.rawset("__newindex", &CppBindClassMetaMethod::newIndex);
    clazz_static.rawset("___getters", LuaRef::createTable(L));
    clazz_static.rawset("___setters", LuaRef::createTable(L));
    clazz_static.rawset("___type", "static_" + type_name);
    clazz_static.rawset("___class", clazz);
    clazz_static.rawset("___const", clazz_const);
    clazz_static.rawset("___parent", parent);
    clazz_static.rawset(CppBindClassMetaMethod::signature(), type_static);

    LuaRef registry(L, LUA_REGISTRYINDEX);
    registry.rawset(type_clazz, clazz);
    registry.rawset(type_const, clazz_const);
    registry.rawset(type_static, clazz_static);
    parent.rawset(name, clazz_static);

    meta = clazz_static;
    return true;
}
Пример #20
0
MerchantData MerchantLoader::loadMerchant(const std::string& merchantID) const
{
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);

	MerchantData merchantData;

	std::string filename = MERCHANT_FOLDER + "ME_" + merchantID + ".lua";

	if (luaL_dofile(L, filename.c_str()) != 0)
	{
		g_logger->logError("MerchantLoader", "Cannot read lua script: " + filename);
		return merchantData;
	}

	lua_pcall(L, 0, 0, 0);

	LuaRef multiplier = getGlobal(L, "multiplier");
	if (multiplier.isNumber())
	{
		float mult = multiplier.cast<float>();
		if (mult < 1.f)
		{
			g_logger->logWarning("MerchantLoader", "Merchant multiplier is smaller than 1, this is not allowed, the default (1.5f) is taken instead.");
		}
		else
		{
			merchantData.multiplier = mult;
		}
	}

	LuaRef fraction = getGlobal(L, "fraction");
	if (fraction.isString())
	{
		merchantData.fraction = resolveFractionID(fraction.cast<std::string>());
	}

	LuaRef wares = getGlobal(L, "wares");
	if (wares.isTable())
	{
		int i = 1; // in lua, the first element is 1, not 0. Like Eiffel haha.
		LuaRef element = wares[i];
		while (!element.isNil())
		{
			LuaRef name = element[1];
			LuaRef amount = element[2];
			if (!name.isString() || !amount.isNumber())
			{
				g_logger->logError("MerchantLoader", "File [" + filename + "]: wares table not resolved, no name or amount or of wrong type.");
				return merchantData;
			}
			merchantData.wares.insert({ name.cast<std::string>(), amount.cast<int>() });
			i++;
			element = wares[i];
		}
	}

	return merchantData;
}
Пример #21
0
CutsceneData CutsceneLoader::loadCutscene(const std::string& cutsceneID) {
	lua_State* L = luaL_newstate();
	luaL_openlibs(L);

	CutsceneData cutsceneData;
	cutsceneData.id = "";

	std::string foldername = CUTSCENE_FOLDER + cutsceneID + "/";
	std::string filename = foldername + cutsceneID + ".lua";

	if (luaL_dofile(L, filename.c_str()) != 0) {
		g_logger->logError("CutsceneLoader", "Cannot read lua script: " + filename);
		return cutsceneData;
	}

	lua_pcall(L, 0, 0, 0);

	LuaRef steps = getGlobal(L, "steps");
	if (steps.isTable()) {
		int i = 1; // in lua, the first element is 1, not 0. Like Eiffel haha.
		LuaRef step = steps[i];
		while (!step.isNil()) {
			LuaRef texts = step[1];
			LuaRef images = step[2];
			if (!texts.isTable() || !images.isTable()) {
				g_logger->logError("CutsceneLoader", "Cutscene [" + filename + "]: step table not resolved, there must be one table for texts and one for images.");
				return cutsceneData;
			}

			CutsceneStep cutsceneStep;

			// resolve texts
			int j = 1;
			LuaRef text = texts[j];
			while (!text.isNil()) {
				LuaRef textString = text[1];
				LuaRef textTime = text[2];

				if (!textString.isString() || !textTime.isNumber()) {
					g_logger->logError("CutsceneLoader", "Cutscene [" + filename + "]: text table not resolved, text string must be of type string and text time of type number.");
					return cutsceneData;
				}

				CutsceneText cutsceneText;
				cutsceneText.text = textString.cast<std::string>();
				cutsceneText.time = sf::seconds(static_cast<float>(textTime.cast<int>()));

				cutsceneStep.texts.push_back(cutsceneText);

				j++;
				text = texts[j];
			}

			// resolve images
			j = 1;
			LuaRef image = images[j];
			while (!image.isNil()) {
				LuaRef imagePath = image[1];
				LuaRef velocity = image[2];
				LuaRef angle = image[3];

				if (!imagePath.isString() || !velocity.isNumber() || !angle.isNumber()) {
					g_logger->logError("CutsceneLoader", "Cutscene [" + filename + "]: image table not resolved, image path must be of type string and velocity and angle of type number.");
					return cutsceneData;
				}

				float phi = degToRad(static_cast<float>(angle.cast<int>() - 90));
				float speed = static_cast<float>(velocity.cast<int>());

				CutsceneImage cutsceneImage;
				cutsceneImage.imagePath = foldername + imagePath.cast<std::string>();
				cutsceneImage.velocity.x = std::round(speed * std::cos(phi));
				cutsceneImage.velocity.y = std::round(speed * std::sin(phi));

				cutsceneStep.images.push_back(cutsceneImage);

				j++;
				image = images[j];
			}

			cutsceneData.steps.push_back(cutsceneStep);
			i++;
			step = steps[i];
		}
	}

	cutsceneData.id = cutsceneID;
	return cutsceneData;
}