int LuaScript::Loader(lua_State* L) { // Get module name String fileName(luaL_checkstring(L, 1)); #ifdef URHO3D_LUA_RAW_SCRIPT_LOADER // First attempt to load lua script file from the file system // Attempt to load .luc file first, then fall back to .lua LuaScript* lua = ::GetContext(L)->GetSubsystem<LuaScript>(); if (lua->LoadRawFile(fileName + ".luc") || lua->LoadRawFile(fileName + ".lua")) return 1; #endif ResourceCache* cache = ::GetContext(L)->GetSubsystem<ResourceCache>(); // Attempt to get .luc file first LuaFile* lucFile = cache->GetResource<LuaFile>(fileName + ".luc", false); if (lucFile) return lucFile->LoadChunk(L) ? 1 : 0; // Then try to get .lua file. If this also fails, error is logged and // resource not found event is sent LuaFile* luaFile = cache->GetResource<LuaFile>(fileName + ".lua"); if (luaFile) return luaFile->LoadChunk(L) ? 1 : 0; return 0; }
IOBanSQL::IOBanSQL() { m_host = g_config.getGlobalString("sql_host"); m_user = g_config.getGlobalString("sql_user"); m_pass = g_config.getGlobalString("sql_pass"); m_db = g_config.getGlobalString("sql_db"); }
void LoadScriptState::End() { #ifdef URHO3D_ANGELSCRIPT if (scriptFile_) { // Execute the optional stop function if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); } #else if (false) { } #endif #ifdef URHO3D_LUA else { LuaScript* luaScript = GetSubsystem<LuaScript>(); if (luaScript && luaScript->GetFunction("Stop", true)) luaScript->ExecuteFunction("Stop"); } #endif scriptFile_.Reset(); GetSubsystem<ResourceCache>()->ReleaseResource(ScriptFile::GetTypeStatic(), project_->mainScript_); project_ = NULL; AppState::End(); }
std::string Player::getDescription(bool self) const { std::stringstream s; std::string str; if(self){ s << "You see yourself."; if(voc > 0) s << " You are " << g_config.getGlobalStringField("vocations", voc) << "."; } else { s << "You see " << name << " (Level " << level <<")."; if(voc > 0){ if(sex != 0) s << " He"; else s << " She"; s << " is "<< g_config.getGlobalStringField("vocations", voc) << "."; } } str = s.str(); return str; }
void AnimatedModel::loadAnimation(LuaScript & script) { std::vector<std::string> animation_list = script.getTableNames("object.model.animation"); for (std::string name : animation_list) { Animation animation; animation.texture_names = script.getArray("object.model.animation." + name + ".states"); animation.period = script.get<int>("object.model.animation." + name + ".period"); animation_pack[name] = animation; } }
void Urho3DPlayer::Start() { String extension = GetExtension(scriptFileName_); if (extension != ".lua" && extension != ".luc") { #ifdef URHO3D_ANGELSCRIPT // Instantiate and register the AngelScript subsystem context_->RegisterSubsystem(new Script(context_)); // Hold a shared pointer to the script file to make sure it is not unloaded during runtime scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_); /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances #ifdef URHO3D_LUA if (scriptFileName_.Contains("Editor.as", false)) context_->RegisterSubsystem(new LuaScript(context_)); #endif // If script loading is successful, proceed to main loop if (scriptFile_ && scriptFile_->Execute("void Start()")) { // Subscribe to script's reload event to allow live-reload of the application SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted)); SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished)); SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed)); return; } #else ErrorExit("AngelScript is not enabled!"); return; #endif } else { #ifdef URHO3D_LUA // Instantiate and register the Lua script subsystem LuaScript* luaScript = new LuaScript(context_); context_->RegisterSubsystem(luaScript); // If script loading is successful, proceed to main loop if (luaScript->ExecuteFile(scriptFileName_)) { luaScript->ExecuteFunction("Start"); return; } #else ErrorExit("Lua is not enabled!"); return; #endif } // The script was not successfully loaded. Show the last error message and do not run the main loop ErrorExit(); }
/** * Called when the server has recovered the value of a quest variable. */ void LuaScript::getQuestCallback(Character *q, const std::string &name, const std::string &value, void *data) { LuaScript *s = static_cast< LuaScript * >(data); assert(s->nbArgs == -1); lua_getglobal(s->mState, "quest_reply"); lua_pushlightuserdata(s->mState, q); lua_pushstring(s->mState, name.c_str()); lua_pushstring(s->mState, value.c_str()); s->nbArgs = 3; s->execute(); }
Component* PrefabManager::ParseLuaScriptComponent(const tinyxml2::XMLElement* element) { using namespace tinyxml2; const char* scriptFile = element->Attribute("file"); UString scriptPath = UStringFromCharArray(scriptFile); LuaScript* script = LuaScriptManager::LoadScript(scriptPath); script->SetPath(scriptPath); return script; }
void FirstPersonLook::Rotation() { glm::vec2 mouseOffset = GetMouseOffset(); //if(abs(mouseOffset.x) > 200) mouseOffset.x = 0; //if(abs(mouseOffset.y) > 200) mouseOffset.y = 0; rotationX -= mouseOffset.x / 5; rotationY += mouseOffset.y / 5; if (rotationY > 89.0f) rotationY = 89.0f; if (rotationY < -89.0f) rotationY = -89.0f; glm::mat4 newTransform; newTransform = glm::translate(newTransform,_owner->getWorldPosition()); //newTransform[2] = glm::vec4(0,0,1,0);//debug newTransform *= glm::rotate( glm::radians(-rotationX), glm::vec3(0.0f, 1.0f, 0.0f)); newTransform *= glm::rotate( glm::radians(-rotationY), glm::vec3(1.0f, 0.0f, 0.0f)); _owner->setWorldTransform(newTransform); float reach = 10.0f; glm::vec3 origin = glm::vec3(newTransform[3]); glm::vec3 dir = glm::normalize(glm::vec3(newTransform[2])) * -1.0f; //RaycastInfo res; Ray ray(origin,dir); bool rayTestResult = CollisionManager::Raycast(ray,_storedRaycastInfo); if(rayTestResult && Input::GetKeyDown(Input::E) && _storedRaycastInfo.distance <= reach) { DualLinkNode<Component>* cn = _storedRaycastInfo.object->GetComponents().startNode; while(cn!=NULL) { LuaScript* script = dynamic_cast<LuaScript*>((Component*)cn); if(script!=NULL && script->IsActive()) script->InvokeFunction("OnInteract"); cn = cn->nextNode; } //std::cout<<"\n"<<res.object->GetComponent<Collider>()->quadTreeOwner->_depth; //std::cout<<"distance: "<<res.distance<<"\n"; } }
/** * Called when the server has recovered the post for a user */ void LuaScript::getPostCallback(Character *q, const std::string &sender, const std::string &letter, void *data) { // get the script LuaScript *s = static_cast<LuaScript*>(data); assert(s->nbArgs == -1); lua_getglobal(s->mState, "post_reply"); lua_pushlightuserdata(s->mState, q); lua_pushstring(s->mState, sender.c_str()); lua_pushstring(s->mState, letter.c_str()); s->nbArgs = 3; s->execute(); }
//! Creates a new script controller with a new node. inline LuaActorState(CoreEngine* engine, int ref) : engine_(engine) { LuaScript* script = static_cast<LuaScript*>(engine_->script()); lua_State* env = script->env(); lua_getref(env, ref); lua_unref(env, ref); self_ = luabind::object(luabind::from_stack(env, -1)); lua_pop(env, 1); assert(!lua_gettop(env)); }
void LuaScriptEventManager::RegisterEventTransformer(LuaScriptEventTransformation transformer, EventType type, LPCSTR name) { LuaScript* luas = (LuaScript*)chimera::g_pApp->GetScript(); LuaPlus::LuaObject table = luas->GetState()->GetGlobals().GetByName("EventType"); if(table.IsNil()) { table = luas->GetState()->GetGlobals().CreateTable("EventType"); } table.SetNumber(name, type); m_transformMap[type] = transformer; }
bool Summons::Load() { std::string file = g_config.getGlobalString("datadir") + "summons.xml"; xmlDocPtr doc; doc = xmlParseFile(file.c_str()); if (!doc) return false; xmlNodePtr root, summonNode; root = xmlDocGetRootElement(doc); if (xmlStrcmp(root->name, (const xmlChar*)"summons")) { xmlFreeDoc(doc); return false; } summonNode = root->children; while (summonNode) { if (strcmp((char*) summonNode->name, "summon") == 0) { std::string name = (const char*)xmlGetProp(summonNode, (const xmlChar *) "name"); int64_t reqMana = atoll((const char*)xmlGetProp(summonNode, (const xmlChar *) "mana")); std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))tolower); summons[name] = reqMana; } summonNode = summonNode->next; } xmlFreeDoc(doc); return true; }
void Urho::Stop() { if (scriptFile_) { // Execute the optional stop function if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); } #ifdef ENABLE_LUA else { LuaScript* luaScript = GetSubsystem<LuaScript>(); if (luaScript) luaScript->ExecuteFunction("Stop"); } #endif }
void Urho::Start() { #ifdef ENABLE_LUA String extension = GetExtension(scriptFileName_).ToLower(); if (extension != ".lua") { #endif // Instantiate and register the AngelScript subsystem context_->RegisterSubsystem(new Script(context_)); // Hold a shared pointer to the script file to make sure it is not unloaded during runtime scriptFile_ = context_->GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_); // If script loading is successful, proceed to main loop if (scriptFile_ && scriptFile_->Execute("void Start()")) { // Subscribe to script's reload event to allow live-reload of the application SubscribeToEvent(scriptFile_, E_RELOADSTARTED, HANDLER(Urho, HandleScriptReloadStarted)); SubscribeToEvent(scriptFile_, E_RELOADFINISHED, HANDLER(Urho, HandleScriptReloadFinished)); SubscribeToEvent(scriptFile_, E_RELOADFAILED, HANDLER(Urho, HandleScriptReloadFailed)); return; } #ifdef ENABLE_LUA } else { // Instantiate and register the Lua script subsystem context_->RegisterSubsystem(new LuaScript(context_)); LuaScript* luaScript = GetSubsystem<LuaScript>(); // If script loading is successful, proceed to main loop if (luaScript->ExecuteFile(scriptFileName_)) { luaScript->ExecuteFunction("Start"); return; } } #endif // The script was not successfully loaded. Show the last error message and do not run the main loop ErrorExit(); }
//------------------------------------------------------- void renderScene(LuaScript script, bool top){ //------------------------------------------------------- static short angle = 0; /*if(top) renderCube(angle); else renderPyramid(angle);*/ if(top) { script.getGlobal("renderTop"); if(script.isFunction( )) { script.call( ); } } else { script.getGlobal("renderBottom"); if(script.isFunction( )) { script.call( ); } } angle++; }
void Model::loadTexturePack(LuaScript & script) { std::vector<std::string> texture_pack_names = script.getTableNames("object.model.texture"); for (std::string name : texture_pack_names) { sf::IntRect geometry( script.get<int>("object.model.texture." + name + ".x"), script.get<int>("object.model.texture." + name + ".y"), script.get<int>("object.model.texture." + name + ".w"), script.get<int>("object.model.texture." + name + ".h") ); sf::Texture texture; texture.loadFromImage(image, geometry); texture_pack[name] = texture; } }
void Urho3DPlayer::Stop() { #ifdef URHO3D_ANGELSCRIPT if (scriptFile_) { // Execute the optional stop function if (scriptFile_->GetFunction("void Stop()")) scriptFile_->Execute("void Stop()"); } #else if (false) { } #endif #ifdef URHO3D_LUA else { LuaScript* luaScript = GetSubsystem<LuaScript>(); if (luaScript && luaScript->GetFunction("Stop", true)) luaScript->ExecuteFunction("Stop"); } #endif }
IOPlayer* IOPlayer::instance(){ if(!_instance){ #ifdef __USE_MYSQL__ if(g_config.getGlobalString("sourcedata") == "SQL") _instance = (IOPlayer*)new IOPlayerSQL; else // if(g_config.getGlobalString("sourcedata") == "XML") //fallback to xml #endif _instance = (IOPlayer*)new IOPlayerXML; } #ifdef __DEBUG__ printf("%s \n", _instance->getSourceDescription()); #endif return _instance; }
// main - Entry point for the sync compiler. // int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); // Enable debug stream buffering. EnableDebugBuffering = true; LLVMContext &Context = getGlobalContext(); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. // Initialize target first, so that --version shows registered targets. LLVMInitializeVerilogBackendTarget(); LLVMInitializeVerilogBackendTargetInfo(); LLVMInitializeVerilogBackendTargetMC(); cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n"); SMDiagnostic Err; LuaScript *S = &scriptEngin(); S->init(); // Run the lua script. if (!S->runScriptFile(InputFilename, Err)){ Err.print(argv[0], errs()); return 1; } S->updateStatus(); // Load the module to be compiled... std::auto_ptr<Module> M; M.reset(ParseIRFile(S->getValue<std::string>("InputFile"), Err, Context)); if (M.get() == 0) { Err.print(argv[0], errs()); return 1; } Module &mod = *M.get(); // TODO: Build the right triple. Triple TheTriple(mod.getTargetTriple()); TargetOptions TO; std::auto_ptr<TargetMachine> target(TheVBackendTarget.createTargetMachine(TheTriple.getTriple(), "", S->getDataLayout(), TO)); // Build up all of the passes that we want to do to the module. PassManagerBuilder Builder; Builder.DisableUnrollLoops = true; Builder.LibraryInfo = new TargetLibraryInfo(); Builder.LibraryInfo->disableAllFunctions(); Builder.OptLevel = 3; Builder.SizeLevel = 2; Builder.DisableSimplifyLibCalls = true; Builder.Inliner = createHLSInlinerPass(); Builder.addExtension(PassManagerBuilder::EP_LoopOptimizerEnd, LoopOptimizerEndExtensionFn); PassManager Passes; Passes.add(new TargetData(*target->getTargetData())); // Add the immutable target-specific alias analysis ahead of all others AAs. Passes.add(createVAliasAnalysisPass(target->getIntrinsicInfo())); Passes.add(createVerifierPass()); // This is the final bitcode, internalize it to expose more optimization // opportunities. Note that we should internalize it before SW/HW partition, // otherwise we may lost some information that help the later internalize. Passes.add(createInternalizePass(true)); // Perform Software/Hardware partition. Passes.add(createFunctionFilterPass(S->getOutputStream("SoftwareIROutput"))); Passes.add(createGlobalDCEPass()); // Optimize the hardware part. //Builder.populateFunctionPassManager(*FPasses); Builder.populateModulePassManager(Passes); Builder.populateLTOPassManager(Passes, /*Internalize*/true, /*RunInliner*/true); //PM.add(createPrintModulePass(&dbgs())); // We do not use the stream that passing into addPassesToEmitFile. formatted_raw_ostream formatted_nulls(nulls()); // Ask the target to add backend passes as necessary. target->addPassesToEmitFile(Passes, formatted_nulls, TargetMachine::CGFT_Null, false/*NoVerify*/); // Analyse the slack between registers. Passes.add(createCombPathDelayAnalysisPass()); Passes.add(createVerilogASTWriterPass(S->getOutputStream("RTLOutput"))); // Run some scripting passes. for (LuaScript::scriptpass_it I = S->passes_begin(), E = S->passes_end(); I != E; ++I) { const luabind::object &o = *I; Pass *P = createScriptingPass( luabind::object_cast<std::string>(I.key()).c_str(), luabind::object_cast<std::string>(o["FunctionScript"]).c_str(), luabind::object_cast<std::string>(o["GlobalScript"]).c_str()); Passes.add(P); } // Run the passes. Passes.run(mod); // If no error occur, keep the files. S->keepAllFiles(); return 0; }
int main(int argc, char * argv[]) { bool ret; /// Tell it our application path LuaPath lp = LuaPath::instance(argv[0]); /// Process command line args bool stubConsole = false; std::vector<std::string> args; for (int i = 1; i < argc; ++i) { std::string arg(argv[i]); if (arg == "--stub") { stubConsole = true; } else { args.push_back(arg); } } /// Create the script object LuaScript script; /// Create the "arg" table luabind::object arg = luabind::newtable(script.getLuaRawState()); arg[0] = std::string(argv[0]); for (unsigned int i = 0; i < args.size(); ++i) { arg[i + 1] = args[i]; } luabind::globals(script.getLuaRawState())["arg"] = arg; /// Create the console GUI boost::shared_ptr<LuaConsole> console; if (stubConsole) { std::cout << "Creating stub console, as requested..." << std::endl; boost::shared_ptr<LuaConsole> temp(new StubConsole(script)); console = temp; } else { QTConsole::setup(argc, argv); boost::shared_ptr<LuaConsole> temp(new QTConsole(script)); console = temp; } console->setTitle("Scenegraph Navigation Testbed"); #ifdef BUILD_WITHOUT_TERMINAL console->captureStdOut(); console->captureStdErr(); #endif /// Load the startup script ret = script.requireModule("osgnav-testbed"); if (!ret) { std::cout << "Could not load osgnav-testbed module!" << std::endl; #ifdef BUILD_WITHOUT_TERMINAL console->appendToDisplay("-- ERROR: Could not load osgnav-testbed module: see View->Show debug log for potential clues."); console->appendToDisplay("-- Application will not function properly - exit when finished viewing log."); console->disableAction(); console->threadLoop(); #endif return 1; } console->getRunBufFromLuaGlobal(); assert(console->isValid()); /// Run it all vrj::Kernel::instance()->start(); ret = console->threadLoop(); if (vrj::Kernel::instance()->isRunning()) { vrj::Kernel::instance()->stop(); } vrj::Kernel::instance()->waitForKernelStop(); return ret ? 0 : 1; }
bool SpawnManager::loadSpawnsSQL(std::string identifier) { std::string host = g_config.getGlobalString("map_host"); std::string user = g_config.getGlobalString("map_user"); std::string pass = g_config.getGlobalString("map_pass"); std::string db = g_config.getGlobalString("map_db"); #ifdef __DEBUG__ std::cout "host" << host << "user" << user << "pass" << pass << "db" << db << std::endl; #endif mysqlpp::Connection con; try{ con.connect(db.c_str(), host.c_str(), user.c_str(), pass.c_str()); } catch(mysqlpp::BadQuery e){ std::cout << "MYSQL-ERROR: " << e.error << std::endl; return false; } mysqlpp::Result res; //Monsters //Try & Find the Monter's try{ mysqlpp::Query query = con.query(); query << "SELECT * FROM " << identifier << "_monsters WHERE name !=''"; #ifdef __DEBUG__ std::cout << query.preview() << std::endl; #endif res = query.store(); } //End Try catch(mysqlpp::BadQuery e){ std::cout << "MYSQL-ERROR: " << e.error << std::endl; return false; } std::cout << ":: Found: " << res.size() << " Monsters(s)/Spawn(s)" << std::endl; if(res.size() < 1){//No Monsters std::cout << "No Monsters found" << std::endl; return false; } //if there are any monster spawns to load else{ //Load Monsters try{ mysqlpp::Result Monster; mysqlpp::Query query = con.query(); for(int i=1; i <= res.size(); ++i){ query.reset(); query << "SELECT * FROM " << identifier << "_monsters WHERE id = '" << i <<"' and id != ''"; Monster = query.store(); mysqlpp::Row row = *Monster.begin(); //Get the Monster's Position on Map std::string pos = std::string(row.lookup_by_name("spawnpos")); boost::char_separator<char> sep(";"); tokenizer spawnpostokens(pos, sep); tokenizer::iterator spawnposit = spawnpostokens.begin(); Position spawnpos; spawnpos.x=atoi(spawnposit->c_str()); spawnposit++; spawnpos.y=atoi(spawnposit->c_str()); spawnposit++; spawnpos.z=atoi(spawnposit->c_str()); std::string name; if(std::string(row.lookup_by_name("name")) != ""){name = std::string(row.lookup_by_name("name"));} int time = row.lookup_by_name("time"); Spawn *spawn = new Spawn(game, spawnpos, 1); spawns.push_back(spawn); spawn->addMonster(name, NORTH, 0, 0, time * 1000); }//End For Loop }//End Try catch(mysqlpp::BadQuery e){ std::cout << "MYSQL-ERROR: " << e.error << std::endl; return false; }//End Catch } //NPC's //Try & Find the NPC's try{ mysqlpp::Query query = con.query(); query << "SELECT * FROM " << identifier << "_npcs WHERE name !=''"; #ifdef __DEBUG__ std::cout << query.preview() << std::endl; #endif res = query.store(); }//End Try catch(mysqlpp::BadQuery e){ std::cout << "MYSQL-ERROR: " << e.error << std::endl; return false; } std::cout << ":: Found: " << res.size() << " NPC(s)" << std::endl; if(res.size() < 1){//No NPC's std::cout << "No NPC's found" << std::endl; return false; } //if there are any NPC's to load else{ //Load Monsters try{ mysqlpp::Result Monster; mysqlpp::Query query = con.query(); for(int i=1; i <= res.size(); ++i){ query.reset(); query << "SELECT * FROM " << identifier << "_npcs WHERE id = '" << i <<"' and id != ''"; Monster = query.store(); mysqlpp::Row row = *Monster.begin(); //Get the NPC's Position on Map std::string pos = std::string(row.lookup_by_name("pos")); boost::char_separator<char> sep(";"); tokenizer postokens(pos, sep); tokenizer::iterator posit = postokens.begin(); Position npcpos; npcpos.x=atoi(posit->c_str()); posit++; npcpos.y=atoi(posit->c_str()); posit++; npcpos.z=atoi(posit->c_str()); std::string name; if(std::string(row.lookup_by_name("name")) != ""){name = std::string(row.lookup_by_name("name"));} int dir = row.lookup_by_name("dir"); Npc* npc = new Npc(name, game); npc->pos = npcpos; switch(dir){ case 1: npc->direction=(NORTH); break; case 2: npc->direction=(SOUTH); break; case 3: npc->direction=(WEST); break; case 4: npc->direction=(EAST); break; default: // std::cout << "Invalid direction for " << name << " " <<x<<" "<<y<<" "<<z<<"."; return false; break; } if(!game->placeCreature(npc->pos, npc)){ delete npc; } }//End For Loop return true; }//End Try catch(mysqlpp::BadQuery e){ std::cout << "MYSQL-ERROR: " << e.error << std::endl; return false; }//End Catch } return true; }
int main(int argc, char *argv[]) { linkApplicationQt(); ImplementationFactoryManager::use("Qt",true); char mydirectory[MAX_PATH] = {""}; GetCurrentDirectory(MAX_PATH,mydirectory); //All the following should be able to be done in a tool or script ;) ApplicationGlobals::getInstance()->kWorkingPath = mydirectory; ApplicationGlobals::getInstance()->kWorkingPath += "\\"; ApplicationGlobals::getInstance()->kIconPath = mydirectory; ApplicationGlobals::getInstance()->kIconPath += "\\..\\..\\Icons\\"; ApplicationController appController; MainController mainController; appController.addSubController(&mainController); MenuController menu1; menu1.setTitle("MenuTest"); menu1.setIconPath("MenuTest.png"); mainController.addSubController(&menu1); ActionController action1; action1.setTitle("ActionTest"); action1.setIconPath("ActionTest.png"); //action1.setVisible(false); menu1.addSubController(&action1); MenuController submenu1; submenu1.setTitle("SubMenuTest"); submenu1.setIconPath("SubMenuTest.png"); menu1.addSubController(&submenu1); ActionController action2; action2.setTitle("ActionTest2"); action2.setIconPath("ActionTest2.png"); action2.setEnabled(false); submenu1.addSubController(&action2); ToolbarController toolbar1; toolbar1.addSubController(&action1); toolbar1.addSubController(&action2); mainController.addSubController(&toolbar1); SplitterController baseSplit; SplitterController split1; split1.setName("hallo"); SplitterController split2; split2.setName("cool"); TabController tab; tab.addSubController(&split1); tab.addSubController(&split2); SourceCodeController sourceCode; sourceCode.setName("Source Code"); TabController tab2; tab2.addSubController(&sourceCode); baseSplit.addSubController(&tab); baseSplit.addSubController(&tab2); mainController.addSubController(&baseSplit); MenuController popupMenu1; popupMenu1.setTitle("popupMenu1"); popupMenu1.setIconPath("MenuTest.png"); ActionController popuaction2; popuaction2.setTitle("Launch Sample"); popuaction2.setIconPath("ActionTest2.png"); popupMenu1.addSubController(&popuaction2); popupMenu1.popup(); //Create script and assign it to sourceCode std::string testScriptPath = mydirectory; testScriptPath += "\\..\\..\\test.lua"; LuaScript s; s.load(testScriptPath); ProxyList objs; objs.push_back(ProxyBase(&s)); sourceCode.set(objs); //Run the application appController.run(); //Load From Depot //if no applicationController found, }
SynchronizedRunBuffer::SynchronizedRunBuffer(LuaScript const& script) : _init(false) { /// @todo own this state? How? _state = script.getLuaRawState(); }
void Spell::loadLua(LuaScript& script){ std::string scriptloc = "../../lua/champions/" + owner->getType() + "/" + getStringForSlot() + ".lua"; //lua/championname/(q/w/e/r), example: /lua/Ezreal/q, also for stuff like nidalee cougar they will have diff folders! printf("Spell script loc is: %s \n" , scriptloc.c_str()); script.lua.script("package.path = '../../lua/lib/?.lua;' .. package.path"); //automatically load vector lib so scripters dont have to worry about path script.lua.set_function("getOwnerX", [this]() { return owner->getX(); }); script.lua.set_function("getOwnerY", [this]() { return owner->getY(); }); script.lua.set_function("getSpellLevel", [this]() { return getLevel(); }); script.lua.set_function("getOwnerLevel", [this]() { return owner->getStats().getLevel(); }); script.lua.set_function("getChampionModel", [this]() { return owner->getModel(); }); script.lua.set_function("setChampionModel", [this](const std::string& newModel) { owner->setModel(newModel); return; }); script.lua.set_function("getSpellToX", [this]() { return x; }); script.lua.set_function("getSpellToY", [this]() { return y; }); script.lua.set_function("getRange", [this]() { return castRange; }); script.lua.set_function("teleportTo", [this](float _x, float _y) { // expose teleport to lua owner->getMap()->getGame()->notifyTeleport(owner, _x, _y); return; }); script.lua.set_function("isWalkable", [this](float _x, float _y) { return owner->getMap()->isWalkable(_x, _y); }); /*script.lua.set_function("addMovementSpeedBuff", [this](Unit* u, float amount, float duration) { // expose teleport to lua Buff* b = new Buff(duration); b->setMovementSpeedPercentModifier(amount); u->addBuff(b); u->getStats().addMovementSpeedPercentageModifier(b->getMovementSpeedPercentModifier()); return; });*/ script.lua.set_function("addBuff", [this](Buff b, Unit* u){ u->addBuff(new Buff(b)); return; }); script.lua.set_function("getEffectValue", [this](uint32 effectNo) { if(effectNo >= effects.size() || level >= effects[effectNo].size()) { return 0.f; } return effects[effectNo][level]; }); script.lua.set_function("getOwner", [this]() { return owner; }); script.lua.set_function("getSide", [this](Object* o) { return o->getSide(); }); script.lua.set_function("isDead", [this](Unit* u) { return u->isDead(); }); script.lua.set_function("getProjectileSpeed", [this]() { return projectileSpeed; }); script.lua.set_function("getCoefficient", [this]() { return coefficient; }); script.lua.set_function("addProjectile", [this](float toX, float toY) { Projectile* p = new Projectile(owner->getMap(), GetNewNetID(), owner->getX(), owner->getY(), 30, owner, new Target(toX, toY), this, projectileSpeed, RAFFile::getHash(spellName +"Missile"), projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); owner->getMap()->getGame()->notifyProjectileSpawn(p); return; }); script.lua.set_function("addProjectileCustom", [this](const std::string& name, float projSpeed, float toX, float toY) { Projectile* p = new Projectile(owner->getMap(), GetNewNetID(), owner->getX(), owner->getY(), 30, owner, new Target(toX, toY), this, projectileSpeed, RAFFile::getHash(name), projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); owner->getMap()->getGame()->notifyProjectileSpawn(p); return; }); /** * For spells that don't require SpawnProjectile, but for which we still need to track the projectile server-side */ script.lua.set_function("addServerProjectile", [this](float toX, float toY) { Projectile* p = new Projectile(owner->getMap(), futureProjNetId, owner->getX(), owner->getY(), 30, owner, new Target(toX, toY), this, projectileSpeed, 0, projectileFlags ? projectileFlags : flags); owner->getMap()->addObject(p); return; }); script.lua.set_function("addParticle", [this](const std::string& particle, float toX, float toY) { Target* t = new Target(toX, toY); owner->getMap()->getGame()->notifyParticleSpawn(owner, t, particle); delete t; return; }); script.lua.set_function("addParticleTarget", [this](const std::string& particle, Target* u) { owner->getMap()->getGame()->notifyParticleSpawn(owner, u, particle); return; }); script.lua.set_function("spellAnimation", [this](const std::string& animation, Unit* u) { owner->getMap()->getGame()->notifySpellAnimation(u, animation); return; }); // TODO: Set multiple animations script.lua.set_function("setAnimation", [this](const std::string& animation1, const std::string& animation2, Unit* u) { std::vector<std::pair<std::string, std::string>> animationPairs; animationPairs.push_back(std::make_pair(animation1, animation2)); owner->getMap()->getGame()->notifySetAnimation(u, animationPairs); return; }); script.lua.set_function("resetAnimations", [this](Unit* u) { std::vector<std::pair<std::string, std::string>> animationPairs; owner->getMap()->getGame()->notifySetAnimation(u, animationPairs); return; }); script.lua.set_function("dashTo", [this](Unit* u, float x, float y, float dashSpeed) { u->dashTo(x, y, dashSpeed); u->setUnitTarget(0); owner->getMap()->getGame()->notifyDash(u, x, y, dashSpeed); return; }); try{ script.loadScript(scriptloc); //todo: abstract class that loads a lua file for any lua }catch(sol::error e){//lua error? don't crash the whole server printf("Error in spell script:\n%s \n", e.what()); } }
bool Game::initialize(ENetAddress *address, const char *baseKey){ if (enet_initialize () != 0) return false; atexit(enet_deinitialize); _server = enet_host_create(address, 32, 0, 0); if(_server == NULL) return false; std::string key = base64_decode(baseKey); if(key.length() <= 0) return false; _blowfish = new BlowFish((uint8*)key.c_str(), 16); initHandlers(); map = new SummonersRift(this); //TODO: better lua implementation LuaScript script; script.loadScript("../../lua/config.lua"); // sol::state lua; // lua.open_libraries(sol::lib::base, sol::lib::table); // lua.open_file("../../lua/config.lua"); sol::table playerList = script.getTable("players"); for (int i=1;i<12;i++) { try { std::string playerIndex = "player"+toString(i); sol::table playerData = playerList.get<sol::table>(playerIndex); std::string rank = playerData.get<std::string>("rank"); std::string name = playerData.get<std::string>("name"); std::string champion = playerData.get<std::string>("champion"); std::string team = playerData.get<std::string>("team"); int skin = playerData.get<int>("skin"); int ribbon = playerData.get<int>("ribbon"); int icon = playerData.get<int>("icon"); std::string summoner1 = playerData.get<std::string>("summoner1"); std::string summoner2 = playerData.get<std::string>("summoner2"); ClientInfo* player = new ClientInfo(rank, ((team == "BLUE") ? TEAM_BLUE : TEAM_PURPLE), ribbon, icon); player->setName(name); Champion* c = ChampionFactory::getChampionFromType(champion, map, GetNewNetID()); c->setPosition(35.90f, 273.55f); c->setSide((team == "BLUE") ? 0 : 1); c->levelUp(); map->addObject(c); player->setSkinNo(skin); player->setChampion(c); static int id = 1; player->userId = id; // same as StartClient.bat id++; player->setSummoners(strToId(summoner1), strToId(summoner2)); players.push_back(player); } catch(sol::error e) { //printf("Error loading champion: \n%s", e.what()); break; } } // Uncomment the following to get 2-players /*ClientInfo* player2 = new ClientInfo("GOLD", TEAM_PURPLE); player2->setName("tseT"); Champion* c2 = ChampionFactory::getChampionFromType("Ezreal", map, GetNewNetID()); c2->setPosition(100.f, 273.55f); c2->setSide(1); map->addObject(c2); player2->setChampion(c2); player2->setSkinNo(4); player2->userId = 2; // same as StartClient.bat player2->setSummoners(SPL_Ignite, SPL_Flash); players.push_back(player2);*/ return _isAlive = true; }