content
stringlengths
5
1.05M
--Class for sprites. Should extend Object Enemy2 = { maxVelocityX = 100, weapon = {} } function Enemy2:new(X,Y) s = Enemy:new(X,Y) setmetatable(s, self) setmetatable(self, Enemy) self.__index = self s.aiStage = 1 s.health = 2 s.maxHealth = 2 s.score = 200 s.NUMROUTES = 1 s.attackPower = 1 --s.accelerationY = 200 s.y = General.screenH - 200 s.sfxHurt = love.audio.newSource(LevelManager:getSound("hurt_2")) return s end function Enemy2:setAnimations() self:addAnimation("idle_0", {1,2}, .1, true) self:addAnimation("fire_0", {3}, .5, false) self:addAnimation("idle_10", {4,5}, .1, true) self:addAnimation("fire_10", {6}, .5, false) self:addAnimation("idle_20", {7,8}, .1, true) self:addAnimation("fire_20", {9}, .5, false) self:addAnimation("idle_30", {10,11}, .1, true) self:addAnimation("fire_30", {12}, .5, false) self:addAnimation("idle_35", {13,14}, .1, true) self:addAnimation("fire_35", {15}, .5, false) end function Enemy2:respawn(SpawnX, SpawnY) if SpawnY == nil then Enemy.respawn(self, SpawnX, General.screenH-120) else Enemy.respawn(self, SpawnX, SpawnY) end end function Enemy2:doConfig() Enemy.doConfig(self) self:setCollisionBox(40, 48, 122, 65) self.dropRate = .7 --Create gun self.weapon = Emitter:new(0, 0) for j=1, 2 do --Create bullets local curBullet = Sprite:new(0, 0, LevelManager:getParticle("bullet-red")) curBullet.attackPower = 1 self.weapon:addParticle(curBullet) GameState.enemyBullets:add(curBullet) end self.weapon:setSpeed(300, 350) self.weapon:start(false, 10, 1, -1) self.weapon:setOffset(58) self.weapon:stop() self.weapon:lockParent(self, true, 51, -4) GameState.emitters:add(self.weapon) end function Enemy2:update() self.weapon:lockTarget(GameState.player, 0, GameState.player.velocityX/3) fireAngle = self.weapon:getAngle() fireAngle = fireAngle * 180 / math.pi fireAngle = 180 - fireAngle if self.aiStage == 1 then --Move to firing point if self:getScreenX() <= General.screenW - 200 then self:updateStage() Timer:new(8, self, Enemy.updateStage) self.weapon:restart() end if fireAngle < 10 then self:playAnimation("idle_0") elseif fireAngle < 20 then self:playAnimation("idle_10") elseif fireAngle < 30 then self:playAnimation("idle_20") elseif fireAngle < 35 then self:playAnimation("idle_30") elseif fireAngle < 90 then self:playAnimation("idle_35") else self:playAnimation("idle_0") end elseif self.aiStage == 2 then --self.weapon:setAngle(180 - weaponAngle, 0) self.x = General:getCamera().x + General.screenW - 200 if fireAngle < 10 then self:playAnimation("idle_0") elseif fireAngle < 20 then self:playAnimation("idle_10") elseif fireAngle < 30 then self:playAnimation("idle_20") elseif fireAngle < 35 then self:playAnimation("idle_30") elseif fireAngle < 90 then self:playAnimation("idle_35") else self:playAnimation("idle_0") end else s.velocityX = 10 self.weapon:stop() self:playAnimation("idle_0") end if self:getScreenX() + self.width < 0 then self:setExists(false) end Enemy.update(self) end function Enemy2:getType() return "Enemy2" end
ITEM.name = "Карта" ITEM.desc = "Карта окрестностей Майенны" ITEM.model = "models/maps.mdl" ITEM.category = "misc" ITEM.functions.View = { name = "Осмотреть", icon = "icon16/map.png", onClick = function(item) local frame = vgui.Create("DFrame") frame:SetSize(840, 850) frame:SetTitle(item.name) frame:MakePopup() frame:Center() frame.html = frame:Add("DHTML") frame.html:Dock(FILL) frame.html:SetHTML([[<html> <body style="background-color: #ECECEC; color: #282B2D; font-family: 'Book Antiqua', Palatino, 'Palatino Linotype', 'Palatino LT STD', Georgia, serif; font-size 16px; text-align: justify;"> <center> <img src="http://i82.fastpic.ru/big/2016/0924/2b/09bed63793b38d7cc5c91acc93eaaf2b.png"></img> </center> </body> </html>]]) end, onRun = function(item) item.player:EmitSound("hgn/crussaria/devices/parchment_open.wav") if !IsValid(item.entity) then item.player:emote("map") end return false end }
--[[ Author: LearningDave Date: december, 6th 2015. Steals mana from target ]] function StealManaBunshin( event ) if (event.ability:IsCooldownReady()) then if not event.target:IsBuilding() and event.target:GetMaxMana() > 0 and not event.target:IsMagicImmune() then -- Variables local caster = event.caster local ability = event.ability local target = event.target local manasteal_percentage = event.ability:GetLevelSpecialValueFor("manasteal_percentage", event.ability:GetLevel() - 1 ) local mana = target:GetMana() target:EmitSound("kisame_samehada_trigger") local reduce_mana_amount = target:GetMana() / 100 * manasteal_percentage local new_mana = mana - reduce_mana_amount target:SetMana(new_mana) local mana_for_kisame = reduce_mana_amount / 2 caster:GetOwner():SetMana(caster:GetOwner():GetMana() + mana_for_kisame) -- Fire particle local fxIndex = ParticleManager:CreateParticle( "particles/generic_gameplay/generic_manaburn.vpcf", PATTACH_CUSTOMORIGIN, target ) ParticleManager:SetParticleControl( fxIndex, 0, target:GetAbsOrigin() ) ParticleManager:SetParticleControlEnt( fxIndex, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), true ) event.ability:StartCooldown(event.ability:GetCooldown(event.ability:GetLevel() - 1)) end end end
local EQUIPMENT = script:FindAncestorByType("Equipment") EQUIPMENT.serverUserData.KillEvents = {} function ActivateRegen(player, damage) if(Object.IsValid(EQUIPMENT) ) then if(damage.sourcePlayer == EQUIPMENT.owner) and (player ~= EQUIPMENT.owner) then Events.Broadcast("ActivateRegen",EQUIPMENT.owner) end end end function AddPlayer(player) EQUIPMENT.serverUserData.KillEvents[player] = player.diedEvent:Connect(ActivateRegen) end function RemovePlayer(player) if Object.IsValid(EQUIPMENT) then local listener = EQUIPMENT.serverUserData.KillEvents[player] if listener and listener.isConnected then listener:Disconnect() end EQUIPMENT.serverUserData.KillEvents[player] = nil end end for _, player in pairs(Game.GetPlayers()) do AddPlayer(player) end function DestroyedEvent() for k,v in pairs(Game.GetPlayers()) do RemovePlayer(v) end for k,v in pairs(EQUIPMENT.serverUserData.Events) do v:Disconnect() end for k,v in pairs(EQUIPMENT.serverUserData.KillEvents) do v:Disconnect() end end EQUIPMENT.serverUserData.Events = { Game.playerJoinedEvent:Connect(AddPlayer), Game.playerLeftEvent:Connect(RemovePlayer), EQUIPMENT.destroyEvent:Connect(DestroyedEvent) }
-- String Util -- Stephen Leitnick -- December 3, 2019 --[[ StringUtil.Trim(String str) StringUtil.TrimStart(String str) StringUtil.TrimEnd(String str) StringUtil.EqualsIgnoreCase(String str, String compare) StringUtil.RemoveWhitespace(String str) StringUtil.RemoveExcessWhitespace(String str) StringUtil.EndsWith(String str, String endsWith) StringUtil.StartsWith(String str, String startsWith) StringUtil.Contains(String str, String contains) StringUtil.ToCharArray(String str) StringUtil.ToByteArray(String str) StringUtil.ByteArrayToString(Table bytes) StringUtil.ToCamelCase(String str) StringUtil.ToPascalCase(String str) StringUtil.ToSnakeCase(String str [, uppercase]) StringUtil.ToKebabCase(String str [, uppercase]) StringUtil.Escape(str) StringUtil.StringBuilder() EXAMPLES: Trim: Trims whitespace from the start and end of the string. StringUtil.Trim(" hello world ") == "hello world" TrimStart: The same as Trim, but only trims the start of the string. StringUtil.TrimStart(" hello world ") == "hello world " TrimEnd: The same as Trim, but only trims the end of the string. StringUtil.TrimEnd(" hello world ") == " hello world" EqualsIgnoreCase: Checks if two strings are equal, but ignores their case. StringUtil.EqualsIgnoreCase("HELLo woRLD", "hEllo wORLd") == true RemoveWhitespace: Removes all whitespace from a string. StringUtil.RemoveWhitespace(" hello World!\n") == "helloWorld!" RemoveExcessWhitespace: Replaces all whitespace with a single space. This does not trim the string. StringUtil.RemoveExcessWhitespace("This is a \n test") == "This is a test" EndsWith: Checks if a string ends with a certain string. StringUtil.EndsWith("Hello world", "rld") == true StartsWith: Checks if a string starts with a certain string. StringUtil.StartsWith("Hello world", "He") == true Contains: Checks if a string contains another string. StringUtil.Contains("Hello world", "lo wor") == true ToCharArray: Returns a table of all the characters in the string. StringUtil.ToCharArray("Hello") >>> {"H","e","l","l","o"} ToByteArray: Returns a table of all the bytes of each character in the string. StringUtil.ToByteArray("Hello") >>> {72,101,108,108,111} ByteArrayToString: Transforms an array of bytes into a string. StringUtil.ByteArrayToString({97, 98, 99}) == "abc" ToCamelCase: Returns a string in camelCase. StringUtil.ToCamelCase("Hello_world-abc") == "helloWorldAbc" ToPascalCase: Returns a string in PascalCase. StringUtil.ToPascalCase("Hello_world-abc") == "HelloWorldAbc" ToSnakeCase: Returns a string in snake_case or SNAKE_CASE. StringUtil.ToPascalCase("Hello_world-abc") == "hello_world_abc" StringUtil.ToPascalCase("Hello_world-abc", true) == "HELLO_WORLD_ABC" ToKebabCase: Returns a string in kebab-case or KEBAB-CASE. StringUtil.ToKebabCase("Hello_world-abc") == "hello-world-abc" StringUtil.ToKebabCase("Hello_world-abc", true) == "HELLO-WORLD-ABC" Escape: Escapes a string from pattern characters. In other words, it prefixes any special pattern characters with a %. For example, the dollar sign $ would become %$. See the example below. StringUtil.Escape("Hello. World$ ^-^") == "Hello%. World%$ %^%-%^" StringBuilder: Creates a StringBuilder object that can be used to build a string. This is useful when a large string needs to be concatenated. Traditional concatenation of a string using ".." can be a performance issue, and thus StringBuilders can be used to store the pieces of the string in a table and then concatenate them all at once. local builder = StringUtil.StringBuilder() builder:Append("world") builder:Prepend("Hello ") builder:ToString() == "Hello world" tostring(builder) == "Hello world" --]] local StringUtil = {} local MAX_TUPLE = 7997 function StringUtil.Escape(str) local escaped = str:gsub("([%.%$%^%(%)%[%]%+%-%*%?%%])", "%%%1") return escaped end function StringUtil.Trim(str) return str:match("^%s*(.-)%s*$") end function StringUtil.TrimStart(str) return str:match("^%s*(.+)") end function StringUtil.TrimEnd(str) return str:match("(.-)%s*$") end function StringUtil.RemoveExcessWhitespace(str) return str:gsub("%s+", " ") end function StringUtil.RemoveWhitespace(str) return str:gsub("%s+", "") end function StringUtil.EndsWith(str, ends) return str:match(StringUtil.Escape(ends) .. "$") ~= nil end function StringUtil.StartsWith(str, starts) return str:match("^" .. StringUtil.Escape(starts)) ~= nil end function StringUtil.Contains(str, contains) return str:find(contains) ~= nil end function StringUtil.StringBuilder() local sb = {} local str = {} function sb:Append(s) str[#str + 1] = s end function sb:Prepend(s) table.insert(str, 1, s) end function sb:ToString() return table.concat(str, "") end setmetatable(sb, {__tostring=sb.ToString}) return sb end function StringUtil.ToCharArray(str) local len = #str local chars = table.create(len) for i = 1,len do chars[i] = str:sub(i, i) end return chars end function StringUtil.ToByteArray(str) local len = #str if (len == 0) then return {} end if (len <= MAX_TUPLE) then return table.pack(str:byte(1, #str)) end local bytes = table.create(len) for i = 1,len do bytes[i] = str:sub(i, i):byte() end return bytes end function StringUtil.ByteArrayToString(bytes) local size = #bytes if (size <= MAX_TUPLE) then return string.char(table.unpack(bytes)) end local numChunks = math.ceil(size / MAX_TUPLE) local stringBuild = table.create(numChunks) for i = 1, numChunks do local chunk = string.char(table.unpack(bytes, ((i - 1) * MAX_TUPLE) + 1, math.min(size, ((i - 1) * MAX_TUPLE) + MAX_TUPLE))) stringBuild[i] = chunk end return table.concat(stringBuild, "") end function StringUtil.EqualsIgnoreCase(str1, str2) return (str1:lower() == str2:lower()) end function StringUtil.ToCamelCase(str) str = str:gsub("[%-_]+([^%-_])", function(s) return s:upper() end) return str:sub(1, 1):lower() .. str:sub(2) end function StringUtil.ToPascalCase(str) str = StringUtil.ToCamelCase(str) return str:sub(1, 1):upper() .. str:sub(2) end function StringUtil.ToSnakeCase(str, uppercase) str = str:gsub("[%-_]+", "_"):gsub("([^%u%-_])(%u)", function(s1, s2) return s1 .. "_" .. s2:lower() end) if (uppercase) then str = str:upper() else str = str:lower() end return str end function StringUtil.ToKebabCase(str, uppercase) str = str:gsub("[%-_]+", "-"):gsub("([^%u%-_])(%u)", function(s1, s2) return s1 .. "-" .. s2:lower() end) if (uppercase) then str = str:upper() else str = str:lower() end return str end setmetatable(StringUtil, {__index = string}) return StringUtil
kMarineInitialIndivRes = 20 kAlienInitialIndivRes = 15
-- Enable Lua module caching if available for a speed boost local ok, impatient = pcall(require, "impatient") if ok then impatient.enable_profile() else vim.notify("impatient.nvim not found. Lua module caching is disabled.", "warn") end -- Check if Nix is managing Vim packages. If not, load them with Packer. -- if not vim.env.NVIM_PBAR_PLUGINS then -- vim.notify("loading packer") -- require("config.packer") -- end -- Load configuration require("config.options") require("config.notify") require("config.theme") require("config.treesitter") require("config.lsp") require("config.dap") require("config.completion") require("config.telescope") require("config.editor") require("config.statusline") require("config.keybinds")
local Mef = require("api.Mef") local Chara = require("api.Chara") local Event = require("api.Event") local I18N = require("api.I18N") local Gui = require("api.Gui") local Input = require("api.Input") local Map = require("api.Map") local World = require("api.World") local Log = require("api.Log") local Env = require("api.Env") local IChara = require("api.chara.IChara") local draw = require("internal.draw") local field = require("game.field") local config = require("internal.config") local data = require("internal.data") local save = require("internal.global.save") local chara_make = require("game.chara_make") local Save = require("api.Save") local state = require("internal.global.field_logic_state") local fs = require("util.fs") local SaveFs = require("api.SaveFs") local Rand = require("api.Rand") local main_state = require("internal.global.main_state") local DeathMenu = require("api.gui.menu.DeathMenu") local field_logic = {} local dt = 0 function field_logic.setup_new_game(player, save_id) main_state.is_in_game = true field.map = nil local scenario = data["base.scenario"]:ensure(save.base.scenario) assert(class.is_an(IChara, player)) Chara.set_player(player) if save_id == nil then save_id = ("%s_%d"):format(player.name, os.time()) end save_id = fs.sanitize(save_id, "_") if string.len(save_id) == 0 then error("Save ID must be greater than 0 characters in length.") end local path = SaveFs.save_path("", "save", save_id) if fs.exists(path) then error(("Save '%s' already exists."):format(save_id)) end config.base._save_id = fs.sanitize(save_id) scenario:on_game_start(player) assert(Map.current(), "Scenario must set the current map") assert(player:current_map() == Map.current(), "Player must exist in current map") save.base.home_map_uid = save.base.home_map_uid or Map.current().uid assert(save.base.home_map_uid) Env.update_play_time() Event.trigger("base.on_new_game") -- >>>>>>>> shade2/economy.hsp:20 snd seSave:gosub *game_save .. Save.save_game() -- <<<<<<<< shade2/economy.hsp:20 snd seSave:gosub *game_save .. end function field_logic.quickstart() field:init_global_data() save.base.scenario = config.base.quickstart_scenario assert(config.base.quickstart_scenario) assert(save.base.scenario) -- We will want to act as if the character making GUI is active, because that -- will force the player's equipment to be generated uncursed, along with -- some other special behaviors (search for CharaMake.is_active()). chara_make.set_is_active_override(true) local ok, err = xpcall(function() local me = Chara.create(config.base.quickstart_chara_id, nil, nil, {no_build=true, ownerless=true}) me.gender = Rand.choice { "female", "male" } -- HACK: We have to apply race/class ourselves as the charamake process -- will assume the GUI will do so local Skill = require("mod.elona_sys.api.Skill") Skill.apply_race_params(me, me.race) Skill.apply_class_params(me, me.class) me:emit("base.on_finalize_player") me:emit("base.on_initialize_player") me:build() return me end, debug.traceback) chara_make.set_is_active_override(false) if not ok then error(err) end local save_id = "quickstart" local path = SaveFs.save_path("", "save", save_id) if fs.exists(path) then fs.remove(path) end local me = err field_logic.setup_new_game(me, save_id) Gui.mes("Quickstarted game.") end function field_logic.setup() -- This function gets called again if field_logic.query() throws an -- error, so don't rerun base.on_game_initialize. if not field.repl then field:setup_repl() end if not main_state.is_in_game then Event.trigger("base.on_game_initialize") end end function field_logic.update_chara_time_this_turn(time_this_turn) for _, chara in Chara.iter() do -- Ensure all characters (including the player) have a -- turn cost at least as much as the player's starting -- turn cost, since the player always goes first at the -- beginning of a turn. chara.time_this_turn = chara.time_this_turn + chara:emit("base.on_calc_speed") * time_this_turn end end local function update_mefs(map) for _, mef in Mef.iter(map) do mef:step_turn() end end function field_logic.turn_begin() local turn_result = Event.trigger("base.on_turn_begin", {}, nil) if turn_result then -- return turn_result end update_mefs(field.map) local player = Chara.player() if not Chara.is_alive(player) then -- NOTE: should be an internal event, separate from ones that -- event callbacks may return. return "player_died", player end if player:has_activity() and config.base.auto_turn_speed ~= "highest" then local anim_wait = player.activity:get_animation_wait() if anim_wait > 0 then dt = coroutine.yield() field:update(dt) end end -- In Elona, the player always goes first at the start of each -- turn, followed by allies, adventurers, then others. This was -- previously accomplished by simply iterating the cdata[] array by -- increasing index, since the player was always index 0, allies -- index 1-15, adventurers 15-56, and so on. state.player_finished_turn = false state.chara_iter, state.chara_iter_state, state.chara_iter_index = Chara.iter_all() local speed = player:emit("base.on_calc_speed") -- All characters will start with at least this much time during -- this turn. local starting_turn_time = (field:turn_cost() - player.time_this_turn) / speed + 1 -- TODO: world map continuous action local update_time_this_turn = true if update_time_this_turn then field_logic.update_chara_time_this_turn(starting_turn_time) end -- BUG: don't pass time if just loaded from save World.pass_time_in_seconds(starting_turn_time / 5 + 1) Event.trigger("base.on_hud_message", {action="new_turn"}) return "pass_turns" end function field_logic.determine_turn() local player = Chara.player() assert(player ~= nil) if state.chara_iter == nil then Log.warn("chara iter was nil, probably hotloaded.") return nil end -- TODO: check if player can go first, then allies, then others. if not state.player_finished_turn then state.player_finished_turn = true return player end -- HACK: use a better way that also orders allies first local found = nil local chara local going = true local any_moved = true while going do repeat state.chara_iter_index, chara = state.chara_iter(state.chara_iter_state, state.chara_iter_index) if chara ~= nil and chara.time_this_turn >= field:turn_cost() then found = chara any_moved = true end until found ~= nil or state.chara_iter_index == nil if found or any_moved == false then going = false end if state.chara_iter_index == nil then any_moved = false state.chara_iter, state.chara_iter_state, state.chara_iter_index = Chara.iter_all() end end return found end function field_logic.pass_turns() local chara = field_logic.determine_turn() if chara == nil then -- Start a new turn. return "turn_begin" end if config.base.anime_wait_type == "at_turn_start" then Gui.wait_for_draw_callbacks() end local is_first_turn = save.base.is_first_turn if is_first_turn then save.base.is_first_turn = false end chara.time_this_turn = chara.time_this_turn - field:turn_cost() chara.turns_alive = chara.turns_alive + 1 local result = chara:emit("base.before_chara_turn_start", {is_first_turn=is_first_turn}, {blocked=false}) if result.blocked then if result.wait then Gui.wait(result.wait, true) end return result.turn_result or "turn_end", chara end -- EVENT: before_chara_begin_turn -- wet if outdoors and rain -- BUILTIN: gain level -- if Chara.is_player(chara) then -- actually means beginning of all turns. -- refresh speed? -- prevent escape -- RETURN: potentially exit map here -- proc map events -- ether disease -- end if chara:is_player() and not Chara.is_alive(chara) then return "player_died", chara end -- proc mef -- proc buff local result = chara:emit("base.on_chara_pass_turn", {}, {blocked=false}) if result.blocked then return result.turn_result or "turn_end", chara end -- >>>>>>>> shade2/main.hsp:821 if cc=pc:if (cRowAct(cc)!rowActEat)&(cRowAct(cc) ... if chara:is_player() and chara:has_activity() then chara:_proc_activity_interrupted() end -- <<<<<<<< shade2/main.hsp:821 if cc=pc:if (cRowAct(cc)!rowActEat)&(cRowAct(cc) .. -- proc refresh if transferred if chara:has_activity() then local turn_result = chara:pass_activity_turn() if config.base.auto_turn_speed ~= "highest" and chara.activity and chara.activity:get_animation_wait() > 0 then Gui.update_screen() end if turn_result then return turn_result, chara end Log.warn("Activity '%s' on chara %d (%s) did not return turn result", chara:get_activity()._id, chara.uid, chara._id) return "pass_turns" end if Chara.is_alive(chara) then if chara:is_player() then return "player_turn", chara else return "npc_turn", chara end end return "pass_turns" end function field_logic.player_turn() local player = Chara.player() player.target_location = nil return "player_turn_query" end -- base.on_player_query_frame needs to be efficient as possible since it will -- get called on every frame, so don't allocate an event params table inside the -- loop. local EVENT_ARGS = {} function field_logic.player_turn_query() local result local going = true local player = Chara.player() if not Chara.is_alive(player) then return "player_died", player end if state.about_to_autosave then state.about_to_autosave = false Save.save_game() end Gui.update_screen(dt, true) -- Wait for draw callbacks if necessary. dt = coroutine.yield() while field:update_draw_callbacks(dt) do dt = coroutine.yield() end if config.base.anime_wait_type == "at_turn_start" then Gui.wait_for_draw_callbacks() end result = Event.trigger("base.on_player_turn") if result then field:update(dt) return result, player end while going do if field.map_changed then -- Game was loaded while we were querying for input; clear the list of -- characters to act and start again from "turn_begin". result = "player_turn_query" going = false break end local ran, turn_result = field:run_actions(dt, player) field:update(dt) if field.repl then local success, turn_result = field.repl:execute_all_deferred() if success and turn_result then result = turn_result going = false break end end if ran == true then result = turn_result or "player_turn_query" going = false break end field.no_scroll_this_update = false table.clear(EVENT_ARGS) Event.trigger("base.on_player_turn_query_frame", EVENT_ARGS) dt = coroutine.yield() end -- TODO: convert public to internal event return result, player end function field_logic.npc_turn(npc) assert(not npc:is_player()) local Ai = require("api.Ai") Ai.run(npc.ai, npc) return "turn_end", npc end function field_logic.turn_end(chara) if not Chara.is_alive(chara) then return "pass_turns" end local result = chara:emit("base.on_chara_turn_end", {}, {regeneration=true}) local regen = result.regeneration if Chara.is_player(chara) then -- hunger -- sleep else -- quest delivery flag end -- party time emoicon if regen then chara:emit("base.on_regenerate") end -- proc timestop return "pass_turns" end local function do_revive_player() local player = Chara.player() assert(player:revive()) local success, map = Map.load(save.base.home_map_uid) if success then Map.travel_to(map) else Log.error("Game has not been saved yet, reviving in current map instead. Scenarios should always save the game when first starting. (%s)", map) end player:emit("base.on_player_death_revival") end local function revive_player() state.player_about_to_respawn = true local ok, err = xpcall(do_revive_player, debug.traceback) state.player_about_to_respawn = false if not ok then error(err) end end function field_logic.player_died(player) Gui.play_sound("base.dead1") Gui.update_screen() local result = Event.trigger("base.on_player_death", {player = player}) if result then return result end Gui.mes("misc.death.good_bye") Gui.mes("misc.death.you_leave_dying_message") local last_words = Input.query_text(16, true) if last_words == nil or last_words == "" then last_words = I18N.get("misc.death.dying_message", "system.last_words") else last_words = I18N.get("misc.death.dying_message", last_words) end local bones = save.base.bones --[[ { title = "Elegant crimson", name = "Xero", last_words = "\"Gee, that smarts!\"", date = DateTime:new(), death_cause = "died from loss of blood", map_name = "Lesimas", score = 9999, image = "elona.human_male", color = {255, 255, 255} } --]] local map = Map.current() local bone = { title = player.title, name = player.name, last_words = last_words, date = table.deepcopy(save.base.date), death_cause = "TODO", map_name = map.name, score = World.calc_score(), image = player.image, color = player.color or {255, 255, 255} } local MAX_BONES = 80 if #bones >= MAX_BONES then -- Remove lowest scoring record. bones[#bones] = bone else bones[#bones+1] = bone end table.sort(bones, function(a, b) return a.score > b.score end) save.base.bones = bones local result, canceled = DeathMenu:new(bones, bone):query() if canceled or result.index == 1 then revive_player() return "turn_begin" end return "title_screen" end function field_logic.run_one_event(event, target_chara) local cb = nil Log.trace("Turn event: %s (%s)", event, target_chara) if Chara.player() == nil then -- Something went wrong; at least boot the game back to the -- title so it doesn't have to be restarted. Log.error("Player is nil, returning to title.") return false end if field.map_changed == true then event = "turn_begin" field.map_changed = false end if event == "turn_begin" then cb = field_logic.turn_begin elseif event == "turn_end" then cb = field_logic.turn_end elseif event == "player_died" then cb = field_logic.player_died elseif event == "player_turn" then cb = field_logic.player_turn elseif event == "player_turn_query" then cb = field_logic.player_turn_query elseif event == "npc_turn" then cb = field_logic.npc_turn elseif event == "pass_turns" then cb = field_logic.pass_turns elseif event == "title_screen" then return false, event elseif event == "quit" then return false, event end if type(cb) ~= "function" then error("Unknown turn event " .. inspect(event)) end local success success, event, target_chara = xpcall(function() return cb(target_chara) end, debug.traceback) if not success then -- pass the error up to the main loop so the error screen can be -- displayed coroutine.yield(event) event = "player_turn_query" target_chara = nil end return true, event, target_chara end function field_logic.query() Log.info("Entered main loop.") field_logic.setup() local event = "turn_begin" local going = true local target_chara main_state.is_in_game = true draw.push_layer(field.hud) draw.push_layer(field) field:reset_scrolling() Gui.update_screen() while going do going, event, target_chara = field_logic.run_one_event(event, target_chara) end draw.pop_layer() draw.pop_layer() field.map = nil main_state.is_in_game = false return event end return field_logic
local UIListLayout = import("./UIListLayout") local typeof = import("../functions/typeof") describe("instances.UIListLayout", function() it("should instantiate", function() local instance = UIListLayout:new() assert.not_nil(instance) end) it("should inherit from UIGridStyleLayout", function() local instance = UIListLayout:new() assert.True(instance:IsA("UIGridStyleLayout")) end) it("should have properties defined", function() local instance = UIListLayout:new() assert.equals(typeof(instance.Padding), "UDim") end) end)
object_tangible_content_wod_token_2 = object_tangible_content_shared_wod_token_2:new { } ObjectTemplates:addTemplate(object_tangible_content_wod_token_2, "object/tangible/content/wod_token_2.iff")
local Root = script:GetCustomProperty("Root"):WaitForObject() local Registry = script:GetCustomProperty("Registrty"):WaitForObject() local function Update(_, prop) if prop == "ActiveChart" then local children = Root:GetChildren() local activestring = Registry:GetCustomProperty("ActiveChart") for i = 1, #activestring do local c = activestring:sub(i, i) if children[i].clientUserData.trapActivateEvent then if c == "1" then if children[i].clientUserData.trapActivationLast ~= true then children[i].clientUserData.trapActivationLast = true children[i].clientUserData.trapActivateEvent:_Fire(true) end else if children[i].clientUserData.trapActivationLast ~= false then children[i].clientUserData.trapActivationLast = false children[i].clientUserData.trapActivateEvent:_Fire(false) end end end end end end Registry.networkedPropertyChangedEvent:Connect(Update)
-- lib/server/groups.lua -- functions for managing the player groups function BSU.RegisterGroup(id, name, color, usergroup, inherit) BSU.SQLInsert(BSU.SQL_GROUPS, { id = id, name = name, color = type(color) == "table" and BSU.ColorToHex(color) or string.gsub(color, "#", ""), usergroup = usergroup, inherit = inherit } ) end function BSU.RemoveGroup(id) BSU.SQLDeleteByValues(BSU.SQL_GROUPS, { id = id }) end function BSU.GetAllGroups() return BSU.SQLSelectAll(BSU.SQL_GROUPS) or {} end -- get group by its numeric id function BSU.GetGroupByID(id) local query = BSU.SQLSelectByValues(BSU.SQL_GROUPS, { id = id }) return query and query[1] end -- get all groups with the function BSU.GetGroupsByName(name) return BSU.SQLSelectByValues(BSU.SQL_GROUPS, { name = name }) or {} end function BSU.SetGroupData(id, values) BSU.SQLUpdateByValues(BSU.SQL_GROUPS, { id = id }, values) end -- setup teams function BSU.PopulateTeams() local groups = BSU.GetAllGroups() for k, v in ipairs(groups) do team.SetUp(v.id, v.name, BSU.HexToColor(v.color)) end end
--- Main module for the Google Analytics implementation for the Defold game -- engine. -- -- @usage -- local ga = require "googleanalytics.ga" -- -- function init(self) -- ga.get_default_tracker().screenview("my_cool_screen") -- end -- -- function update(self, dt) -- ga.update() -- end -- -- function on_input(self, action_id, action) -- if gui.pick_node(node, action.x, action.y) and action.pressed then -- go.get_default_tracker().event("category", "action")) -- end -- end local tracker = require "googleanalytics.tracker" local queue = require "googleanalytics.internal.queue" local M = { dispatch_period = tonumber(sys.get_config("googleanalytics.dispatch_period", 30 * 60)), } local default_tracker = nil --- Get the default tracker -- @return Tracker instance function M.get_default_tracker() if not default_tracker then local tracking_id = sys.get_config("googleanalytics.tracking_id") assert(tracking_id, "You must set tracking_id in section [googleanalytics] in game.project before using this module") default_tracker = tracker.create(tracking_id) end return default_tracker end --- Dispatch hits to Google Analytics function M.dispatch() queue.dispatch() end --- Update the Google Analytics module. -- This will check if automatic dispatch of hits are enabled and if so, if it is -- time to dispatch stored hits. function M.update() -- manual dispatch only? if M.dispatch_period <= 0 then return end if not queue.last_dispatch_time or (socket.gettime() >= (queue.last_dispatch_time + M.dispatch_period)) then M.dispatch() end end return M
-- type = github -- DO NOT REMOVE THIS LINE! local name = "jx" local version = "3.2.279" local org = "jenkins-x" local repo = "jx" local base_url = "https://github.com/" .. org .. "/" .. repo food = { name = name, description = "JX is a command line tool for installing and using Jenkins X", license = "Apache-2.0", homepage = "https://jenkins-x.io/", version = version, packages = { { os = "darwin", arch = "amd64", url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "-darwin-amd64.tar.gz", sha256 = "34b84a4c2a132a24c85ba8fd80ee2ea09c6cb40b9e137b1ce71efe172e54ab63", resources = { { path = name, installpath = "bin/" .. name, executable = true } } }, { os = "darwin", arch = "arm64", url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "-darwin-arm64.tar.gz", sha256 = "afc7d3c0c8711fd51f59402b32d34d16be097a341005af9c24737e77d51036d3", resources = { { path = name, installpath = "bin/" .. name, executable = true } } }, { os = "linux", arch = "amd64", url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "-linux-amd64.tar.gz", sha256 = "550ae3552673b0d68cc2b8bb5f3b21b2d1f34054c5cfc41ecba345185a574188", resources = { { path = name, installpath = "bin/" .. name, executable = true } } }, { os = "windows", arch = "amd64", url = base_url .. "/releases/download/v" .. version .. "/" .. name .. "-windows-amd64.zip", sha256 = "39ed90d483da071f976cf26f80f95de28fc9e07f0f07bef0edd03d18fb7324e0", resources = { { path = name .. ".exe", installpath = "bin\\" .. name .. ".exe" } } } } }
data:extend( { { type = "item", name = "economics-buyer-chest", icon = "__Economics__/graphics/icons/economics-buyer-chest.png", flags = {"goes-to-quickbar"}, subgroup = "storage", order = "a[items]-e[economics-buyer-chest]", place_result = "economics-buyer-chest", stack_size = 50 }, { type = "item", name = "economics-seller-chest", icon = "__Economics__/graphics/icons/economics-seller-chest.png", flags = {"goes-to-quickbar"}, subgroup = "storage", order = "a[items]-e[economics-seller-chest]", place_result = "economics-seller-chest", stack_size = 50 } } )
local function GetItem(desiredItemID) for i = 1, 16, 1 do local data = turtle.getItemDetail(i) if(data ~= nil) then if(data.name == desiredItemID) then return i end end end -- to avoid "too long without yielding" error: turtle.inspect() end local function DropItem(desiredItemID) for i = 1, 16, 1 do local data = turtle.getItemDetail(i) if(data ~= nil) then if(data.name == desiredItemID) then turtle.select(i) turtle.drop() end end end end local function isInvFull() for i = 1, 16, 1 do local data = turtle.getItemDetail(i) if(data == nil) then return false end end return true end local function readState() local file = fs.open("State.txt","a") file.flush() return fs.open("State.txt","r") end local function writeState(state) local file = fs.open("State.txt","w") file.write(state) file.flush() end -- should create functions which automatically look if the way is free (for forward and up and that stuff) return { GetItem = GetItem, DropItem = DropItem, isInvFull = isInvFull, readState = readState, writeState = writeState}
--============================================================================-- -- initialization.lua --============================================================================-- require 'util' require ('config') require 'scripts/utils' --============================================================================-- -- initialize_subterra() -- -- initiate mod and generate underground surface -- wired in control.lua:game.on_init --============================================================================-- function initialize_subterra () debug("Starting SubTerra Initialization") local max_depth = settings.startup["subterra-max-depth"].value global.max_depth = max_depth local top_surface = game.surfaces['nauvis'] local gen_settings = get_underground_settings(top_surface) -- create surface(s) with no resources -- for i = 1, max_depth do -- local layer_name = "underground_" .. tostring(i) -- if game.surfaces[layer_name] == nil then -- game.create_surface(layer_name, gen_settings) -- game.surfaces[layer_name].daytime = 0.5 -- game.surfaces[layer_name].freeze_daytime = true -- end -- if remote.interfaces["RSO"] then -- remote.call("RSO", "ignoreSurface", layer_name) -- end -- end -- create force_proxies -- global.force_proxies = {} -- for name, force in pairs(game.forces) do -- force_proxies[name] = { -- } -- end -- create player proxies global.player_proxies = {} global.drawing_players = {} debug("Player Count: " .. tostring(# game.players)) for i, p in pairs(game.players) do debug("Creating proxy for player: " .. p.name) add_player_proxy(i) end -- initialize layers container global.layers = {} local ground = { index = 1, layer_above = nil, surface = top_surface, telepads = Quadtree:new(), pad_ghosts = Quadtree:new(), belt_ghosts = Quadtree:new(), power_ghosts = Quadtree:new() } ground.telepads:rebuild_index() ground.pad_ghosts:rebuild_index() ground.belt_ghosts:rebuild_index() ground.power_ghosts:rebuild_index() table.insert(global.layers, ground) global.layers["nauvis"] = global.layers[1] for i = 1, global.max_depth do local l_name, layer = create_layer(i, gen_settings) table.insert(global.layers, layer) global.layers[l_name] = layer end local middle, radius = get_generated_extents(top_surface) -- debug("World Rect: {" .. middle[1] .. ", " .. middle[2] .. "} radius = " .. radius .. "\n") -- debug("X: " .. minx .. ", " .. maxx) -- debug("Y: " .. miny .. ", " .. maxy) -- debug("") -- set adjacency and kickstart chunk generation global.layers[1].layer_below = global.layers[2] for i = 2, max_depth + 1 do local layer = global.layers[i] --layer.surface.request_to_generate_chunks({0,0}, 10) layer.surface.request_to_generate_chunks(middle, radius) layer.layer_above = global.layers[i-1] if i <= max_depth then layer.layer_below = global.layers[i+1] else layer.layer_below = nil end end -- initialize proxy containers if not global.belt_inputs then global.belt_inputs = {} end if not global.belt_outputs then global.belt_outputs = {} end if not global.power_proxies then global.power_proxies = {} end if not global.power_array then global.power_array = {} end if not global.current_depth then global.current_depth = {} end for index, force in pairs(game.forces) do global.current_depth[force.name] = 0 end -- set underground enitity list initialize_belt_elevators() initialize_underground_blacklist() initialize_underground_whitelist() initialize_underground_type_whitelist() -- intialize radar proxy table -- will only be populated runtime global.radar_proxies = {} -- indexed by unit_number, for lookup from entity global.radar_proxy_array = {} -- compact array of all proxies, for iterating over on_tick global.radar_proxy_forces = {} -- compact arrays indexed by force name, for iterating over on tech rechearhed for name, force in pairs(game.forces) do global.radar_proxy_forces[name] = {} end debug("SubTerra Initialization Complete") end function initialize_underground_blacklist() if not global.underground_blacklist then global.underground_blacklist = {} end local blacklist = global.underground_blacklist -- required entities for name,_ in pairs(subterra.config.underground_blacklist) do blacklist[name] = true end -- add entities from settings local blacklist_string = settings.startup["subterra-blacklist"].value or "" local new_list = split(blacklist_string, ";") global.blacklist_string = blacklist_string for _, name in pairs(new_list) do log("blacklist: " .. name) blacklist[name] = true end end function initialize_underground_whitelist() if not global.underground_whitelist then global.underground_whitelist = {} end local whitelist = global.underground_whitelist -- required entities for name,_ in pairs(subterra.config.underground_entities) do whitelist[name] = true end -- add entities from settings local whitelist_string = settings.startup["subterra-whitelist"].value or "" local new_list = split(whitelist_string, ";") global.whitelist_string = whitelist_string for _, name in pairs(new_list) do log("whitelist: " .. name) whitelist[name] = true end end function initialize_underground_type_whitelist() if not global.underground_types then global.underground_types = {} end local whitelist = global.underground_types -- required entities for name,_ in pairs(subterra.config.underground_types) do whitelist[name] = true end -- add entities from settings local whitelist_string = settings.startup["subterra-whitelist"].value or "" local new_list = split(whitelist_string, ";") global.whitelist_string = whitelist_string for _, name in pairs(new_list) do log("whitelist: " .. name) whitelist[name] = true end end function initialize_belt_elevators() local belt_elevators = {} for name, prototype in pairs(game.entity_prototypes) do if string.find(prototype.name, "subterra%-%a*%-*transport%-belt") then belt_elevators[name] = true end end global.belt_elevators = belt_elevators end function on_load() for i, layer in pairs(global.layers) do local pads = layer.telepads if pads and not getmetatable(pads) then setmetatable(pads, Quadtree) pads:rebuild_metatables() end local pad_ghosts = layer.pad_ghosts if pad_ghosts and not getmetatable(pad_ghosts) then setmetatable(pad_ghosts, Quadtree) pad_ghosts:rebuild_metatables() end local belt_ghosts = layer.belt_ghosts if belt_ghosts and not getmetatable(belt_ghosts) then setmetatable(belt_ghosts, Quadtree) belt_ghosts:rebuild_metatables() end local power_ghosts = layer.power_ghosts if power_ghosts and not getmetatable(power_ghosts) then setmetatable(power_ghosts, Quadtree) power_ghosts:rebuild_metatables() end end end
-- Image and Animation Assets for fire dart. local assets = { -- Animations. Asset("ANIM", "anim/fire_dart.zip"), -- Inventory images. Asset("ATLAS", "images/inventoryimages/fire_dart.xml"), Asset("IMAGE", "images/inventoryimages/fire_dart.tex"), } -- Load additional Prefabs, just in case. local prefabs = { "impact" } -- On a hit, hit the target and damage it. Remove dart afterwards. local function OnHit(inst, attacker, target) local impactfx = SpawnPrefab("impact") if impactfx ~= nil then local follower = impactfx.entity:AddFollower() follower:FollowSymbol(target.GUID, target.components.combat.hiteffectsymbol, 0, 0, 0) if attacker ~= nil then impactfx:FacePoint(attacker.Transform:GetWorldPosition()) target.components.combat:SuggestTarget(attacker) target.components.combat:GetAttacked(attacker, TUNING.BLOWGUN_REVAMPED.FIRE_DART_DAMAGE) end end inst:Remove() end -- On a miss, spawn the dart for pickup. Remove projectile dart afterwards. local function OnMiss(inst, attacker, target) local dart = SpawnPrefab("fire_dart") if dart then local x, y, z = inst.Transform:GetWorldPosition() dart.Transform:SetPosition(x, y, z) end inst:Remove() end -- Orient the dart so that it looks correct. local function OnThrown(inst, data) inst.AnimState:SetOrientation(ANIM_ORIENTATION.OnGround) end -- Handle animation of dart. local function DartThrown(inst) inst:AddTag("NOCLICK") inst.persists = false inst.AnimState:PlayAnimation("projectile") end -- Fire Darat Definition / Initialization local function fn() local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddNetwork() MakeInventoryPhysics(inst) RemovePhysicsColliders(inst) inst.AnimState:SetBank("fire_dart") inst.AnimState:SetBuild("fire_dart") inst.AnimState:PlayAnimation("idle") inst.entity:SetPristine() inst:AddTag("projectile") inst:AddTag("ammunuition") if not TheWorld.ismastersim then return inst end -- Make dart inspectable. inst:AddComponent("inspectable") -- Make dart an inventory item. inst:AddComponent("inventoryitem") inst.components.inventoryitem.imagename = "fire_dart" inst.components.inventoryitem.atlasname = "images/inventoryimages/fire_dart.xml" -- Handle stack size. inst:AddComponent("stackable") inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM -- Make dart into ammunition. inst:AddComponent("ammunition") -- Make dart a projectile. inst:AddComponent("projectile") inst.components.projectile:SetSpeed(TUNING.BLOWGUN_REVAMPED.FIRE_DART_SPEED) inst.components.projectile:SetHoming(TUNING.BLOWGUN_REVAMPED.FIRE_DART_HOMING) inst.components.projectile:SetRange(TUNING.BLOWGUN_REVAMPED.BLOWGUN_RANGE) -- Handle dart actions. inst.components.projectile:SetOnHitFn(OnHit) inst.components.projectile:SetOnMissFn(OnMiss) inst.components.projectile:SetOnThrownFn(OnThrown) inst:ListenForEvent("onthrown", DartThrown) MakeHauntableLaunch(inst) return inst end return Prefab("fire_dart", fn, assets)
-- local discordia = require('discordia') local stars = setmetatable({}, {__index = function() return 0 end}) local function star(msg) if msg.author.discriminator ~= '0000' then return end local embed = msg.embed if not embed then return end if not embed.title then return end if not embed.title:find('New star added') then return end if not embed.author then return end if not embed.author.name then return end local key = msg.channel.id .. embed.author.name .. embed.title stars[key] = stars[key] + 1 if stars[key] > 1 then if stars[key] == 2 then msg.client.owner:sendf( 'Star spam detected at %q (%q) by %q', msg.channel.name, msg.channel.id, embed.author.name ) end return true end end return function(msg) local channel = msg.channel local guild = channel.guild local bot = guild.me if bot:hasPermission(channel, 'manageMessages') then if star(msg) then -- github star spam return msg:delete() end end end
mapFields = require "lib/mapFields" target.play_portal_sound_effect() target.modify_skill(20000016, 0, -1) target.modify_skill(20000016, 1, 0) target.transfer_field(mapFields.getID("BurningForest3"), 1)
--[[============================================================================= ON_INIT, Timer,s and Property management functions Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] require "common.c4_driver_declarations" require "lib.c4_log" require "lib.c4_timer" -- Set template version for this file if (TEMPLATE_VERSION ~= nil) then TEMPLATE_VERSION.c4_common = "2014.10.31" end --[[============================================================================= Create and Initialize Logging ===============================================================================]] function ON_DRIVER_EARLY_INIT.c4_common() -- Create a logger LOG = c4_log:new("Template_c4z Change Name") end function ON_DRIVER_INIT.c4_common() -- Create Log Timer gC4LogTimer = c4_timer:new("Log Timer", 45, "MINUTES", OnLogTimerExpired) end --[[============================================================================= Log timer callback function ===============================================================================]] function OnLogTimerExpired() LogWarn("Turning Log Mode Off (timer expired)") gC4LogTimer:KillTimer() C4:UpdateProperty("Log Mode", "Off") OnPropertyChanged("Log Mode") end gForceLogging = false function ON_PROPERTY_CHANGED.LogMode(propertyValue) gC4LogTimer:KillTimer() if (gForceLogging) then LOG:OutputPrint(true) LOG:OutputC4Log(true) else LOG:OutputPrint(propertyValue:find("Print") ~= nil) LOG:OutputC4Log(propertyValue:find("Log") ~= nil) if (propertyValue == "Off") then return end gC4LogTimer:StartTimer() end end function ON_PROPERTY_CHANGED.LogLevel(propertyValue) if (gForceLogging) then LOG:SetLogLevel("5 - Debug") else LOG:SetLogLevel(propertyValue) end end --[[============================================================================= Print Template Versions ===============================================================================]] function TemplateVersion() print ("\nTemplate Versions") print ("-----------------------") for k, v in pairs(TEMPLATE_VERSION) do print (k .. " = " .. v) end print ("") end
local home = {} local properties = {} local json = require("json") local zip = require("plugin.zip") function home:render(params) ------------------------------------------------------------------------------ -- Declarations ------------------------------------------------------------------------------ local showBlur, closeBlur, showTextOnBlur, callBackFunc, getSubscription, getSubscribeIrancell local background = display.newImage( "images/mainBackGround.jpg") background.x = backgroundX background.y = backgroundY table.insert(properties, background) local pageTitleBackground = display.newImage("images/titleBackGround.png") pageTitleBackground.x = pageTitleBackgroundX pageTitleBackground.y = pageTitleBackgroundY pageTitleBackground.name = "pageTitle" table.insert(properties, pageTitleBackground) local pageTitle = display.newText(texts.home.pageTitle, pageTitleX, pageTitleY, fonts.lalezar, fonts.pageTitleSize) table.insert(properties, pageTitle) local apps = nil apps = display.newImage( "images/home/apps.png") apps.height, apps.width = 126, 126 apps.x = centerX + 0.4 * screenWidth apps.y = centerY + (-0.1) * screenHeight apps.name = "apps" table.insert(properties, apps) local cheetah = display.newImage("images/cheetah.png") cheetah.x = cheetahX cheetah.y = cheetahY table.insert(properties, cheetah) local deer = display.newImage("images/deer.png") deer.x = 135 deer.y = display.actualContentHeight - 145 table.insert(properties, deer) local picture = display.newImage( "images/paint/pic.png") picture.x = display.contentCenterX - 480 picture.y = screenTop + 0.14 * screenHeight picture.name = "picture" table.insert(properties, picture) local pictureInner = nil pictureInner = display.newImage(appConfig:getAvatarAddress()) pictureInner.x = picture.x pictureInner.y = picture.y pictureInner.width = picture.width * .9 pictureInner.height = picture.height * .9 table.insert(properties, pictureInner) -- local productsIcon = nil -- productsIcon = display.newImage("images/buy.png") -- productsIcon.height, productsIcon.width = 126, 126 -- productsIcon.x = centerX + 0.4 * screenWidth -- productsIcon.y = centerY - 0.165 * screenHeight -- productsIcon.name = "productsIcon" -- table.insert(properties, productsIcon) local competitionHistory = display.newImage( "images/cup.png") competitionHistory.x = centerX + 0.01 * screenWidth competitionHistory.y = centerY + 0.230 * screenHeight competitionHistory.name = "competitionHistory" table.insert(properties, competitionHistory) local painting = display.newImage( "images/home/painting.png") painting.x = centerX - 0.150 * screenWidth painting.y = centerY - 0.190 * screenHeight painting.name = "painting" table.insert(properties, painting) local coloring = display.newImage( "images/home/coloring.png") coloring.x = centerX + 0.170 * screenWidth coloring.y = centerY - 0.190 * screenHeight coloring.name = "coloring" table.insert(properties, coloring) local selected = display.newImage( "images/home/select.png") selected.x = centerX - 0.150 * screenWidth selected.y = centerY + 0.05 * screenHeight selected.name = "selected" table.insert(properties, selected) local gallery = display.newImage( "images/home/gallery.png") gallery.x = centerX + 0.175 * screenWidth gallery.y = centerY + 0.05 * screenHeight gallery.name = "gallery" table.insert(properties, gallery) local exit = display.newImage( "images/home/exit.png") exit.height, exit.width = 126, 126 exit.x = display.contentCenterX - 480 exit.y = centerY - 0.150 * screenHeight exit.name = "exit" table.insert(properties, exit) if not appConfig:isParentSet() then navigate("slidSwiper1") end native.showPopup( "requestAppPermission", { appPermission = { "Camera", "Storage"}, urgency = "Normal", listener = permissionsListener, } ) renderSoundButton() local function exitFunction() if isAlertRendered then return true else isExitAlertRendered = true alert({ textImage = images.alerts.exit, isYesNo = true, callBack = function(index) if index == 1 then os.exit() elseif index == 2 then end end}) return true end end -- end of exit function local function buttonTouchHandlers(event) if event.phase == "began" then audio.stop(clickSoundCannel) audio.play(clickSound, clickPlayOptions) event.target.width = event.target.width * clickResizeFactor event.target.height = event.target.height * clickResizeFactor if event.target.name == "picture" then pictureInner.width = pictureInner.width * clickResizeFactor pictureInner.height = pictureInner.height * clickResizeFactor end display.getCurrentStage():setFocus( event.target ) event.target.isFocus = true end if not event.target.isFocus then return false end if event.phase then print("&&&&&$$$$$$$#@#########@@@@@") print(appConfig) print(appConfig:getFlagCheckStatus()) print(appConfig:getTypeOperator()) if not appConfig:getFlagCheckStatus() then if appConfig:getTypeOperator() == texts.typeOperator.mci then if appConfig:getReferenceCode() then -- getSubscription() else -- navigate("slidSwiper1") end else if appConfig:getToken() then getSubscribeIrancell() else navigate("slidSwiper1") end end appConfig:setFlagCheckStatus(true) end end if event.phase == "ended" then event.target.width = event.target.width / clickResizeFactor event.target.height = event.target.height / clickResizeFactor if event.target.name == "painting" then navigate("paint") end if event.target.name == "selected" then navigate("selected") end if event.target.name == "gallery" then navigate("gallery") end if event.target.name == "coloring" then navigate("coloringCategoriesList") end if event.target.name == "apps" then navigate("dorsa") end if event.target.name == "pageTitle" then navigate("about") end if event.target.name == "picture" then pictureInner.width = pictureInner.width / clickResizeFactor pictureInner.height = pictureInner.height / clickResizeFactor navigate("users") end -- if event.target.name == "productsIcon" then -- print('productsIcon') -- navigate("products") -- end if event.target.name == "exit" then exitFunction() end if event.target.name == "competitionHistory" then if appConfig:isParentSet() then alert({ textImage = images.alerts.sendPainting, isCustomeBtn = true, isYesNo = true, callBack = function(index) if index == 1 then navigate("gallery") elseif index == 2 then loadimg() elseif index == 3 then showLoading() local function onComplete( event ) if event.completed then local pictureName = saveImageFromGallery("tempCameraImage.jpg", system.DocumentsDirectory) local params = { directoryAddress = appConfig:getUserName().."/savedPictures/"..pictureName, dir = system.DocumentsDirectory, image = appConfig:getUserName().."/savedPictures/"..pictureName.."/main.png", name = pictureName, isFromGallery = true } navigate("showSavedPicture", params) closeLoading() else closeLoading() end end os.remove( system.pathForFile( "tempCameraImage.jpg", system.DocumentsDirectory ) ) local function permissionsListener( event ) print( "permissionsListener") end if media.hasSource( media.Camera ) then media.capturePhoto( { mediaSource = media.Camera, listener = onComplete, destination = { baseDir = system.DocumentsDirectory, filename = "tempCameraImage.jpg" } } ) else native.showAlert( "خطا", "این دستگاه فاقد دوربین می باشد", { "تایید" } ) end end end}) else alert({ textImage = images.alerts.parentNotSet, isYesNo = true, callBack = function(index) if index == 1 then navigate("parent", getCurrentRoute()) elseif index == 2 then end end}) end end event.target.isFocus = false display.getCurrentStage():setFocus(nil) end end painting:addEventListener("touch", buttonTouchHandlers) coloring:addEventListener("touch", buttonTouchHandlers) selected:addEventListener("touch", buttonTouchHandlers) gallery:addEventListener("touch", buttonTouchHandlers) picture:addEventListener("touch", buttonTouchHandlers) pageTitleBackground:addEventListener("touch", buttonTouchHandlers) -- productsIcon:addEventListener("touch", buttonTouchHandlers) apps:addEventListener("touch", buttonTouchHandlers) exit:addEventListener("touch", buttonTouchHandlers) competitionHistory:addEventListener("touch", buttonTouchHandlers) ------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------------- ------------------------------------------------------------------------------ -- Functions ------------------------------------------------------------------------------ local blur = nil local text = nil ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ callBackFunc = function() if not appConfig:hasUser() then navigate("slidSwiper1") end end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ showTextOnBlur = function(newText) print("(showTextOnBlur&&&&&)") if text then display.remove(text) text = nil end text = display.newText({ text = newText, x = centerX, y = centerY, font = fonts.lalezar, fontSize = 46, }) text:setFillColor(1, 1, 1, 1) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ closeBlur = function(triggerCallBack) print("close blur &&&&&& kjh") local function removeGroup(cb1) display.remove(blur) blur = nil if text then display.remove(text) text = nil end -- authenticationCode.isVisible = true if triggerCallBack then print("triggerCallBack") print(triggerCallBack) callBackFunc() end end transition.to(blur, { alpha = 0, onComplete = removeGroup}) return true end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ showBlur = function() if blur then return end blur = display.captureScreen() blur.x, blur.y = centerX, centerY blur:setFillColor(.1, .1, .1) blur.fill.effect = "filter.blur" blur.alpha = 0 -- authenticationCode.isVisible = false transition.to(blur, {alpha = 1}) blur:addEventListener("tap", function() return true end) blur:addEventListener("touch", function() return true end) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ function getSubscription() print("&&&&&&&&&&&&&&&&&^^^^^^^^^^^^^^############") local function networkListener( event ) print(event.response) local response = json.decode(event.response) print(event.response) print("homePage loooog") if ( event.isError ) then showTextOnBlur(texts.buyProduct.problemInConnectingToServer) timer.performWithDelay( 1000, closeBlur() ) else -------------------------------------------------------------------------- NEEDS CHANGING print(event.status) if event.status == 200 then appConfig:setParentFromJSON(event.response) if response.data[1].product_status == 'INACTIVE' then navigate("slidSwiper0") appConfig:eraseUsers() appConfig:eraseParent() end elseif event.status == 409 then showTextOnBlur(texts.parent.wrongInformation) timer.performWithDelay( 1500, closeBlur() ) elseif event.status == 400 then showTextOnBlur(texts.parent.wrongInformation) timer.performWithDelay( 1500, closeBlur() ) else errorResponse(response) timer.performWithDelay( 1500, closeBlur() ) end end end print(referenceCode) local tempUrl = { urls.getSubscription, "?user_number=", appConfig:getParentPhone(), urls.serviceCodeProductCode, "&reference_code=", appConfig:getReferenceCode()} print(table.concat(tempUrl)) network.request( table.concat(tempUrl), "GET", networkListener) end ----------------------------------------------------------------------------------------- ------------------------------------------------------------------------------ function getSubscribeIrancell() local function netCheckSubscribeListener( event ) -------------------------------------------------------------------------- NEEDS CHANGING if event.status == 200 then local response = json.decode(event.response) timer.performWithDelay( 2000, closeBlur()) print("its okkkkkk") print(response.cancelReason) if response.cancelReason ~= nil then appConfig:eraseUsers() appConfig:eraseParent() navigate("slidSwiper0") end else showTextOnBlur(texts.parent.wrongInformation) timer.performWithDelay( 1500, closeBlur() ) end end local tempUrl = { urls.serviceCheckSubscribIrancell, appConfig:getToken(), "?access_token=", accessToken} network.request( table.concat(tempUrl), "GET", netCheckSubscribeListener) end end function home:close() closeSoundButton() if #properties > 0 then for n = #properties, 1, - 1 do display.remove(properties[n]) properties[n] = nil end end end return home
-- function setup() FONT_load("AlexBrush","asset://AlexBrush-Regular-OTF.otf") end function execute(deltaT) sysLoad("asset://List.lua") end function leave() end
--*********************************************************** --** THE INDIE STONE ** --*********************************************************** require "OptionScreens/CharacterCreationMain" ---@class CoopCharacterCreationMain : CharacterCreationMain CoopCharacterCreationMain = CharacterCreationMain:derive("CoopCharacterCreationMain") function CoopCharacterCreationMain:onOptionMouseDown(button, x, y) if button.internal == "BACK" then self:setVisible(false) CharacterCreationProfession.instance:setVisible(true, self.joyfocus) end if button.internal == "NEXT" then self:setVisible(false) CoopCharacterCreation.instance:accept() end if button.internal == "RANDOM" then CharacterCreationHeader.instance:onOptionMouseDown(button, x, y) end end function CoopCharacterCreationMain:new(x, y, width, height) local o = CharacterCreationMain.new(self, x, y, width, height) o:setUIName("CoopCharacterCreationMain") return o end
local nvim = require("nvim") local util = require("fzfmania.util") local fzf_cmd = require("fzf-lua.cmd") local fzf = require("fzf-lua") local fzfgrep = require("fzf-lua.providers.grep") local function op(desc) return { silent = true, desc = desc } end local function _config(opts) if opts.commands then --{{{ local o = op("Show commands") if opts.frontend then vim.keymap.set("n", opts.commands, function() fzf_cmd.load_command("commands") end, o) else vim.keymap.set("n", opts.commands, ":Commands<CR>", o) end end --}}} if opts.history then --{{{ if opts.frontend then vim.keymap.set("n", opts.history, fzf.oldfiles, op("Show history")) else vim.keymap.set("n", opts.history, ":History<CR>", op("Show history")) end end --}}} if opts.files then --{{{ local o = op("Show files") if opts.frontend then vim.keymap.set("n", opts.files, fzf.files, o) else vim.keymap.set("n", opts.files, ":Files<CR>", o) end end --}}} if opts.files_location then --{{{ local o = op("Show all files in home directory") if opts.frontend then vim.keymap.set("n", opts.files_location.key, function() fzf.files({ cwd = opts.files_location.loc }) end, o) else local command = string.format(":Files %s<CR>", opts.files_location.loc) vim.keymap.set("n", opts.files_location.key, command, o) end end --}}} if opts.buffers then --{{{ local o = op("Show buffers") if opts.frontend then vim.keymap.set("n", opts.buffers, fzf.buffers, o) else vim.keymap.set("n", opts.buffers, ":Buffers<CR>", o) end end --}}} if opts.delete_buffers then --{{{ local o = op("Delete buffers") if opts.frontend then vim.keymap.set("n", opts.delete_buffers, util.delete_buffers, o) else vim.keymap.set("n", opts.delete_buffers, util.delete_buffers_native, o) end end --}}} if opts.git_files then --{{{ local o = op("Show files in git (git ls-files)") if opts.frontend then vim.keymap.set("n", opts.git_files, fzf.git_files, o) else vim.keymap.set("n", opts.git_files, ":GitFiles<CR>", o) end end --}}} if opts.buffer_lines then --{{{ local o = op("Grep lines of current buffer") local header = "'<CR>:jumps to line, <C-w>:adds to locallist, <C-q>:adds to quickfix list'" if opts.frontend then vim.keymap.set("n", opts.buffer_lines, function() fzf.blines({ fzf_opts = { ["--header"] = header }, }) end, o) else vim.keymap.set("n", opts.buffer_lines, function() util.lines_grep(util.fzf_actions, header) end, o) end end --}}} if opts.all_buffer_lines then --{{{ local o = op("Search in lines of all open buffers") if opts.frontend then vim.keymap.set("n", opts.all_buffer_lines, fzf.lines, o) else vim.keymap.set("n", opts.all_buffer_lines, ":Lines<CR>", o) end end --}}} if opts.complete_dict then --{{{ -- Replace the default dictionary completion with fzf-based fuzzy completion. vim.keymap.set("i", "<c-x><c-k>", function() vim.fn["fzf#vim#complete"]("cat /usr/share/dict/words-insane") end, op("Dict completion")) end --}}} if opts.complete_path then --{{{ vim.keymap.set("i", opts.complete_path, "<Plug>(fzf-complete-path)", op("Path completion")) end --}}} if opts.complete_line then --{{{ vim.keymap.set("i", opts.complete_line, "<Plug>(fzf-complete-line)", op("Line completion")) end --}}} if opts.spell_suggestion then --{{{ if opts.frontend then vim.keymap.set( "n", opts.spell_suggestion, fzf.spell_suggest, { desc = "Show spell suggestions" } ) else vim.keymap.set("n", opts.spell_suggestion, function() local term = vim.fn.expand("<cword>") vim.fn["fzf#run"]({ source = vim.fn.spellsuggest(term), sink = function(new_term) require("arshlib.quick").normal("n", '"_ciw' .. new_term .. "") end, down = 10, }) end, { desc = "Show spell suggestions" }) end end --}}} if opts.in_files then --{{{ local in_files = opts.in_files local in_files_names = nil if type(in_files) == "table" then in_files_names = in_files[2] in_files = in_files[1] end local o = { desc = "Find in files" } if opts.frontend then vim.keymap.set("n", in_files, fzf.grep_project, o) if in_files_names then vim.keymap.set("n", in_files_names, function() fzf.grep_project({ fzf_opts = { ["--nth"] = "1.." } }) end, o) end else vim.keymap.set("n", in_files, util.ripgrep_search, o) if in_files_names then vim.keymap.set("n", in_files_names, function() util.ripgrep_search("", false, true) end, o) end end end --}}} if opts.in_files_force then --{{{ local in_files_force = opts.in_files_force local in_files_force_name = nil if type(in_files_force) == "table" then in_files_force_name = in_files_force[2] in_files_force = in_files_force[1] end local o = { desc = "Find in files (ignore .gitignore)" } if opts.frontend then vim.keymap.set("n", in_files_force, function() fzf.grep({ search = "", rg_opts = "--no-ignore", fzf_opts = { ["--nth"] = "2.." }, }) end, o) if in_files_force_name then vim.keymap.set("n", in_files_force_name, function() fzf.grep({ search = "", rg_opts = "--no-ignore", fzf_opts = { ["--nth"] = "1.." }, }) end, o) end else vim.keymap.set("n", in_files_force, function() util.ripgrep_search("", true) end, o) if in_files_force_name then vim.keymap.set("n", in_files_force_name, function() util.ripgrep_search("", true, true) end, o) end end end --}}} if opts.incremental_search then --{{{ local o = { desc = "Incremental search with rg" } if opts.frontend then vim.keymap.set("n", opts.incremental_search, function() fzf.live_grep({ exec_empty_query = true }) end, o) else vim.keymap.set("n", opts.incremental_search, function() util.ripgrep_search_incremental("", true) end, o) end end --}}} if opts.current_word then --{{{ local current_word = opts.current_word local current_word_names = nil if type(current_word) == "table" then current_word_names = current_word[2] current_word = current_word[1] end local o = { desc = "Search over current word" } if opts.frontend then vim.keymap.set("n", current_word, function() fzfgrep.grep_cword({ fzf_opts = { ["--nth"] = "2.." } }) end, o) if current_word_names then vim.keymap.set("n", current_word_names, fzfgrep.grep_cword, o) end else vim.keymap.set("n", current_word, function() util.ripgrep_search(vim.fn.expand("<cword>")) end, o) if current_word_names then vim.keymap.set("n", current_word_names, function() util.ripgrep_search(vim.fn.expand("<cword>"), false, true) end, o) end end end --}}} if opts.current_word_force then --{{{ local current_word_force = opts.current_word_force local current_word_force_names = nil if type(current_word_force) == "table" then current_word_force_names = current_word_force[2] current_word_force = current_word_force[1] end local o = { desc = "Search over current word (ignore .gitignore)" } if opts.frontend then vim.keymap.set("n", current_word_force, function() fzfgrep.grep_cword({ rg_opts = "--no-ignore", fzf_opts = { ["--nth"] = "2.." }, }) end, o) if current_word_force_names then vim.keymap.set("n", current_word_force_names, function() fzfgrep.grep_cword({ rg_opts = "--no-ignore", }) end, o) end else vim.keymap.set("n", current_word_force, function() util.ripgrep_search(vim.fn.expand("<cword>"), true) end, o) if current_word_force_names then vim.keymap.set("n", current_word_force_names, function() util.ripgrep_search(vim.fn.expand("<cword>"), true, true) end, o) end end end --}}} if opts.marks then --{{{ local o = { desc = "Show marks" } if opts.frontend then vim.keymap.set("n", opts.marks, fzf.marks, o) else vim.keymap.set("n", opts.marks, ":Marks<CR>", o) end end --}}} if opts.tags then --{{{ vim.keymap.set("n", opts.tags, nvim.ex.BTags, op("Show tags")) end --}}} end return { config = _config, } -- vim: fdm=marker fdl=0
#!/usr/bin/env lua -------------------------------------------------------------------------------- -- @script Lua Module Pre-Loader -- @version 1.1 -- @author Renato Maia <maia@tecgraf.puc-rio.br> -- local assert = assert local ipairs = ipairs local pairs = pairs local select = select local io = require "io" local os = require "os" module("preloader", require "loop.compiler.Arguments") local FILE_SEP = "/" local FUNC_SEP = "_" local OPEN_PAT = "int%s+luaopen_([%w_]+)%s*%(%s*lua_State%s*%*[%w_]*%);" help = false names = false include = {} funcname = "" output = "preload" prefix = "LUAPRELOAD_API" directory = "" _optpat = "^%-(%-?%w+)(=?)(.-)$" _alias = { I = "include", ["-help"] = "help", } for name in pairs(_M) do _alias[name:sub(1, 1)] = name end local start, errmsg = _M(...) if not start or help then if errmsg then io.stderr:write("ERROR: ", errmsg, "\n") end io.stderr:write([[ Lua Module Pre-Loader 1.1 Copyright (C) 2006-2008 Tecgraf, PUC-Rio Usage: ]],_NAME,[[.lua [options] [inputs] [inputs] is a sequence of names that may be header file paths or package names, use the options described below to indicate how they should be interpreted. If no [inputs] is provided then such names are read from the standard input. Options: -d, -directory Directory where the output files should be generated. Its default is the current directory. -I, -i, -include Adds a directory to the list of paths where the header files are searched. -f, -funcname Name of the generated function that pre-loads all library modules. Its default is 'luapreload_' plus the name defined by option '-output'. -n, -names Flag that indicates provided input names are actually package names and not header files. -o, -output Name used to form the name of the files generated. Two files are generated: a source code file with the sufix '.c' with the pre-loading code and a header file with the sufix '.h' with function signatures. Its default is ']],output,[['. -p, -prefix Prefix added to the signature of the functions generated. Its default is ']],prefix,[['. ]]) os.exit(1) end -------------------------------------------------------------------------------- local function escapepattern(pattern) return pattern:gsub("([%^%$%(%)%%%.%[%]%*%+%-%?])", "%%%1") end local filesep = escapepattern(FILE_SEP) local funcsep = escapepattern(FUNC_SEP) local function adjustpath(path) if path ~= "" and not path:find(filesep.."$") then return path..FILE_SEP end return path end local filepath = adjustpath(directory)..output if funcname == "" then funcname = "luapreload_"..output end -------------------------------------------------------------------------------- local function openheader(name) local file, errmsg = io.open(name) if not file then for _, path in ipairs(include) do path = adjustpath(path)..name file, errmsg = io.open(path) if file then break end end end return file, errmsg end -------------------------------------------------------------------------------- local outh = assert(io.open(filepath..".h", "w")) local guard = output:upper():gsub("[^%w]", "_") outh:write([[ #ifndef __]],guard,[[__ #define __]],guard,[[__ #ifndef ]],prefix,[[ #define ]],prefix,[[ #endif ]],prefix,[[ int ]],funcname,[[(lua_State *L); #endif /* __]],guard,[[__ */ ]]) outh:close() -------------------------------------------------------------------------------- local inputs = { select(start, ...) } if #inputs == 0 then for name in io.stdin:lines() do inputs[#inputs+1] = name end end local outc = assert(io.open(filepath..".c", "w")) outc:write([[ #include <lua.h> #include <lauxlib.h> ]]) for i, input in ipairs(inputs) do if names then outc:write('int luaopen_',input:gsub("%.", FUNC_SEP),'(lua_State*);\n') else outc:write('#include "',input,'"\n') end end outc:write([[ #include "]],output,[[.h" ]],prefix,[[ int ]],funcname,[[(lua_State *L) { luaL_findtable(L, LUA_GLOBALSINDEX, "package.preload", ]], #inputs, [[); ]]) local code = [[ lua_pushcfunction(L, luaopen_%s); lua_setfield(L, -2, "%s"); ]] for i, input in ipairs(inputs) do if names then outc:write(code:format(input:gsub("%.", FUNC_SEP), input)) else local input = assert(openheader(input)) local header = input:read("*a") input:close() for func in header:gmatch(OPEN_PAT) do outc:write(code:format(func, func:gsub(funcsep, "."))) end end end outc:write([[ lua_pop(L, 1); return 0; } ]]) outc:close()
local function github(user, repo, branch, file, name) local url = "https://github.com/"..textutils.urlEncode(user).."/"..textutils.urlEncode(repo).."/raw/"..textutils.urlEncode(branch).."/"..textutils.urlEncode(file) shell.run("wget",url,name) end local function pastebin(paste, file) shell.run("pastebin","get",paste,file) end pastebin("4nRg9CHU","json.lua") github("justync7","jua","master","jua.lua","jua.lua") github("justync7","w.lua","master","w.lua","w.lua") github("justync7","r.lua","master","r.lua","r.lua") github("justync7","k.lua","master","k.lua","k.lua") github("justync7","k.lua","master","example.lua","kexample.lua") print("Bootstrapped! You now have the proper dependencies and kexample.lua in your current directory.")
-- FILE: alt_set_1000.lua -- VERSION: 1.0 -- AUTHOR: Carsten Lynker -- DESCRIPTION: Will increase or decrese the value of the autopilot's altitude setting -- to the next 1000th, to tune in the values more effective. -- You can easily modify this script to change the step size. -- set the dataref ALT to read and write the altitude tuned into the autopilot dataref("ALT", "sim/cockpit2/autopilot/altitude_dial_ft", "writable") -- create a command to increase the altitude value of the autopilot create_command("FlyWithLua/autopilot/inc_alt_1000", "Increase the altitude to the next 1000 value", "ALT = math.floor(ALT / 1000 + 1) * 1000", "", "") -- create a command to increase the altitude value of the autopilot create_command("FlyWithLua/autopilot/dec_alt_1000", "Decrease the altitude to the next 1000 value", "ALT = math.floor( (ALT - 1) / 1000) * 1000", "", "")
function onCreate() -- background shit makeLuaSprite('eteledstageback1', 'eteledstageback1', -600, -300); setScrollFactor('stageback', 0.9, 0.9); makeAnimatedLuaSprite('miibuttons','miibuttons',-350,0)addAnimationByPrefix('miibuttons','dance','miibuttons anim',6,true) objectPlayAnimation('miibuttons','dance',false) setScrollFactor('miibuttons', 0.9, 0.9); addLuaSprite('eteledstageback1', false); addLuaSprite('miibuttons', true); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
if SERVER then AddCSLuaFile() end SWEP.Author = "add___123" SWEP.Base = "weapon_base" SWEP.PrintName = "Light SMG" SWEP.Instructions = "" SWEP.ViewModel = "models/weapons/c_smg1.mdl" SWEP.WorldModel = "models/weapons/w_smg1.mdl" SWEP.ViewModelFlip = false SWEP.UseHands = true SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.Slot = 1 SWEP.SlotPos = 4 SWEP.DrawAmmo = true SWEP.DrawCrosshair = true SWEP.Spawnable = false SWEP.AdminSpawnable = false SWEP.Primary.ClipSize = 30 SWEP.Primary.DefaultClip= 30 SWEP.Primary.Ammo = "SMG1" SWEP.Primary.Recoil = 0.25 SWEP.Primary.Damage = 15 SWEP.Primary.Spread = 0.03 SWEP.Primary.Delay = 0.1 SWEP.Primary.Automatic = true SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Ammo = "none" SWEP.Secondary.Automatic= false SWEP.ShouldDropOnDie = false local shootSound = "weapons/smg1/smg1_fire1.wav" function SWEP:Initialize() self:SetHoldType("smg") end function SWEP:PrimaryAttack() if self:CanPrimaryAttack() then local ply = self:GetOwner() ply:EmitSound(shootSound, 100, 100, 0.25) self:SetNextPrimaryFire(CurTime() + self.Primary.Delay) self:SendWeaponAnim(ACT_VM_PRIMARYATTACK) ply:SetAnimation(PLAYER_ATTACK1) local mult = 1 if ply:GetModel() == "models/player/police.mdl" then mult = 1.2 end local bullet = { Num = self.Primary.NumShots, Src = ply:GetShootPos(), Dir = ply:GetAimVector(), Spread = Vector(self.Primary.Spread, self.Primary.Spread, 0), Tracer = 1, TracerName = "AirboatGunTracer", Force = 1000, Damage = self.Primary.Damage * mult, AmmoType = self.Primary.Ammo, } ply:FireBullets(bullet) self:TakePrimaryAmmo(1) ply:ViewPunch(Angle(-1 * self.Primary.Recoil, math.random(-0.2, 0.2) * self.Primary.Recoil, 0)) self:ShootEffects() else self:Reload() end end function SWEP:Reload() local ply = self:GetOwner() self:SetNextPrimaryFire(CurTime() + 1.5) self:DefaultReload( ACT_VM_RELOAD ) ply:SetAnimation(PLAYER_RELOAD) self:EmitSound("weapons/smg1/smg1_reload.wav") timer.Simple(1.5, function() if IsValid(ply) and IsValid(self) then ply:SetAmmo(self.Primary.ClipSize, self.Primary.Ammo) end end) end function SWEP:CanSecondaryAttack() return false end function SWEP:Deploy() local ply = self:GetOwner() ply:SetAmmo(self.Primary.ClipSize, self.Primary.Ammo) end
AddCommand("ban", function(player, dest, reason) if PLAYER_HAVE_PERMISSION(player, "essential.ban") == false then MessageChat(player, 4, " You don't haver permission to execute this commande !") return end if dest == nil then MessageChat(player, 4, " syntaxe error /ban [player] ([reason]) !") return end if PlayerData[tonumber(dest)] == nil then MessageChat(player, 4, " "..dest.." is not valide player !") return end PLAYER_BAN(tonumber(dest), reason) MessageChat(player, 3, "Player "..GetPlayerName(dest).." has ben ban frome the server !") end) AddCommand("unban", function(player, steamId) if PLAYER_HAVE_PERMISSION(player, "essential.unban") == false then MessageChat(player, 4, " You don't haver permission to execute this commande !") return end if steamId == nil then MessageChat(player, 4, " syntaxe error /unban [steamId] !") return end PLAYER_UNBAN(steamId) MessageChat(player, 3, steamId.." has ben unban frome the server !") end)
--Copyright (C) 2009 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --which carries forward this exception. object_installation_mining_liquid_shared_mining_liquid_harvester_style_1 = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_mining_liquid_harvester_style_1.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/ins_all_mobile_chem_refinery.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "clientdata/installation/client_shared_mining_liquid_harvester_style_1.cdf", clientGameObjectType = 4099, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "", gameObjectType = 4099, locationReservationRadius = 0, lookAtText = "", noBuildRadius = 0, objectName = "@installation_n:liquid_mine", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/mining_liquid/shared_mining_liquid_harvester_style_1.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 2015682736, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff", "object/installation/mining_liquid/base/shared_mining_liquid_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_mining_liquid_harvester_style_1, "object/installation/mining_liquid/shared_mining_liquid_harvester_style_1.iff") object_installation_mining_liquid_shared_mining_liquid_harvester_style_2 = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_mining_liquid_harvester_style_2.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/ins_all_min_liquid_s01_u0.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "clientdata/installation/client_shared_mining_liquid_harvester_style_2.cdf", clientGameObjectType = 4099, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "", gameObjectType = 4099, locationReservationRadius = 0, lookAtText = "", noBuildRadius = 0, objectName = "@installation_n:liquid_mine_medium", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/mining_liquid/shared_mining_liquid_harvester_style_2.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 2738047015, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff", "object/installation/mining_liquid/base/shared_mining_liquid_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_mining_liquid_harvester_style_2, "object/installation/mining_liquid/shared_mining_liquid_harvester_style_2.iff") object_installation_mining_liquid_shared_mining_liquid_harvester_style_3 = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_mining_liquid_harvester_style_3.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/ins_all_creature_farm_s01_u0.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "clientdata/installation/client_shared_mining_organic_creature_farm.cdf", clientGameObjectType = 4099, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "", gameObjectType = 4099, locationReservationRadius = 0, lookAtText = "", noBuildRadius = 0, objectName = "@installation_n:liquid_mine_heavy", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/mining_liquid/shared_mining_liquid_harvester_style_3.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 3929943978, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff", "object/installation/mining_liquid/base/shared_mining_liquid_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_mining_liquid_harvester_style_3, "object/installation/mining_liquid/shared_mining_liquid_harvester_style_3.iff") object_installation_mining_liquid_shared_mining_liquid_moisture_harvester = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_mining_liquid_moisture_harvester.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/ins_all_min_moisture_s01_u0.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "clientdata/installation/client_shared_mining_moisture_harvester_style_1.cdf", clientGameObjectType = 4099, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "", gameObjectType = 4099, locationReservationRadius = 0, lookAtText = "", noBuildRadius = 0, objectName = "@installation_n:moisture_mine", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/mining_liquid/shared_mining_liquid_moisture_harvester.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 2235626870, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff", "object/installation/mining_liquid/base/shared_mining_liquid_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_mining_liquid_moisture_harvester, "object/installation/mining_liquid/shared_mining_liquid_moisture_harvester.iff") object_installation_mining_liquid_shared_mining_liquid_moisture_harvester_heavy = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_mining_liquid_moisture_harvester_heavy.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/ins_all_moisture_lrg.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "", clientGameObjectType = 4099, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "", gameObjectType = 4099, locationReservationRadius = 0, lookAtText = "", noBuildRadius = 0, objectName = "@installation_n:moisture_mine_heavy", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/mining_liquid/shared_mining_liquid_moisture_harvester_heavy.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 1305511934, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff", "object/installation/mining_liquid/base/shared_mining_liquid_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_mining_liquid_moisture_harvester_heavy, "object/installation/mining_liquid/shared_mining_liquid_moisture_harvester_heavy.iff") object_installation_mining_liquid_shared_mining_liquid_moisture_harvester_medium = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_mining_liquid_moisture_harvester_medium.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/ins_all_moisture_med.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "", clientGameObjectType = 4099, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "", gameObjectType = 4099, locationReservationRadius = 0, lookAtText = "", noBuildRadius = 0, objectName = "@installation_n:moisture_mine_medium", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/mining_liquid/shared_mining_liquid_moisture_harvester_medium.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 3152239258, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff", "object/installation/mining_liquid/base/shared_mining_liquid_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_mining_liquid_moisture_harvester_medium, "object/installation/mining_liquid/shared_mining_liquid_moisture_harvester_medium.iff") object_installation_mining_liquid_shared_resource_harvester = SharedInstallationObjectTemplate:new { clientTemplateFileName = "object/installation/mining_liquid/shared_resource_harvester.iff" --Data below here is deprecated and loaded from the tres, keeping for easy lookups --[[ appearanceFilename = "appearance/tatt_ming_hydro_evaporator.apt", arrangementDescriptorFilename = "", certificationsRequired = {}, clearFloraRadius = 15, clientDataFile = "", clientGameObjectType = 4096, collisionActionBlockFlags = 0, collisionActionFlags = 51, collisionActionPassFlags = 1, collisionMaterialBlockFlags = 0, collisionMaterialFlags = 1, collisionMaterialPassFlags = 0, containerType = 0, containerVolumeLimit = 1, customizationVariableMapping = {}, detailedDescription = "@item_n:default_craftable", gameObjectType = 4096, locationReservationRadius = 0, lookAtText = "string_id_table", noBuildRadius = 0, objectName = "@string_table:Moisture Harvester", onlyVisibleInTools = 0, paletteColorCustomizationVariables = {}, portalLayoutFilename = "", rangedIntCustomizationVariables = {}, scale = 1, scaleThresholdBeforeExtentTest = 0.5, sendToClient = 1, slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff", snapToTerrain = 1, socketDestinations = {}, structureFootprintFileName = "footprint/installation/base/shared_installation_base.sfp", surfaceType = 1, targetable = 1, totalCellNumber = 0, useStructureFootprintOutline = 0, clientObjectCRC = 860426391, derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/installation/base/shared_installation_base.iff"} ]] } ObjectTemplates:addClientTemplate(object_installation_mining_liquid_shared_resource_harvester, "object/installation/mining_liquid/shared_resource_harvester.iff")
print('hello world') -- define a function function fact(n) if n == 0 then return 1 else return n * fact(n - 1) end end --print('Enter a number:') --num = io.read('*n') num = 3 print(fact(num)) --block comments --[[ print(10) --]] print(b) b = 22 print(b) b = nil print(b) -- 1.1 function fact2(n) if n < 0 then print('Bad entry, factorials are for positives.') elseif n == 0 then return 1 else return n * fact2(n - 1) end end print(fact2(-2)) -- 1.4 print('Valid Names:') print('___ _end END NULL') -- 1.5 print('Filename is: ', arg[0])
local UniversalAppOnWindows = game:GetEngineFeature("UniversalAppOnWindows") game:DefineFastFlag("InGameMenuOpenOnHover", false) return function() return UniversalAppOnWindows and game:GetFastFlag("InGameMenuOpenOnHover") end
----------------------------------- -- Area: Grauberg [S] -- Mob: Ajattara -- Note: PH for Scitalis ----------------------------------- local ID = require("scripts/zones/Grauberg_[S]/IDs") require("scripts/globals/mobs") ----------------------------------- function onMobDeath(mob, player, isKiller) end function onMobDespawn(mob) tpz.mob.phOnDespawn(mob, ID.mob.SCITALIS_PH, 5, 3600) -- 1 hour end
Action = {} local bot = GetBot() local NEARBY_RADIUS = 1500 local ACTION_MOVE = 0 local ACTION_ATTACK_HERO = 1 local ACTION_ATTACK_CREEP = 2 local ACTION_USE_ABILITY = 3 local ACTION_ATTACK_TOWER = 4 local ACTION_MOVE_DISCRETE = 5 local ACTION_DO_NOTHING = 6 local last_time_move = GameTime() local wrong_action = 0 local ABILITY = { bot:GetAbilityByName('nevermore_shadowraze1'), bot:GetAbilityByName('nevermore_shadowraze2'), bot:GetAbilityByName('nevermore_shadowraze3'), bot:GetAbilityByName('nevermore_requiem') } function Action.last_time_moved() return last_time_move end --- Move by the delta vector. -- @param delta_vector -- function move_delta(delta_vector) print('MOVE DELTA', delta_vector[1], delta_vector[2]) last_time_move = GameTime() local position = bot:GetLocation() position[1] = position[1] + delta_vector[1] position[2] = position[2] + delta_vector[2] bot:Action_MoveToLocation(position) end --- Move towards the specified angle. -- @param direction value from 0-15 that maps to direction/8*pi -- function move_discrete(direction) print('MOVE DISCRETE', direction) local radius = 150 local angle = direction * (math.pi / 8) local cos_theta = math.cos(angle) local sin_theta = math.sin(angle) move_delta({ radius * cos_theta, radius * sin_theta }) end --- Use ability. -- @param ability_idx index of ability in 'ABILITY' table. -- function use_ability(ability_idx) print('USE ABILITY', ability_idx) local ability = ABILITY[ability_idx] if ability:IsFullyCastable() then bot:Action_UseAbility(ability) else wrong_action = 1 end end --- Attack the closest enemy hero nearby. function attack_hero() print('ATTACK HERO') local enemy_heroes_list = bot:GetNearbyHeroes(NEARBY_RADIUS, true, BOT_MODE_NONE) if #enemy_heroes_list > 0 then bot:Action_AttackUnit(enemy_heroes_list[1], false) else wrong_action = 1 end end --- Attack enemy creep. -- @param creep_idx index of creep in nearby creeps table. -- function attack_creep(creep_idx) print('ATTACK CREEP', creep_idx) local enemy_creeps = bot:GetNearbyCreeps(NEARBY_RADIUS, true) if #enemy_creeps >= creep_idx then bot:Action_AttackUnit(enemy_creeps[creep_idx], false) else wrong_action = 1 end end -- Attack nearby enemy tower. function attack_tower() print('ATTACK TOWER') local towers = bot:GetNearbyTowers(NEARBY_RADIUS, true) if #towers > 0 then bot:Action_AttackUnit(towers[1], false) else wrong_action = 1 end end -- Take all available abilities' upgrades. function upgrade_abilities() for _, ability in ipairs(ABILITY) do if ability:CanAbilityBeUpgraded() then bot:ActionImmediate_LevelAbility(ability:GetName()) end end end --- Execute given action. -- @param action_info action info {'action': action id, 'params': action parameters} -- function Action.execute_action(action_info) local action = action_info['action'] local action_params = action_info['params'] wrong_action = 0 upgrade_abilities() if action == ACTION_MOVE then -- Consider params[1], params[2] as x, y of a delta vector move_delta(action_params) elseif action == ACTION_MOVE_DISCRETE then -- Move towards the angle computed as (params[1] / 8 * pi) move_discrete(action_params[1]) elseif action == ACTION_USE_ABILITY then -- Consider params[1] as an ability index use_ability(action_params[1]) elseif action == ACTION_ATTACK_HERO then -- Attacks the closest enemy hero. attack_hero() elseif action == ACTION_ATTACK_CREEP then -- Consider params[1] as an index in the nearby creeps table attack_creep(action_params[1]) elseif action == ACTION_ATTACK_TOWER then -- Attacks the closes enemy tower. attack_tower() elseif action == ACTION_DO_NOTHING then -- do nothing end return wrong_action end return Action;
MLIB = MLIB or {} MLIB.Installed = true MLIB.Verison = "v2.0.3" WSG = {} function MLIB.Print(...) MsgC(Color(225, 20, 30), "[MLIB - " ..MLIB.Verison.." ] ", Color(129, 225, 20), ..., "\n\r") end hook.Add("ROOKI_load_prio_register", "rooki_loadutils", function() rookiutil.new("Edge HUD Utils", { { Autoload = true, -- Ob es automatisch CL, SH und SV erkennen soll muss natürlich genormt sein deswegen! Path = "rooki_modules", -- Jaaa hmmm........ zur relation von lua/ Realm = ROOKI.realms.ROOKI_CLIENT -- Ist beim Autoload "useless" }, }, { Active = true }) end)
local lwtk = require"lwtk" local call = lwtk.call local ChildLookup = lwtk.ChildLookup local getParent = lwtk.get.parent local getChildLookup = lwtk.get.childLookup local getStyle = lwtk.get.style local Super = lwtk.MouseDispatcher(lwtk.Compound(lwtk.Widget)) local Group = lwtk.newClass("lwtk.Group", Super) local Super_addChild = Super.addChild function Group:new(initParams) Super.new(self) getChildLookup[self] = ChildLookup(self) local childList = {} if initParams then for i = 1, #initParams do childList[#childList + 1] = initParams[i] initParams[i] = nil end end for i = 1, #childList do self:addChild(childList[i]) end self:setInitParams(initParams) end function Group:_clearChildLookup() ChildLookup.clear(getChildLookup[self]) local p = getParent[self] if p then p:_clearChildLookup() end end function Group:childById(id) local id1, id2 = id:match("^([^/]*)/(.*)$") if id1 then local c = getChildLookup[self][id1] if c and c.childById then return c:childById(id2) end else return getChildLookup[self][id] end end function Group:addChild(child) Super_addChild(self, child) self:_clearChildLookup() local style = getStyle[self] if style then call("_setStyleFromParent", child, style) end self:triggerLayout() return child end return Group
local ReplicatedStorage = game:GetService("ReplicatedStorage") local lib = ReplicatedStorage.lib local common = ReplicatedStorage.common local util = common.util local Dictionary = require(util.Dictionary) local RECS = require(lib.RECS) return RECS.defineComponent({ name = "Rig", generator = function(props) return Dictionary.join({ rigModel = nil, }, props) end, })
local ReactFiberScheduler = require "ReactFiberScheduler" local pi = require "pi" pi(ReactFiberScheduler)
local dap = require'dap' dap.adapters.node2 = { type = 'executable', command = 'node', args = {os.getenv('HOME') .. '/vscode-node-debug2/out/src/nodeDebug.js'}, } dap.configurations.javascript = { { type = 'node2', request = 'launch', program = '${file}', cwd = vim.fn.getcwd(), sourceMaps = true, protocol = 'inspector', console = 'integratedTerminal', }, } vim.fn.sign_define('DapBreakpoint', {text='🛑', texthl='', linehl='', numhl=''}) vim.fn.sign_define('DapStopped', {text='🟢', texthl='', linehl='', numhl=''}) local nvim_set_keymap = vim.api.nvim_set_keymap local opts = {noremap = true, silent = true} nvim_set_keymap('n', '<F5>', ':lua require\'dap\'.continue()<CR>', opts) nvim_set_keymap('n', '<F10>', ':lua require\'dap\'.step_over()<CR>', opts) nvim_set_keymap('n', '<F11>', ':lua require\'dap\'.step_into()<CR>', opts) nvim_set_keymap('n', '<F12>', ':lua require\'dap\'.step_out()<CR>', opts) nvim_set_keymap('n', '<leader>b', ':lua require\'dap\'.toggle_breakpoint()<CR>', opts) nvim_set_keymap('n', '<leader>B', ':lua require\'dap\'.set_breakpoint(vim.fn.input(\'Breakpoint condition: \'))<CR>', opts) nvim_set_keymap('n', '<leader>lp', ':lua require\'dap\'.set_breakpoint(nil, nil, vim.fn.input(\'Log point message: \'))<CR>', opts) nvim_set_keymap('n', '<leader>dr', ':lua require\'dap\'.repl.open()<CR>', opts) nvim_set_keymap('n', '<leader>dl', ':lua require\'dap\'.run_last()<CR>', opts)
-- -*- coding:utf-8; -*- --- misc/ip.lua -- @script ip -- @author:phenix3443@gmail.com -- bin/resty --shdict "falcon 20m" --errlog-level debug --http-include nginx/lua/test/test.nginx.conf nginx/lua/test/mmdb_helper.lua local sp = require("serpent") local lu = require("luaunit") local MMH = require("misc.mmdb_helper") local city_db = ngx.config.prefix() .. "lua/misc/GeoLite2-City.mmdb" local asn_db = ngx.config.prefix() .. "lua/misc/GeoLite2-ASN.mmdb" local mmh = MMH(city_db, asn_db) _G.test_mm_helper = {} function test_mm_helper:setUp() end function test_mm_helper:test_get_city_info_ipv4() local ip = "223.255.254.254" local info = mmh:get_city_info(ip) -- print(sp.block(info)) lu.assertNotNil(info) end function test_mm_helper:test_get_city_info_invalid_ipv4() local ip = "127.0.0.1" local info = mmh:get_city_info(ip) lu.assertNil(info) end function test_mm_helper:test_get_city_info_ipv6() local ip = "2607:f8b0:4004:801::100e" local info = mmh:get_city_info(ip) lu.assertNotNil(info) -- print(sp.block(info)) end function test_mm_helper:test_get_isp_info_ipv4() local ip = "223.255.254.254" local info = mmh:get_isp_info(ip) lu.assertNotNil(info) -- print(sp.block(info)) end function test_mm_helper:test_get_isp_info_ipv6() local ip = "2607:f8b0:4004:801::100e" local info = mmh:get_isp_info(ip) lu.assertNotNil(info) -- print(sp.block(info)) end os.exit(lu.LuaUnit.run())
IngameMenuUpperSpaceComposition = IngameMenuUpperSpaceComposition or {} function IngameMenuUpperSpaceComposition.Create(_ARG_0_, _ARG_1_) local oComposition = IngameMenuUpperSpaceComposition.CreateIngameMenuUpperSpaceComposition(_ARG_0_, _ARG_1_) return oComposition end function IngameMenuUpperSpaceComposition.CreateIngameMenuUpperSpaceComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = IngameMenuUpperSpaceComposition.CreateSpecialAbilitiesIconsComposition("SpecialAbilitiesIconsComposition", {X = "0.00000", Y = "0.00000", SizeX = "0.18750", SizeY = "0.25000", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateStatusComposition("StatusComposition", { X = "0.18750", Y = "0.00000", SizeX = "1.01875", SizeY = "0.26667", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateSpecialAbilitiesIconsComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("Background", "CSprite", { X = "0.00000", Y = "0.00000", SizeX = "0.18750", SizeY = "0.25000", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "0.14000", ColorG = "0.14000", ColorB = "0.14000", ColorA = "0.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "WhiteSquare", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateAbilitySelectorComposition("AbilitiesSelector", { X = "0.00000", Y = "0.00833", SizeX = "0.16875", SizeY = "0.22500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateAbilitySelectorComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("CancelTL", "CSprite", { X = "0.01563", Y = "0.03750", SizeX = "0.06875", SizeY = "0.09167", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Cancel12", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("CancelTR", "CSprite", { X = "0.08438", Y = "0.03750", SizeX = "0.06875", SizeY = "0.09167", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Cancel12", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("CancelBL", "CSprite", { X = "0.01563", Y = "0.12917", SizeX = "0.06875", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000",FlipX = false, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Cancel12", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("CancelBR", "CSprite", { X = "0.08438", Y = "0.12917", SizeX = "0.06875", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Cancel12", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateScanningPulseComposition("ScanningPulse", { X = "0.03750", Y = "0.01667", SizeX = "0.08750", SizeY = "0.12500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateEnergyShieldComposition("EnergyShield", { X = "0.00000", Y = "0.06667", SizeX = "0.08125", SizeY = "0.12500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateEnergyWaveComposition("EnergyWave", { X = "0.10625", Y = "0.06667", SizeX = "0.08125", SizeY = "0.12500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreatePhaseDisplacementComposition("PhaseDisplacement", { X = "0.03750", Y = "0.15833", SizeX = "0.08750", SizeY = "0.12500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ClosureTL", "CSprite", { X = "0.02813", Y = "0.05417", SizeX = "0.01563", SizeY = "0.02083", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Close", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ClosureTR", "CSprite", { X = "0.12500", Y = "0.05417", SizeX = "0.01562", SizeY = "0.02083", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Close", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ClosureBL", "CSprite", { X = "0.02813", Y = "0.18334", SizeX = "0.01562", SizeY = "0.02083", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Close", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ClosureBR", "CSprite", { X = "0.12500", Y = "0.18334", SizeX = "0.01562", SizeY = "0.02083", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Close", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale"}) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateScanningPulseComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("FX_Static", "CSprite", { X = "0.08750", Y = "0.00417", SizeX = "0.08125", SizeY = "0.07083", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "1.57044", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = true, SpriteSheetItem = "FX_Base", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FX_Dynamic", "CSprite", { X = "0.08750", Y = "0.00417", SizeX = "0.05312", SizeY = "0.10833", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "1.56999", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "WhiteSquare", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Frame", "CSprite", { X = "0.09375", Y = "0.00000", SizeX = "0.08125", SizeY = "0.12499", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "1.57027", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Normal", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Icon", "CSprite", { X = "0.02500", Y = "0.00417", SizeX = "0.04687", SizeY = "0.06250", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "IconS_ScanningPulse", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateEnergyShieldComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("FX_Static", "CSprite", { X = "0.00313", Y = "0.00833", SizeX = "0.05312", SizeY = "0.10834", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = true, SpriteSheetItem = "FX_Base", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale"}) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FX_Dynamic", "CSprite", { X = "0.00313", Y = "0.00833", SizeX = "0.05312", SizeY = "0.10834", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "WhiteSquare", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Frame", "CSprite", { X = "0.00000", Y = "0.00000", SizeX = "0.08125", SizeY = "0.12500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Normal", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Icon", "CSprite", { X = "0.00313", Y = "0.03333", SizeX = "0.04687", SizeY = "0.06250", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "IconS_EnergyShield", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateEnergyWaveComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("FX_Static", "CSprite", { X = "0.00625", Y = "0.00834", SizeX = "0.05312", SizeY = "0.10833", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = true, SpriteSheetItem = "FX_Base", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FX_Dynamic", "CSprite", { X = "0.00625", Y = "0.00834", SizeX = "0.05312", SizeY = "0.10833", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "WhiteSquare", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Frame", "CSprite", { X = "-0.01875", Y = "-0.00000", SizeX = "0.08125", SizeY = "0.12500", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Normal", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Icon", "CSprite", { X = "0.01250", Y = "0.03333", SizeX = "0.04687", SizeY = "0.06250", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "IconS_EnergyWave", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreatePhaseDisplacementComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("FX_Static", "CSprite", { X = "0.00625", Y = "0.07917", SizeX = "0.08125", SizeY = "0.07083", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "-1.57044", FlipX = false, FlipY = false,Enabled = true, SkinItemType = "", Autosize = true, SpriteSheetItem = "FX_Base", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FX_Dynamic", "CSprite", { X = "0.00625", Y = "0.07917", SizeX = "0.05312", SizeY = "0.10833", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "-1.56999", FlipX = false, FlipY = false,Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "WhiteSquare", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Frame", "CSprite", { X = "0.00000", Y = "0.08333", SizeX = "0.08125", SizeY = "0.12499", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "-1.57027", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ButtonSpecialHabilities_Normal", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Icon", "CSprite", { X = "0.02500", Y = "0.01667", SizeX = "0.04687", SizeY = "0.06250", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "IconS_PhaseDisplacement", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateStatusComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = IngameMenuUpperSpaceComposition.CreateUpperScreenHighlightComposition("UpperScreenHighlight", { X = "-0.03141", Y = "-0.21458", SizeX = "-0.03141", SizeY = "-0.21458", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "0.00000", ColorG = "0.00000", ColorB = "0.00000", ColorA = "1.00000" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("BackgroundOrnamentUpLeftLower", "CSprite", { X = "-0.20625", Y = "0.08750", SizeX = "0.49375", SizeY = "0.10000", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Head_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale"}) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("BackgroundOrnamentUpRightLower", "CSprite", { X = "0.28750", Y = "0.08750", SizeX = "0.49375", SizeY = "0.10000", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Head_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("BackgroundOrnamentUpRightUpper", "CSprite", { X = "0.33125", Y = "-0.00416", SizeX = "0.49999", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Head_A", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("BackgroundOrnamentUpLeftUpper", "CSprite", { X = "-0.25624", Y = "-0.00416", SizeX = "0.49999", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Head_A", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateEnergyTanksContainerComposition("EnergyTanksContainerComposition", { X = "0.09062", Y = "0.02083", SizeX = "0.29688", SizeY = "0.08750", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("EnergyCounter", "CText", { X = "0.01250", Y = "0.00833", SizeX = "0.06876", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Text = "test", Font = "digital_big", TextAlignment = "Right", Autosize = false, Outline = false, EmbeddedSpritesSuffix = "", BlinkColorR = "1.00000", BlinkColorG = "1.00000", BlinkColorB = "1.00000", BlinkAlpha = "1.00000", Blink = "-1.00000" }) oContainer:AddChild(oChild) oChild = IngameMenuUpperSpaceComposition.CreateSpecialEnergyBarComponentsComposition("SpecialEnergyBarComponents", { X = "-0.01250", Y = "0.15833", SizeX = "0.52187", SizeY = "0.08333", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ReserveTankE", "CSprite", { X = "0.38125", Y = "0.02083", SizeX = "0.05312", SizeY = "0.05416", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ReseveTank_E_Empty", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ReserveTankS", "CSprite", { X = "0.44375", Y = "0.02083", SizeX = "0.05312", SizeY = "0.05416", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ReseveTank_S_Empty", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("ReserveTankM", "CSprite", { X = "0.50625", Y = "0.02083", SizeX = "0.05312", SizeY = "0.05416", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "ReseveTank_M_Empty", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("MissilesSelection", "CSprite", { X = "0.06250", Y = "0.09167", SizeX = "0.15001", SizeY = "0.06249", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Weaponflare", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SuperMissilesSelection", "CSprite", { X = "0.23125", Y = "0.09167", SizeX = "0.13125", SizeY = "0.06249", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Weaponflare", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("PowerBombsSelection", "CSprite", { X = "0.38125", Y = "0.09167", SizeX = "0.13126", SizeY = "0.06249", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Weaponflare", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SGI_Missile", "CSprite", { X = "0.07500", Y = "0.10000", SizeX = "0.02501", SizeY = "0.04583", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Icon_Missiles", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SGC_Missile", "CText", { X = "0.10938", Y = "0.07917", SizeX = "0.10001", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "0.76000", ColorG = "0.90000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Text = "250", Font = "digital_hefty", TextAlignment = "Left", Autosize = false, Outline = false, EmbeddedSpritesSuffix = "", BlinkColorR = "1.00000", BlinkColorG = "1.00000", BlinkColorB = "1.00000", BlinkAlpha = "1.00000", Blink = "-1.00000" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SGI_SuperMissile", "CSprite", { X = "0.24375", Y = "0.10000", SizeX = "0.04063", SizeY = "0.04583", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Icon_SuperMissiles", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SGC_SuperMissile", "CText", { X = "0.29375", Y = "0.07917", SizeX = "0.06564", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "0.76000", ColorG = "0.90000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Text = "50", Font = "digital_hefty", TextAlignment = "Left", Autosize = false, Outline = false, EmbeddedSpritesSuffix = "", BlinkColorR = "1.00000", BlinkColorG = "1.00000", BlinkColorB = "1.00000", BlinkAlpha = "1.00000", Blink = "-1.00000" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SGI_PowerBomb", "CSprite", { X = "0.39375", Y = "0.10000", SizeX = "0.03750", SizeY = "0.04583", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Icon_PowerBombs", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SGC_PowerBomb", "CText", { X = "0.44062", Y = "0.07917", SizeX = "0.06564", SizeY = "0.09166", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "0.76000", ColorG = "0.90000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Text = "30", Font = "digital_hefty", TextAlignment = "Left", Autosize = false, Outline = false, EmbeddedSpritesSuffix = "", BlinkColorR = "1.00000", BlinkColorG = "1.00000", BlinkColorB = "1.00000", BlinkAlpha = "1.00000", Blink = "-1.00000" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("EnergyFlare", "CSprite", { X = "-0.04688", Y = "-0.00833", SizeX = "0.48440", SizeY = "0.12498", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_01", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FlareReserveTankE", "CSprite", { X = "0.34687", Y = "0.00417", SizeX = "0.12501", SizeY = "0.10415", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = false, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_02", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FlareReserveTankA", "CSprite", { X = "0.40937", Y = "0.00417", SizeX = "0.12501", SizeY = "0.10415", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = false, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_02", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FlareReserveTankM", "CSprite", { X = "0.47187", Y = "0.00417", SizeX = "0.12501", SizeY = "0.10415", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = false, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_02", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("FlareSE", "CSprite", { X = "0.02813", Y = "0.14167", SizeX = "0.53128", SizeY = "0.12498", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_01", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("MissilesFlare", "CSprite", { X = "0.05000", Y = "0.07917", SizeX = "0.17189", SizeY = "0.10415", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_02", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SuperMissilesFlare", "CSprite", { X = "0.21563", Y = "0.07917", SizeX = "0.15626", SizeY = "0.10415", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_02", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("PowerBombsFlare", "CSprite", { X = "0.36875", Y = "0.07917", SizeX = "0.15626", SizeY = "0.10415", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Flare_02", BlendMode = "Additive", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateUpperScreenHighlightComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateEnergyTanksContainerComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("Tank7", "CSprite", { X = "0.15625", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank8", "CSprite", { X = "0.18438", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank6", "CSprite", { X = "0.12812", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank9", "CSprite", { X = "0.21250", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank10", "CSprite", { X = "0.24063", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank2", "CSprite", { X = "0.01563", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank3", "CSprite", { X = "0.04375", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank1", "CSprite", { X = "-0.01250", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank4", "CSprite", { X = "0.07187", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("Tank5", "CSprite", { X = "0.10000", Y = "-0.01667", SizeX = "0.04376", SizeY = "0.08752", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "1.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end function IngameMenuUpperSpaceComposition.CreateSpecialEnergyBarComponentsComposition(_ARG_0_, _ARG_1_) local oContainer = GUI.CreateDisplayObjectEx(_ARG_0_, "CDisplayObjectContainer", {}) local oChild = nil oChild = GUI.CreateDisplayObjectEx("LineBarsLow_01", "CSprite", { X = "0.03125", Y = "0.02917", SizeX = "0.11250", SizeY = "0.06666", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "LineBarsLow_01", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Max_Middle", "CSprite", { X = "0.08125", Y = "0.03333", SizeX = "0.43750", SizeY = "0.01666", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "0.07000", ColorG = "0.25000", ColorB = "0.34000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "WhiteSquare", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("LineBarsLow_00", "CSprite", { X = "-0.00625", Y = "0.01250", SizeX = "0.04063", SizeY = "0.03750", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "LineBarsLow_05", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("LineBarsLow_03", "CSprite", { X = "0.44063", Y = "0.05417", SizeX = "0.06562", SizeY = "0.03750", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "LineBarsLow_03", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("LineBarsLow_02", "CSprite", { X = "0.14375", Y = "0.05417", SizeX = "0.29686", SizeY = "0.03750", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "LineBarsLow_02", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Previous_Left", "CSprite", { X = "0.06563", Y = "0.01667", SizeX = "0.01563", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "0.00000", ColorB = "0.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_01_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Previous_Middle", "CSprite", { X = "0.08125", Y = "0.01667", SizeX = "0.43748", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "0.00000", ColorB = "0.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_01", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Previous_Right", "CSprite", { X = "0.51875", Y = "0.01668", SizeX = "0.01563", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, ColorR = "1.00000", ColorG = "0.00000", ColorB = "0.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_01_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Current_Left", "CSprite", { X = "0.06563", Y = "0.01667", SizeX = "0.01563", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "0.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_01_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Current_Middle", "CSprite", { X = "0.08125", Y = "0.01667", SizeX = "0.43748", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, ColorR = "1.00000", ColorG = "1.00000", ColorB = "0.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_01", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_Current_Right", "CSprite", { X = "0.51875", Y = "0.01668", SizeX = "0.01563", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, ColorR = "1.00000", ColorG = "1.00000", ColorB = "0.00000", ColorA = "1.00000", Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_01_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_SPH_Left", "CSprite", { X = "0.45937", Y = "0.01667", SizeX = "0.01563", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_02_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_SPH_Right", "CSprite", { X = "0.51875", Y = "0.01668", SizeX = "0.01563", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = true, FlipY = true, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_02_B", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) oChild = GUI.CreateDisplayObjectEx("SEB_SPH_Middle", "CSprite", { X = "0.47500", Y = "0.01667", SizeX = "0.04375", SizeY = "0.04999", ScaleX = "1.00000", ScaleY = "1.00000", Angle = "0.00000", FlipX = false, FlipY = false, Enabled = true, SkinItemType = "", Autosize = false, SpriteSheetItem = "Bar_02", BlendMode = "AlphaBlend", USelMode = "Scale", VSelMode = "Scale" }) oContainer:AddChild(oChild) GUI.SetHierarchyProperties(oContainer, _ARG_1_) return oContainer end
local ArtifactUI = { Name = "ArtifactUI", Type = "System", Namespace = "C_ArtifactUI", Functions = { { Name = "AddPower", Type = "Function", Arguments = { { Name = "powerID", Type = "number", Nilable = false }, }, Returns = { { Name = "success", Type = "bool", Nilable = false }, }, }, { Name = "ApplyCursorRelicToSlot", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, }, { Name = "CanApplyArtifactRelic", Type = "Function", Arguments = { { Name = "relicItemID", Type = "number", Nilable = false }, { Name = "onlyUnlocked", Type = "bool", Nilable = false }, }, Returns = { { Name = "canApply", Type = "bool", Nilable = false }, }, }, { Name = "CanApplyCursorRelicToSlot", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "canApply", Type = "bool", Nilable = false }, }, }, { Name = "CanApplyRelicItemIDToEquippedArtifactSlot", Type = "Function", Arguments = { { Name = "relicItemID", Type = "number", Nilable = false }, { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "canApply", Type = "bool", Nilable = false }, }, }, { Name = "CanApplyRelicItemIDToSlot", Type = "Function", Arguments = { { Name = "relicItemID", Type = "number", Nilable = false }, { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "canApply", Type = "bool", Nilable = false }, }, }, { Name = "CheckRespecNPC", Type = "Function", Returns = { { Name = "canRespec", Type = "bool", Nilable = false }, }, }, { Name = "Clear", Type = "Function", }, { Name = "ClearForgeCamera", Type = "Function", }, { Name = "ConfirmRespec", Type = "Function", }, { Name = "DoesEquippedArtifactHaveAnyRelicsSlotted", Type = "Function", Returns = { { Name = "hasAnyRelicsSlotted", Type = "bool", Nilable = false }, }, }, { Name = "GetAppearanceInfo", Type = "Function", Arguments = { { Name = "appearanceSetIndex", Type = "number", Nilable = false }, { Name = "appearanceIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "artifactAppearanceID", Type = "number", Nilable = false }, { Name = "appearanceName", Type = "string", Nilable = false }, { Name = "displayIndex", Type = "number", Nilable = false }, { Name = "unlocked", Type = "bool", Nilable = false }, { Name = "failureDescription", Type = "string", Nilable = true }, { Name = "uiCameraID", Type = "number", Nilable = false }, { Name = "altHandCameraID", Type = "number", Nilable = true }, { Name = "swatchColorR", Type = "number", Nilable = false }, { Name = "swatchColorG", Type = "number", Nilable = false }, { Name = "swatchColorB", Type = "number", Nilable = false }, { Name = "modelOpacity", Type = "number", Nilable = false }, { Name = "modelSaturation", Type = "number", Nilable = false }, { Name = "obtainable", Type = "bool", Nilable = false }, }, }, { Name = "GetAppearanceInfoByID", Type = "Function", Arguments = { { Name = "artifactAppearanceID", Type = "number", Nilable = false }, }, Returns = { { Name = "artifactAppearanceSetID", Type = "number", Nilable = false }, { Name = "artifactAppearanceID", Type = "number", Nilable = false }, { Name = "appearanceName", Type = "string", Nilable = false }, { Name = "displayIndex", Type = "number", Nilable = false }, { Name = "unlocked", Type = "bool", Nilable = false }, { Name = "failureDescription", Type = "string", Nilable = true }, { Name = "uiCameraID", Type = "number", Nilable = false }, { Name = "altHandCameraID", Type = "number", Nilable = true }, { Name = "swatchColorR", Type = "number", Nilable = false }, { Name = "swatchColorG", Type = "number", Nilable = false }, { Name = "swatchColorB", Type = "number", Nilable = false }, { Name = "modelOpacity", Type = "number", Nilable = false }, { Name = "modelSaturation", Type = "number", Nilable = false }, { Name = "obtainable", Type = "bool", Nilable = false }, }, }, { Name = "GetAppearanceSetInfo", Type = "Function", Arguments = { { Name = "appearanceSetIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "artifactAppearanceSetID", Type = "number", Nilable = false }, { Name = "appearanceSetName", Type = "string", Nilable = false }, { Name = "appearanceSetDescription", Type = "string", Nilable = false }, { Name = "numAppearances", Type = "number", Nilable = false }, }, }, { Name = "GetArtifactArtInfo", Type = "Function", Returns = { { Name = "artifactArtInfo", Type = "ArtifactArtInfo", Nilable = false }, }, }, { Name = "GetArtifactInfo", Type = "Function", Returns = { { Name = "itemID", Type = "number", Nilable = false }, { Name = "altItemID", Type = "number", Nilable = true }, { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, { Name = "xp", Type = "number", Nilable = false }, { Name = "pointsSpent", Type = "number", Nilable = false }, { Name = "quality", Type = "number", Nilable = false }, { Name = "artifactAppearanceID", Type = "number", Nilable = false }, { Name = "appearanceModID", Type = "number", Nilable = false }, { Name = "itemAppearanceID", Type = "number", Nilable = true }, { Name = "altItemAppearanceID", Type = "number", Nilable = true }, { Name = "altOnTop", Type = "bool", Nilable = false }, { Name = "tier", Type = "number", Nilable = false }, }, }, { Name = "GetArtifactItemID", Type = "Function", Returns = { { Name = "itemID", Type = "number", Nilable = false }, }, }, { Name = "GetArtifactTier", Type = "Function", Returns = { { Name = "tier", Type = "number", Nilable = true }, }, }, { Name = "GetArtifactXPRewardTargetInfo", Type = "Function", Arguments = { { Name = "artifactCategoryID", Type = "number", Nilable = false }, }, Returns = { { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, }, }, { Name = "GetCostForPointAtRank", Type = "Function", Arguments = { { Name = "rank", Type = "number", Nilable = false }, { Name = "tier", Type = "number", Nilable = false }, }, Returns = { { Name = "cost", Type = "number", Nilable = false }, }, }, { Name = "GetEquippedArtifactArtInfo", Type = "Function", Returns = { { Name = "artifactArtInfo", Type = "ArtifactArtInfo", Nilable = false }, }, }, { Name = "GetEquippedArtifactInfo", Type = "Function", Returns = { { Name = "itemID", Type = "number", Nilable = false }, { Name = "altItemID", Type = "number", Nilable = true }, { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, { Name = "xp", Type = "number", Nilable = false }, { Name = "pointsSpent", Type = "number", Nilable = false }, { Name = "quality", Type = "number", Nilable = false }, { Name = "artifactAppearanceID", Type = "number", Nilable = false }, { Name = "appearanceModID", Type = "number", Nilable = false }, { Name = "itemAppearanceID", Type = "number", Nilable = true }, { Name = "altItemAppearanceID", Type = "number", Nilable = true }, { Name = "altOnTop", Type = "bool", Nilable = false }, { Name = "tier", Type = "number", Nilable = false }, }, }, { Name = "GetEquippedArtifactItemID", Type = "Function", Returns = { { Name = "itemID", Type = "number", Nilable = false }, }, }, { Name = "GetEquippedArtifactNumRelicSlots", Type = "Function", Arguments = { { Name = "onlyUnlocked", Type = "bool", Nilable = false, Default = false, Documentation = { "If true then only the relic slots that are unlocked will be considered." } }, }, Returns = { { Name = "numRelicSlots", Type = "number", Nilable = false }, }, }, { Name = "GetEquippedArtifactRelicInfo", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, { Name = "slotTypeName", Type = "string", Nilable = false, Documentation = { "Matches the socket identifiers used in the socketing system." } }, { Name = "link", Type = "string", Nilable = false }, }, }, { Name = "GetEquippedRelicLockedReason", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "lockedReason", Type = "string", Nilable = true }, }, }, { Name = "GetForgeRotation", Type = "Function", Returns = { { Name = "forgeRotationX", Type = "number", Nilable = false }, { Name = "forgeRotationY", Type = "number", Nilable = false }, { Name = "forgeRotationZ", Type = "number", Nilable = false }, }, }, { Name = "GetItemLevelIncreaseProvidedByRelic", Type = "Function", Arguments = { { Name = "itemLinkOrID", Type = "string", Nilable = false }, }, Returns = { { Name = "itemIevelIncrease", Type = "number", Nilable = false }, }, }, { Name = "GetMetaPowerInfo", Type = "Function", Returns = { { Name = "spellID", Type = "number", Nilable = false, StrideIndex = 1 }, { Name = "powerCost", Type = "number", Nilable = false, StrideIndex = 2 }, { Name = "currentRank", Type = "number", Nilable = false, StrideIndex = 3 }, }, }, { Name = "GetNumAppearanceSets", Type = "Function", Returns = { { Name = "numAppearanceSets", Type = "number", Nilable = false }, }, }, { Name = "GetNumObtainedArtifacts", Type = "Function", Returns = { { Name = "numObtainedArtifacts", Type = "number", Nilable = false }, }, }, { Name = "GetNumRelicSlots", Type = "Function", Arguments = { { Name = "onlyUnlocked", Type = "bool", Nilable = false, Default = false, Documentation = { "If true then only the relic slots that are unlocked will be considered." } }, }, Returns = { { Name = "numRelicSlots", Type = "number", Nilable = false }, }, }, { Name = "GetPointsRemaining", Type = "Function", Returns = { { Name = "pointsRemaining", Type = "number", Nilable = false }, }, }, { Name = "GetPowerHyperlink", Type = "Function", Arguments = { { Name = "powerID", Type = "number", Nilable = false }, }, Returns = { { Name = "link", Type = "string", Nilable = false }, }, }, { Name = "GetPowerInfo", Type = "Function", Arguments = { { Name = "powerID", Type = "number", Nilable = false }, }, Returns = { { Name = "powerInfo", Type = "ArtifactPowerInfo", Nilable = false }, }, }, { Name = "GetPowerLinks", Type = "Function", Arguments = { { Name = "powerID", Type = "number", Nilable = false }, }, Returns = { { Name = "linkingPowerID", Type = "table", InnerType = "number", Nilable = false }, }, }, { Name = "GetPowers", Type = "Function", Returns = { { Name = "powerID", Type = "table", InnerType = "number", Nilable = false }, }, }, { Name = "GetPowersAffectedByRelic", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "powerIDs", Type = "number", Nilable = false, StrideIndex = 1 }, }, }, { Name = "GetPowersAffectedByRelicItemLink", Type = "Function", Arguments = { { Name = "relicItemInfo", Type = "string", Nilable = false }, }, Returns = { { Name = "powerIDs", Type = "number", Nilable = false, StrideIndex = 1 }, }, }, { Name = "GetPreviewAppearance", Type = "Function", Returns = { { Name = "artifactAppearanceID", Type = "number", Nilable = true }, }, }, { Name = "GetRelicInfo", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, { Name = "slotTypeName", Type = "string", Nilable = false, Documentation = { "Matches the socket identifiers used in the socketing system." } }, { Name = "link", Type = "string", Nilable = false }, }, }, { Name = "GetRelicInfoByItemID", Type = "Function", Arguments = { { Name = "itemID", Type = "number", Nilable = false }, }, Returns = { { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, { Name = "slotTypeName", Type = "string", Nilable = false, Documentation = { "Matches the socket identifiers used in the socketing system." } }, { Name = "link", Type = "string", Nilable = false }, }, }, { Name = "GetRelicLockedReason", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "lockedReason", Type = "string", Nilable = true }, }, }, { Name = "GetRelicSlotType", Type = "Function", Arguments = { { Name = "relicSlotIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "slotTypeName", Type = "string", Nilable = false }, }, }, { Name = "GetRespecArtifactArtInfo", Type = "Function", Returns = { { Name = "artifactArtInfo", Type = "ArtifactArtInfo", Nilable = false }, }, }, { Name = "GetRespecArtifactInfo", Type = "Function", Returns = { { Name = "itemID", Type = "number", Nilable = false }, { Name = "altItemID", Type = "number", Nilable = true }, { Name = "name", Type = "string", Nilable = false }, { Name = "icon", Type = "number", Nilable = false }, { Name = "xp", Type = "number", Nilable = false }, { Name = "pointsSpent", Type = "number", Nilable = false }, { Name = "quality", Type = "number", Nilable = false }, { Name = "artifactAppearanceID", Type = "number", Nilable = false }, { Name = "appearanceModID", Type = "number", Nilable = false }, { Name = "itemAppearanceID", Type = "number", Nilable = true }, { Name = "altItemAppearanceID", Type = "number", Nilable = true }, { Name = "altOnTop", Type = "bool", Nilable = false }, { Name = "tier", Type = "number", Nilable = false }, }, }, { Name = "GetRespecCost", Type = "Function", Returns = { { Name = "cost", Type = "number", Nilable = false }, }, }, { Name = "GetTotalPowerCost", Type = "Function", Arguments = { { Name = "startingTrait", Type = "number", Nilable = false }, { Name = "numTraits", Type = "number", Nilable = false }, { Name = "artifactTier", Type = "number", Nilable = false }, }, Returns = { { Name = "totalArtifactPowerCost", Type = "number", Nilable = false }, }, }, { Name = "GetTotalPurchasedRanks", Type = "Function", Returns = { { Name = "totalPurchasedRanks", Type = "number", Nilable = false }, }, }, { Name = "IsArtifactDisabled", Type = "Function", Returns = { { Name = "artifactDisabled", Type = "bool", Nilable = false }, }, }, { Name = "IsAtForge", Type = "Function", Returns = { { Name = "isAtForge", Type = "bool", Nilable = false }, }, }, { Name = "IsEquippedArtifactDisabled", Type = "Function", Returns = { { Name = "artifactDisabled", Type = "bool", Nilable = false }, }, }, { Name = "IsEquippedArtifactMaxed", Type = "Function", Returns = { { Name = "artifactMaxed", Type = "bool", Nilable = false }, }, }, { Name = "IsMaxedByRulesOrEffect", Type = "Function", Returns = { { Name = "isEffectivelyMaxed", Type = "bool", Nilable = false }, }, }, { Name = "IsPowerKnown", Type = "Function", Arguments = { { Name = "powerID", Type = "number", Nilable = false }, }, Returns = { { Name = "known", Type = "bool", Nilable = false }, }, }, { Name = "IsViewedArtifactEquipped", Type = "Function", Returns = { { Name = "isViewedArtifactEquipped", Type = "bool", Nilable = false }, }, }, { Name = "SetAppearance", Type = "Function", Arguments = { { Name = "artifactAppearanceID", Type = "number", Nilable = false }, }, }, { Name = "SetForgeCamera", Type = "Function", }, { Name = "SetForgeRotation", Type = "Function", Arguments = { { Name = "forgeRotationX", Type = "number", Nilable = false }, { Name = "forgeRotationY", Type = "number", Nilable = false }, { Name = "forgeRotationZ", Type = "number", Nilable = false }, }, }, { Name = "SetPreviewAppearance", Type = "Function", Documentation = { "Call without an argument to clear the preview." }, Arguments = { { Name = "artifactAppearanceID", Type = "number", Nilable = false, Default = 0 }, }, }, { Name = "ShouldSuppressForgeRotation", Type = "Function", Returns = { { Name = "shouldSuppressForgeRotation", Type = "bool", Nilable = false }, }, }, }, Events = { { Name = "ArtifactClose", Type = "Event", LiteralName = "ARTIFACT_CLOSE", }, { Name = "ArtifactEndgameRefund", Type = "Event", LiteralName = "ARTIFACT_ENDGAME_REFUND", Payload = { { Name = "numRefundedPowers", Type = "number", Nilable = false }, { Name = "refundedTier", Type = "number", Nilable = false }, { Name = "bagOrSlotIndex", Type = "number", Nilable = false }, { Name = "slotIndex", Type = "number", Nilable = true }, }, }, { Name = "ArtifactRelicForgeClose", Type = "Event", LiteralName = "ARTIFACT_RELIC_FORGE_CLOSE", }, { Name = "ArtifactRelicForgePreviewRelicChanged", Type = "Event", LiteralName = "ARTIFACT_RELIC_FORGE_PREVIEW_RELIC_CHANGED", }, { Name = "ArtifactRelicForgeUpdate", Type = "Event", LiteralName = "ARTIFACT_RELIC_FORGE_UPDATE", }, { Name = "ArtifactRelicInfoReceived", Type = "Event", LiteralName = "ARTIFACT_RELIC_INFO_RECEIVED", }, { Name = "ArtifactRespecPrompt", Type = "Event", LiteralName = "ARTIFACT_RESPEC_PROMPT", }, { Name = "ArtifactTierChanged", Type = "Event", LiteralName = "ARTIFACT_TIER_CHANGED", Payload = { { Name = "newTier", Type = "number", Nilable = false }, { Name = "bagOrSlotIndex", Type = "number", Nilable = false }, { Name = "slotIndex", Type = "number", Nilable = true }, }, }, { Name = "ArtifactUpdate", Type = "Event", LiteralName = "ARTIFACT_UPDATE", Payload = { { Name = "newItem", Type = "bool", Nilable = false }, }, }, { Name = "ArtifactXpUpdate", Type = "Event", LiteralName = "ARTIFACT_XP_UPDATE", }, }, Tables = { { Name = "ArtifactArtInfo", Type = "Structure", Fields = { { Name = "textureKit", Type = "string", Nilable = false }, { Name = "titleName", Type = "string", Nilable = false }, { Name = "titleColor", Type = "table", Mixin = "ColorMixin", Nilable = false }, { Name = "barConnectedColor", Type = "table", Mixin = "ColorMixin", Nilable = false }, { Name = "barDisconnectedColor", Type = "table", Mixin = "ColorMixin", Nilable = false }, { Name = "uiModelSceneID", Type = "number", Nilable = false }, { Name = "spellVisualKitID", Type = "number", Nilable = false }, }, }, { Name = "ArtifactPowerInfo", Type = "Structure", Fields = { { Name = "spellID", Type = "number", Nilable = false }, { Name = "cost", Type = "number", Nilable = false }, { Name = "currentRank", Type = "number", Nilable = false }, { Name = "maxRank", Type = "number", Nilable = false }, { Name = "bonusRanks", Type = "number", Nilable = false }, { Name = "numMaxRankBonusFromTier", Type = "number", Nilable = false }, { Name = "prereqsMet", Type = "bool", Nilable = false }, { Name = "isStart", Type = "bool", Nilable = false }, { Name = "isGoldMedal", Type = "bool", Nilable = false }, { Name = "isFinal", Type = "bool", Nilable = false }, { Name = "tier", Type = "number", Nilable = false }, { Name = "position", Type = "table", Mixin = "Vector2DMixin", Nilable = false }, { Name = "offset", Type = "table", Mixin = "Vector2DMixin", Nilable = true }, { Name = "linearIndex", Type = "number", Nilable = true }, }, }, }, }; APIDocumentation:AddDocumentationTable(ArtifactUI);
local draw = draw local math = math local string = string local GetLang = LANG.GetUnsafeLanguageTable local util = util local base = "old_ttt_element" DEFINE_BASECLASS(base) HUDELEMENT.Base = base if CLIENT then local x = 0 local y = 0 local const_defaults = { basepos = {x = 0, y = 0}, size = {w = HUDELEMENT.maxwidth, h = HUDELEMENT.maxheight}, minsize = {w = HUDELEMENT.maxwidth, h = HUDELEMENT.maxheight} } --- -- @ignore function HUDELEMENT:Initialize() BaseClass.Initialize(self) end --- -- @ignore function HUDELEMENT:GetDefaults() const_defaults["size"] = {w = self.maxwidth, h = self.maxheight} const_defaults["minsize"] = {w = self.maxwidth, h = self.maxheight} const_defaults["basepos"] = {x = self.margin, y = ScrH() - (self.margin + self.maxheight)} return const_defaults end --- -- @ignore function HUDELEMENT:PerformLayout() local pos = self:GetPos() x = pos.x y = pos.y BaseClass.PerformLayout(self) end --- -- Draws the old role icon -- @param number xPos -- @param number yPos -- @param number wSize width -- @param number hSize height -- @param Material iconMat the role icon -- @param Color col -- @realm client local function DrawOldRoleIcon(xPos, yPos, wSize, hSize, iconMat, col) local base_mat = Material("vgui/ttt/dynamic/base") local base_overlay = Material("vgui/ttt/dynamic/base_overlay") surface.SetDrawColor(col.r, col.g, col.b, col.a) surface.SetMaterial(base_mat) surface.DrawTexturedRect(xPos, yPos, wSize, hSize) surface.SetDrawColor(col.r, col.g, col.b, col.a) surface.SetMaterial(base_overlay) surface.DrawTexturedRect(xPos, yPos, wSize, hSize) surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial(iconMat) surface.DrawTexturedRect(xPos, yPos, wSize, hSize) end --- -- @ignore function HUDELEMENT:Draw() local client = LocalPlayer() local L = GetLang() local maxwidth = self.maxwidth local width = maxwidth local height = self.maxheight local margin = self.margin if client:Alive() and client:Team() == TEAM_TERROR then self:DrawBg(x, y, width, height, client) local bar_height = 25 local bar_width = width - self.dmargin -- Draw health local health = math.max(0, client:Health()) local health_y = y + margin local health_string = health if not GetGlobalBool("ttt_armor_classic", false) and client:GetArmor() > 0 then health_string = health_string .. " + " .. client:GetArmor() end self:PaintBar(x + margin, health_y, bar_width, bar_height, self.health_colors, health / client:GetMaxHealth()) self:ShadowedText(health_string, "HealthAmmo", x + bar_width, health_y, COLOR_WHITE, TEXT_ALIGN_RIGHT, TEXT_ALIGN_RIGHT) -- Draw ammo local ammo_y = health_y + bar_height + margin if client:GetActiveWeapon().Primary then local ammo_clip, ammo_max, ammo_inv = self:GetAmmo(client) if ammo_clip ~= -1 then local text = string.format("%i + %02i", ammo_clip, ammo_inv) self:PaintBar(x + margin, ammo_y, bar_width, bar_height, self.ammo_colors, ammo_clip / ammo_max) self:ShadowedText(text, "HealthAmmo", x + bar_width, ammo_y, COLOR_WHITE, TEXT_ALIGN_RIGHT, TEXT_ALIGN_RIGHT) end end -- sprint bar local sbh = 8 -- spring bar height if GetGlobalBool("ttt2_sprint_enabled", true) then self:PaintBar(x + margin, ammo_y + bar_height + 5, bar_width, sbh, self.sprint_colors, client.sprintProgress) end local hastewidth = self.hastewidth local bgheight = self.bgheight local smargin = self.smargin local tmp = width - hastewidth - bgheight - smargin * 2 -- Draw the current role local round_state = GAMEMODE.round_state local traitor_y = y - 30 local text if round_state == ROUND_ACTIVE then text = L[client:GetSubRoleData().name] else text = L[self.roundstate_string[round_state]] end self:ShadowedText(text, "TraitorState", x + tmp * 0.5, traitor_y, COLOR_WHITE, TEXT_ALIGN_CENTER) -- Draw team icon local team = client:GetTeam() if team ~= TEAM_NONE and round_state == ROUND_ACTIVE and not TEAMS[team].alone then local t = TEAMS[team] if t.iconMaterial then DrawOldRoleIcon(x + tmp + smargin, traitor_y, bgheight, bgheight, t.iconMaterial, t.color or COLOR_BLACK) end end -- Draw round time local is_haste = HasteMode() and round_state == ROUND_ACTIVE local is_traitor = client:IsActive() and client:GetTeam() == TEAM_TRAITOR local endtime = GetGlobalFloat("ttt_round_end", 0) - CurTime() local font = "TimeLeft" local color = COLOR_WHITE tmp = width + x - hastewidth + smargin + hastewidth * 0.5 local rx = tmp local ry = traitor_y + 3 -- Time displays differently depending on whether haste mode is on, -- whether the player is traitor or not, and whether it is overtime. if is_haste then local hastetime = GetGlobalFloat("ttt_haste_end", 0) - CurTime() if hastetime < 0 then if not is_traitor or math.ceil(CurTime()) % 7 <= 2 then -- innocent or blinking "overtime" text = L.overtime font = "Trebuchet18" -- need to hack the position a little because of the font switch ry = ry + 5 rx = rx - 3 else -- traitor and not blinking "overtime" right now, so standard endtime display text = util.SimpleTime(math.max(0, endtime), "%02i:%02i") color = COLOR_RED end else -- still in starting period local t = hastetime if is_traitor and math.ceil(CurTime()) % 6 < 2 then t = endtime color = COLOR_RED end text = util.SimpleTime(math.max(0, t), "%02i:%02i") end else -- bog standard time when haste mode is off (or round not active) text = util.SimpleTime(math.max(0, endtime), "%02i:%02i") end self:ShadowedText(text, font, rx, ry, color, TEXT_ALIGN_CENTER) if is_haste then draw.SimpleText(L.hastemode, "TabLarge", tmp, traitor_y - 8, COLOR_WHITE, TEXT_ALIGN_CENTER) end else -- Draw round state local smargin = self.smargin local hastewidth = self.hastewidth local bg_colors = self.bg_colors local round_y = y + height - self.bgheight height = self.bgheight -- move up a little on low resolutions to allow space for spectator hints if ScrW() < 1000 then round_y = round_y - 15 end local time_x = width - hastewidth local time_y = round_y + 4 draw.RoundedBox(8, x, round_y, width, height, bg_colors.background_main) draw.RoundedBox(8, x, round_y, time_x, height, bg_colors.noround) -- Draw current round state local text = L[self.roundstate_string[GAMEMODE.round_state]] self:ShadowedText(text, "TraitorState", x + (width - hastewidth) * 0.5, round_y, COLOR_WHITE, TEXT_ALIGN_CENTER) -- Draw round/prep/post time remaining text = util.SimpleTime(math.max(0, GetGlobalFloat("ttt_round_end", 0) - CurTime()), "%02i:%02i") self:ShadowedText(text, "TimeLeft", x + time_x + smargin + hastewidth * 0.5, time_y, COLOR_WHITE, TEXT_ALIGN_CENTER) end end end
local DebugLogger = require "lil.DebugLogger" local OsFacts = require "lil.OsFacts" local StringUtils = require "lil.StringUtils" local useFile = function(filePath, mode, useBlock) local file = assert(io.open(filePath, mode)) local useBlockOk, useBlockErrorOrRetVal = xpcall(function() return useBlock(file) end, debug.traceback) pcall(function() file:close() end) if not useBlockOk then error(useBlockErrorOrRetVal) end return useBlockErrorOrRetVal end local appendTextToFile = function(filePath, text) DebugLogger.log("appending text to file with filePath = '%s'", filePath) return useFile(filePath, "a", function(file) return file:write(text) end) end local getFileSizeInBytes = function(filePath) DebugLogger.log("get file size in bytes with filePath = '%s'", filePath) return useFile(filePath, "r", function(file) return file:seek("end") end) end local fileExists = function(filePath) DebugLogger.log("checking if file exists with filePath = '%s'", filePath) local file, fileOpenError = io.open(filePath) pcall(function() file:close() end) return file and not fileOpenError end local getFileDirectory = function(filePath) DebugLogger.log("get file directory with filePath = '%s'", filePath) local lastSeperatorIndex = filePath:match(OsFacts.lastDirectorySeperatorRegex) if not lastSeperatorIndex then return string.format(".%s", OsFacts.directorySeperator) end return filePath:sub(0, lastSeperatorIndex) end local getFileName = function(filePath) DebugLogger.log("get file directory with filePath = '%s'", filePath) local lastSeperatorIndex = filePath:match(OsFacts.lastDirectorySeperatorRegex) if not lastSeperatorIndex then return filePath end local fileName = StringUtils.replacePatternIfPresent(filePath:sub(lastSeperatorIndex), OsFacts.directorySeperator, "") DebugLogger.log("get file directory returning with fileName = '%s'", fileName) return fileName end local combinePaths = function(left, right) DebugLogger.log("combine paths with left = '%s' and right = '%s'", left, right) return string.format("%s%s%s", left, OsFacts.directorySeperator, right):gsub(OsFacts.directorySeperatorRegex, OsFacts.directorySeperator) end return { useFile = useFile, appendTextToFile = appendTextToFile, getFileSizeInBytes = getFileSizeInBytes, fileExists = fileExists, getFileDirectory = getFileDirectory, getFileName = getFileName, combinePaths = combinePaths }
local S = mobs.intllib -- Warthog originally by KrupnoPavel, B3D model by sirrobzeroone mobs:register_mob("mobs_animal:pumba", { stepheight = 0.6, type = "animal", passive = false, attack_type = "dogfight", group_attack = true, owner_loyal = true, attack_npcs = false, reach = 2, damage = 2, hp_min = 5, hp_max = 15, armor = 200, collisionbox = {-0.4, -0.01, -0.4, 0.4, 0.95, 0.4}, visual = "mesh", mesh = "mobs_pumba.b3d", textures = { {"mobs_pumba.png"}, }, makes_footstep_sound = true, sounds = { random = "mobs_pig", attack = "mobs_pig_angry", }, walk_velocity = 2, run_velocity = 3, jump = true, jump_height = 6, pushable = true, follow = {"default:apple", "farming:potato"}, view_range = 10, drops = { {name = "mobs:pork_raw", chance = 1, min = 1, max = 3}, }, water_damage = 0, lava_damage = 5, light_damage = 0, fear_height = 2, animation = { speed_normal = 15, stand_start = 25, stand_end = 55, walk_start = 70, walk_end = 100, punch_start = 70, punch_end = 100, }, on_rightclick = function(self, clicker) if mobs:feed_tame(self, clicker, 8, true, true) then return end if mobs:protect(self, clicker) then return end if mobs:capture_mob(self, clicker, 0, 5, 50, false, nil) then return end end, }) local spawn_on = {"default:dirt_with_grass"} local spawn_by = {"group:grass"} if minetest.get_mapgen_setting("mg_name") ~= "v6" then spawn_on = {"default:dirt_with_dry_grass", "default:dry_dirt_with_dry_grass"} spawn_by = {"group:dry_grass"} end if minetest.get_modpath("ethereal") then spawn_on = {"ethereal:mushroom_dirt"} spawn_by = {"flowers:mushroom_brown", "flowers:mushroom_red"} end mobs:spawn({ name = "mobs_animal:pumba", nodes = spawn_on, neighbors = spawn_by, min_light = 14, interval = 60, chance = 8000, -- 15000 min_height = 0, max_height = 200, day_toggle = true, }) mobs:register_egg("mobs_animal:pumba", S("Warthog"), "mobs_pumba_inv.png") mobs:alias_mob("mobs:pumba", "mobs_animal:pumba") -- compatibility -- raw porkchop minetest.register_craftitem(":mobs:pork_raw", { description = S("Raw Porkchop"), inventory_image = "mobs_pork_raw.png", on_use = minetest.item_eat(4), groups = {food_meat_raw = 1, food_pork_raw = 1, flammable = 2}, }) -- cooked porkchop minetest.register_craftitem(":mobs:pork_cooked", { description = S("Cooked Porkchop"), inventory_image = "mobs_pork_cooked.png", on_use = minetest.item_eat(8), groups = {food_meat = 1, food_pork = 1, flammable = 2}, }) minetest.register_craft({ type = "cooking", output = "mobs:pork_cooked", recipe = "mobs:pork_raw", cooktime = 5, })
-- Last Change: 2022 Apr 16 if vim.g.loaded_nvim_treesitter then return end vim.g.loaded_nvim_treesitter = true -- setup modules require("nvim-treesitter").setup() local api = vim.api -- define autocommands local augroup = api.nvim_create_augroup("NvimTreesitter", {}) api.nvim_create_autocmd("Filetype", { pattern = "query", group = augroup, callback = function() api.nvim_clear_autocmds { group = augroup, event = "BufWritePost", } api.nvim_create_autocmd("BufWritePost", { group = augroup, buffer = 0, callback = function(opts) require("nvim-treesitter.query").invalidate_query_file(opts.file) end, desc = "Invalidate query file", }) end, desc = "Reload query", }) -- define highlights local highlights = { TSNone = { default = true }, TSPunctDelimiter = { link = "Delimiter", default = true }, TSPunctBracket = { link = "Delimiter", default = true }, TSPunctSpecial = { link = "Delimiter", default = true }, TSConstant = { link = "Constant", default = true }, TSConstBuiltin = { link = "Special", default = true }, TSConstMacro = { link = "Define", default = true }, TSString = { link = "String", default = true }, TSStringRegex = { link = "String", default = true }, TSStringEscape = { link = "SpecialChar", default = true }, TSStringSpecial = { link = "SpecialChar", default = true }, TSCharacter = { link = "Character", default = true }, TSCharacterSpecial = { link = "SpecialChar", default = true }, TSNumber = { link = "Number", default = true }, TSBoolean = { link = "Boolean", default = true }, TSFloat = { link = "Float", default = true }, TSFunction = { link = "Function", default = true }, TSFuncBuiltin = { link = "Special", default = true }, TSFuncMacro = { link = "Macro", default = true }, TSParameter = { link = "Identifier", default = true }, TSParameterReference = { link = "TSParameter", default = true }, TSMethod = { link = "Function", default = true }, TSField = { link = "Identifier", default = true }, TSProperty = { link = "Identifier", default = true }, TSConstructor = { link = "Special", default = true }, TSAnnotation = { link = "PreProc", default = true }, TSAttribute = { link = "PreProc", default = true }, TSNamespace = { link = "Include", default = true }, TSSymbol = { link = "Identifier", default = true }, TSConditional = { link = "Conditional", default = true }, TSRepeat = { link = "Repeat", default = true }, TSLabel = { link = "Label", default = true }, TSOperator = { link = "Operator", default = true }, TSKeyword = { link = "Keyword", default = true }, TSKeywordFunction = { link = "Keyword", default = true }, TSKeywordOperator = { link = "TSOperator", default = true }, TSKeywordReturn = { link = "TSKeyword", default = true }, TSException = { link = "Exception", default = true }, TSDebug = { link = "Debug", default = true }, TSDefine = { link = "Define", default = true }, TSPreProc = { link = "PreProc", default = true }, TSStorageClass = { link = "StorageClass", default = true }, TSTodo = { link = "Todo", default = true }, TSType = { link = "Type", default = true }, TSTypeBuiltin = { link = "Type", default = true }, TSTypeQualifier = { link = "Type", default = true }, TSTypeDefinition = { link = "Typedef", default = true }, TSInclude = { link = "Include", default = true }, TSVariableBuiltin = { link = "Special", default = true }, TSText = { link = "TSNone", default = true }, TSStrong = { bold = true, default = true }, TSEmphasis = { italic = true, default = true }, TSUnderline = { underline = true }, TSStrike = { strikethrough = true }, TSMath = { link = "Special", default = true }, TSTextReference = { link = "Constant", default = true }, TSEnvironment = { link = "Macro", default = true }, TSEnvironmentName = { link = "Type", default = true }, TSTitle = { link = "Title", default = true }, TSLiteral = { link = "String", default = true }, TSURI = { link = "Underlined", default = true }, TSComment = { link = "Comment", default = true }, TSNote = { link = "SpecialComment", default = true }, TSWarning = { link = "Todo", default = true }, TSDanger = { link = "WarningMsg", default = true }, TSTag = { link = "Label", default = true }, TSTagDelimiter = { link = "Delimiter", default = true }, TSTagAttribute = { link = "TSProperty", default = true }, } for k, v in pairs(highlights) do api.nvim_set_hl(0, k, v) end
function distortions.pinch(x, y) local slen = (x * x + y * y) slen = (slen * slen) * 0.0005 return (x / slen), (y / slen) end function distortions.lens(x, y, width) local delta = vector_distance( 0, 0, x, y ) local radius = width/2 local newLength = 0 if delta < radius then newLength = radius - math.sqrt( radius * radius - delta * delta ) - delta newLength = newLength / delta end return x*newLength, y*newLength end function distortions.spin( degrees ) return function( x, y, w, h ) local delta = vector_distance( 0, 0, x, y ) local radius = w/2 local angle = vector_direction( 0, 0, x, y ) if ( delta < radius ) then local factor = 1 - delta/radius local newX, newY= angle_vector( angle + degrees * factor, delta ) return vector_diff( x, y, newX, newY ) end return 0,0 end end distortions.swirl = distortions.spin(90) function distortions.ripple(waves, distance ) return function( x, y, w, h ) local delta = vector_distance( 0, 0, x, y ) local radius = w/2 local angle = vector_direction( 0, 0, x, y ) if ( delta < radius ) then local factor = delta/radius return angle_vector( angle, -distance * math.sin(math.pi * waves * factor) ) end return 0, 0 end end
require("utils/functions.lua") -- Teleport the player inside the Mobile Factory -- function teleportPlayerInside(player) -- Check Internal Surface and Player -- if global.MF.fS == nil then game.print("Factory surface lost") return end if player == nil then return end -- Save the visited Factory once variable -- setPlayerVariable(player.name, "VisitedFactory", true) -- Get the Player direction -- local direction = player.walking_state.direction -- Calcul the future position -- local position if direction == defines.direction.north then position = {0,-2} elseif direction == defines.direction.northeast or direction == defines.direction.east or direction == defines.direction.southeast then position = {2,0} elseif direction == defines.direction.south then position = {0,2} else position = {-2,0} end --Test where the Player can be teleported and teleport the Player -- if global.MF.fS.can_place_entity{name="character", position = position} then player.teleport(position, global.MF.fS) elseif global.MF.fS.can_place_entity{name="character", position = {2, 0}} then player.teleport({2,0}, global.MF.fS) elseif global.MF.fS.can_place_entity{name="character", position = {-2, 0}} then player.teleport({-2,0}, global.MF.fS) elseif global.MF.fS.can_place_entity{name="character", position = {0, 2}} then player.teleport({0,2}, global.MF.fS) else player.teleport({0,-2}, global.MF.fS) end -- Play the sound -- player.surface.play_sound{path="MFEnter", position=player.position} -- Save the Mobile Factory last surface and position -- global.MF.lastSurface = global.MF.ent.surface global.MF.lastPosX = global.MF.ent.position.X global.MF.lastPosY = global.MF.ent.position.Y end -- Teleport the player outside the Mobile Factory -- function teleportPlayerOutside(player) -- Check if the Player is on the right Surface -- if player.surface.name ~= _mfSurfaceName and player.surface.name ~= _mfControlSurfaceName then return end -- Check if the Mobile Factory Vehicle is valid -- if global.MF == nil or global.MF.ent.valid == false then -- Unable to find the Mobile Factory -- player.print("Unable to find the Mobile Factory vehicle (Destroyed? Changed surface?), teleporting to spawn point") if global.MF.lastSurface ~= nil then -- Teleport the Player to the last know position -- player.teleport({0,0}, global.MF.lastSurface) else -- Teleport the Player to the spawm point -- player.teleport({0,0}, "nauvis") end return end -- Get the Player direction -- local direction = player.walking_state.direction -- Calcul the future position -- local position if direction == defines.direction.north then position = {global.MF.ent.position.x, global.MF.ent.position.y -5} elseif direction == defines.direction.northeast or direction == defines.direction.east or direction == defines.direction.southeast then position = {global.MF.ent.position.x + 2, global.MF.ent.position.y} elseif direction == defines.direction.south then position = {global.MF.ent.position.x, global.MF.ent.position.y + 5} else position = {global.MF.ent.position.x -5, global.MF.ent.position.y} end -- Teleport the Player -- if global.MF.ent.surface.can_place_entity{name="character", position=position} then player.teleport(position, global.MF.ent.surface) elseif global.MF.ent.surface.can_place_entity{name="character", position = {global.MF.ent.position.x + 5, global.MF.ent.position.y}} then player.teleport({global.MF.ent.position.x + 5, global.MF.ent.position.y}, global.MF.ent.surface) elseif global.MF.ent.surface.can_place_entity{name="character", position = {global.MF.ent.position.x -5, global.MF.ent.position.y}} then player.teleport({global.MF.ent.position.x - 5, global.MF.ent.position.y}, global.MF.ent.surface) elseif global.MF.ent.surface.can_place_entity{name="character", position = {global.MF.ent.position.x, global.MF.ent.position.y - 7}} then player.teleport({global.MF.ent.position.x, global.MF.ent.position.y - 7}, global.MF.ent.surface) else player.teleport({global.MF.ent.position.x, global.MF.ent.position.y + 7}, global.MF.ent.surface) end -- Play the sound -- player.surface.play_sound{path="MFLeave", position=player.position} end -- Teleport the player from the Factory to the Control Center -- function teleportPlayerToControlCenter(player) -- Check the Player -- if player == nil then return end -- Check if the Control Center Surface is valid -- if global.MF.ccS == nil then game.print("Control Center surface lost") return end -- Teleport the Player -- player.teleport({0,4}, global.MF.ccS) -- Play the sound -- player.surface.play_sound{path="MFEnter", position=player.position} end -- Teleport the player from Control Center to the Factory -- function teleportPlayerToFactory(player) -- Check if the Factory Surface is valid -- if global.MF.fS == nil then game.print("Factory surface lost") return end -- Teleport the Player -- player.teleport({0,-30}, global.MF.fS) -- Play the sound -- player.surface.play_sound{path="MFEnter", position=player.position} end
--[[ TheNexusAvenger Class for a Dodgeball round. --]] local SCORE_TO_END = 3 local INTERMISSION_TIME_SECONDS = 5 local TEAM_END_DELAY_SECONDS = 5 local TEAM_COLOR_NAME_TO_NAME = { ["Bright red"] = "Red team", ["Bright blue"] = "Blue team", } local ReplicatedStorage = game:GetService("ReplicatedStorage") local NexusReplication = require(ReplicatedStorage:WaitForChild("External"):WaitForChild("NexusReplication")) local Dodgeball = require(ReplicatedStorage:WaitForChild("Round"):WaitForChild("BaseTeamRound")):Extend() Dodgeball:SetClassName("Dodgeball") NexusReplication:RegisterType("Dodgeball",Dodgeball) --[[ Creates the round object. --]] function Dodgeball:__new() self:InitializeSuper() self.Name = "Dodgeball" --Set up the scores. if NexusReplication:IsServer() then self.TeamScores = NexusReplication:CreateObject("ReplicatedTable") self.TeamScores:Set("Bright blue",0) self.TeamScores:Set("Bright red",0) end self:AddToSerialization("TeamScores") end --[[ Starts the round. --]] function Dodgeball:RoundStarted() --Spawn the players. for _,Player in pairs(self.Players:GetAll()) do self:SetSpawningEnabled(Player,true) self:SpawnPlayer(Player) end --Run matches until the round ends. coroutine.wrap(function() while self.Timer.State ~= "COMPLETE" do --Run a match. wait(INTERMISSION_TIME_SECONDS) self:RunDoggeballMatch() --Stop the match if a team has enough points. if self.Timer.State ~= "COMPLETE" then for _,Score in pairs(self.TeamScores:GetAll()) do if Score >= SCORE_TO_END then self.Timer:Complete() break end end end end end)() --Wait for the timer to complete. while self.Timer.State ~= "COMPLETE" do self.Timer:GetPropertyChangedSignal("State"):Wait() end --End the round. self:End() end --[[ Runs a dodgeball match. --]] function Dodgeball:RunDoggeballMatch() local DamageService = self:GetService("DamageService") local LocalEffectService = self:GetService("LocalEffectService") --Determine the players. local ActiveMatchPlayers = {} for _,Player in pairs(self.Players:GetAll()) do local Character = Player.Character local TeamColorName = Player.TeamColor.Name if not ActiveMatchPlayers[TeamColorName] then ActiveMatchPlayers[TeamColorName] = {} end if Character then local Humanoid = Character:FindFirstChild("Humanoid") local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart") local Backpack = Player:FindFirstChild("Backpack") if Humanoid and Humanoid.Health >= 0 and HumanoidRootPart and Backpack then table.insert(ActiveMatchPlayers[TeamColorName],Player) end end end --[[ Removes a player from the match. --]] local function RemovePlayer(Player) for _,TeamPlayers in pairs(ActiveMatchPlayers) do for i,OtherPlayer in pairs(TeamPlayers) do if Player == OtherPlayer then table.remove(TeamPlayers,i) break end end end end --Connect players leaving the match. local MatchEvents = {} table.insert(MatchEvents,self.Players.ItemRemoved:Connect(RemovePlayer)) --Move the players. local MatchActive = true local Zones = { ["Bright red"] = self.Map:WaitForChild("Arena"):WaitForChild("RedZone"), ["Bright blue"] = self.Map:WaitForChild("Arena"):WaitForChild("BlueZone"), } for TeamColorName,TeamPlayers in pairs(ActiveMatchPlayers) do local TeamZone = Zones[TeamColorName] local ZoneSize2 = TeamZone.Size/2 if TeamZone then for _,Player in pairs(TeamPlayers) do local Character = Player.Character if Character then local Humanoid = Character:FindFirstChild("Humanoid") local HumanoidRootPart = Character:FindFirstChild("HumanoidRootPart") local Backpack = Player:FindFirstChild("Backpack") if Humanoid and Humanoid.Health >= 0 and HumanoidRootPart and Backpack then --Move the player and give a superball. HumanoidRootPart.CFrame = TeamZone.CFrame * CFrame.new(TeamZone.Size.X * ((math.random() * 0.8) - 0.4),3,TeamZone.Size.Z * (0.25 + (0.2 * math.random()))) self:SetTools(Player,{"Superball"}) coroutine.wrap(function() --Connect the character dieing. table.insert(MatchEvents,DamageService:GetWOEvent(Player):Connect(function() RemovePlayer(Player) end)) --Equip the superball. Humanoid:EquipTool(Backpack:WaitForChild("Superball")) --Kill the player if the exit the zone. while MatchActive and Humanoid.Health > 0 do local LocalCharacterPosition = TeamZone.CFrame:Inverse() * HumanoidRootPart.CFrame if LocalCharacterPosition.X < -ZoneSize2.X or LocalCharacterPosition.X > ZoneSize2.X or LocalCharacterPosition.Z < -ZoneSize2.Z or LocalCharacterPosition.Z > ZoneSize2.Z then Humanoid.Health = 0 LocalEffectService:PlayLocalEffect(Player,"DisplayAlert","Don't cross the line!") end wait() end end)() end end end end end --Wait for only 1 team to remain. while self.Timer.State ~= "COMPLETE" do --Get the teams with players. local TeamsWithPlayers = {} for TeamColorName,TeamPlayers in pairs(ActiveMatchPlayers) do if #TeamPlayers > 0 then table.insert(TeamsWithPlayers,TeamColorName) end end --Award the point to the team and stop the loop if there is 1 team. if #TeamsWithPlayers == 0 then --Display the message. self:BroadcastLocalEffect("DisplayAlert","No team wins!") --Break the match loop. break elseif #TeamsWithPlayers == 1 then --Display the message. local WinningTeamColorName = TeamsWithPlayers[1] if TEAM_COLOR_NAME_TO_NAME[WinningTeamColorName] then self:BroadcastLocalEffect("DisplayAlert",tostring(TEAM_COLOR_NAME_TO_NAME[WinningTeamColorName]).." wins!") end --Award a point. self.TeamScores:Set(WinningTeamColorName,self.TeamScores:Get(WinningTeamColorName) + 1) --Break the match loop. break end --Wait to continue. wait() end MatchActive = false --Respawn the remaining players. wait(TEAM_END_DELAY_SECONDS) for _,TeamPlayers in pairs(ActiveMatchPlayers) do for _,Player in pairs(TeamPlayers) do self:SpawnPlayer(Player) end end --Disconnect the events. for _,Event in pairs(MatchEvents) do Event:Disconnect() end end --[[ Disposes of the object. --]] function Dodgeball:Dispose() self.super:Dispose() --Destroy the objects. self.TeamScores:Destroy() end return Dodgeball
return {[1114112]=true,[141314]=true,[31121411]=true,[31113221]=true,[14342]=true,[312111113]=true,[14131211]=true,[3123212]=true,[2142221]=true,[3332111]=true,[4112]=true,[3131411]=true,[141332]=true,[2312213]=true,[4313111]=true,[111321113]=true,[1241114]=true,[4112411]=true,[311324]=true,[11311133]=true,[1114142]=true,[2222111]=true,[32]=true,[2222114]=true,[21221411]=true,[311333]=true,[142211111]=true,[1411112]=true,[14211113]=true,[131114]=true,[31111211]=true,[4142]=true,[344111]=true,[33112112]=true,[111112241]=true,[1112114]=true,[143411]=true,[1241141]=true,[114221111]=true,[12344]=true,[3211322]=true,[3121211]=true,[2222141]=true,[3121214]=true,[2111]=true,[2114]=true,[131141]=true,[1411142]=true,[113111111]=true,[131144]=true,[4311113]=true,[113111114]=true,[14411]=true,[1112141]=true,[14414]=true,[41132111]=true,[1112144]=true,[223313]=true,[14423]=true,[3121241]=true,[12421211]=true,[2141]=true,[31113311]=true,[14432]=true,[342113]=true,[1421411]=true,[113111141]=true,[133223]=true,[14441]=true,[11311211]=true,[21121133]=true,[11311214]=true,[1114223]=true,[133232]=true,[113]=true,[311411]=true,[24111221]=true,[311414]=true,[32213111]=true,[111112313]=true,[12413]=true,[4223]=true,[2312321]=true,[131]=true,[111321221]=true,[1241222]=true,[211122311]=true,[311432]=true,[11311241]=true,[2222222]=true,[143]=true,[3412112]=true,[4241]=true,[12434]=true,[4244]=true,[14211221]=true,[131222]=true,[211241111]=true,[14121113]=true,[3113114]=true,[12443]=true,[1112222]=true,[41123]=true,[114131111]=true,[111111224]=true,[32211113]=true,[3121322]=true,[22231211]=true,[41132]=true,[1321133]=true,[2222]=true,[11432111]=true,[111112223]=true,[111122213]=true,[11114231]=true,[11231411]=true,[223412]=true,[4311221]=true,[113111222]=true,[12413111]=true,[111222113]=true,[4221113]=true,[111223112]=true,[21121211]=true,[112111223]=true,[223421]=true,[21121214]=true,[1413311]=true,[112121213]=true,[133313]=true,[11323112]=true,[2243]=true,[342212]=true,[112221113]=true,[2423]=true,[131111111]=true,[31442]=true,[3111113]=true,[131111114]=true,[43211]=true,[122111213]=true,[342221]=true,[43214]=true,[123211112]=true,[41212112]=true,[11141123]=true,[13133]=true,[133331]=true,[122112212]=true,[222111113]=true,[242111]=true,[223111112]=true,[12241112]=true,[4313]=true,[11311322]=true,[1114331]=true,[111112412]=true,[111113111]=true,[3111134]=true,[422111]=true,[224]=true,[31313]=true,[422114]=true,[211114211]=true,[11142311]=true,[131111141]=true,[123212]=true,[313211111]=true,[11131112]=true,[43241]=true,[111112142]=true,[2431211]=true,[414311]=true,[112111142]=true,[4334]=true,[14211311]=true,[112121132]=true,[1411313]=true,[242]=true,[31111313]=true,[422132]=true,[111231221]=true,[111111413]=true,[4343]=true,[112111412]=true,[111141113]=true,[24422]=true,[1321211]=true,[1413131]=true,[422141]=true,[1321214]=true,[11214221]=true,[141111311]=true,[3131111]=true,[111311213]=true,[1221341]=true,[4421111]=true,[131333]=true,[3113222]=true,[22223111]=true,[412111112]=true,[112223111]=true,[111311114]=true,[211411211]=true,[11131223]=true,[1112333]=true,[211214]=true,[41231]=true,[142111112]=true,[111331112]=true,[41234]=true,[424211]=true,[111233111]=true,[32211221]=true,[114143]=true,[21113111]=true,[11411231]=true,[1321241]=true,[21113114]=true,[41243]=true,[111311132]=true,[2333]=true,[311111213]=true,[11342111]=true,[334112]=true,[311112212]=true,[142142]=true,[311122211]=true,[311212112]=true,[4221221]=true,[312211112]=true,[342311]=true,[411111113]=true,[4131113]=true,[21121322]=true,[4221131]=true,[211244]=true,[311111132]=true,[222113]=true,[312242]=true,[1114133]=true,[43313]=true,[122113211]=true,[111122231]=true,[24221111]=true,[3111221]=true,[131111222]=true,[311]=true,[3111224]=true,[22221113]=true,[43322]=true,[231121211]=true,[4412]=true,[111222131]=true,[11122313]=true,[1442111]=true,[23111141]=true,[3111233]=true,[141211211]=true,[13222211]=true,[11211224]=true,[4421]=true,[114113]=true,[2423111]=true,[4424]=true,[21111113]=true,[3111242]=true,[2222411]=true,[332]=true,[11212223]=true,[422222]=true,[332111]=true,[112221131]=true,[4433]=true,[332114]=true,[131411]=true,[1411412]=true,[341]=true,[131414]=true,[1313111]=true,[344]=true,[33113]=true,[1313114]=true,[2341211]=true,[11222213]=true,[1411421]=true,[1112414]=true,[11223212]=true,[31222112]=true,[123233]=true,[41231111]=true,[3322211]=true,[112122212]=true,[122111231]=true,[12211223]=true,[331211111]=true,[14211131]=true,[11131241]=true,[1321322]=true,[2411]=true,[41324]=true,[332141]=true,[2414]=true,[12221213]=true,[222112112]=true,[131441]=true,[12321113]=true,[113111411]=true,[12322112]=true,[41333]=true,[111311222]=true,[33143]=true,[1141112]=true,[2421113]=true,[211322]=true,[11211131]=true,[2311241]=true,[222111131]=true,[41342]=true,[311114111]=true,[12211241]=true,[211112321]=true,[22212212]=true,[334211]=true,[22311113]=true,[22312112]=true,[21113222]=true,[33311111]=true,[31112]=true,[1311113]=true,[23311112]=true,[114211211]=true,[2444]=true,[1141133]=true,[111111131]=true,[3111311]=true,[1114412]=true,[22411211]=true,[3111314]=true,[14111123]=true,[11211113]=true,[2122133]=true,[1141142]=true,[231113111]=true,[122123111]=true,[12211112]=true,[111111134]=true,[3111323]=true,[14111132]=true,[43421]=true,[322133]=true,[13214111]=true,[1131143]=true,[414113]=true,[112111133]=true,[112121123]=true,[3111332]=true,[22221221]=true,[422]=true,[23411111]=true,[122111123]=true,[111111431]=true,[11123114]=true,[11111243]=true,[211112213]=true,[3111341]=true,[12231113]=true,[431]=true,[11211143]=true,[311112113]=true,[434]=true,[414131]=true,[11143211]=true,[332213]=true,[244211]=true,[213431]=true,[21111224]=true,[3113111]=true,[11131322]=true,[443]=true,[11112233]=true,[11224211]=true,[332222]=true,[3314111]=true,[112114112]=true,[111111323]=true,[242114]=true,[31222211]=true,[111114131]=true,[33221]=true,[41414]=true,[1223111]=true,[33224]=true,[231111113]=true,[1223114]=true,[112113131]=true,[1222223]=true,[123341]=true,[11431211]=true,[41423]=true,[412112]=true,[33233]=true,[111242111]=true,[3232211]=true,[112142111]=true,[311111123]=true,[111141131]=true,[113111]=true,[41432]=true,[11121113]=true,[113114]=true,[1141211]=true,[321111221]=true,[242141]=true,[1141214]=true,[113222111]=true,[3142112]=true,[41441]=true,[11114132]=true,[2122211]=true,[111311231]=true,[2421221]=true,[2122214]=true,[111131111]=true,[112411112]=true,[211433]=true,[111131114]=true,[142111211]=true,[111411131]=true,[14111213]=true,[31214]=true,[112112111]=true,[11141213]=true,[3312113]=true,[112112114]=true,[131111411]=true,[111413]=true,[3111413]=true,[13112321]=true,[321221111]=true,[1311224]=true,[1141241]=true,[112221311]=true,[114121211]=true,[22231112]=true,[111311123]=true,[3111422]=true,[14111231]=true,[11131142]=true,[2122241]=true,[11141132]=true,[11422211]=true,[111331211]=true,[111131141]=true,[11134112]=true,[32111111]=true,[1332113]=true,[31241]=true,[32111114]=true,[422411]=true,[31244]=true,[414221]=true,[1221134]=true,[1143311]=true,[11411213]=true,[324113]=true,[1132232]=true,[31111214]=true,[11131412]=true,[123413]=true,[11123222]=true,[1221143]=true,[2243111]=true,[14112212]=true,[14212112]=true,[111131]=true,[14131112]=true,[23112221]=true,[111134]=true,[33311]=true,[311111231]=true,[332321]=true,[33314]=true,[4121123]=true,[21111332]=true,[32111141]=true,[31111223]=true,[214211111]=true,[311211131]=true,[31121213]=true,[431114]=true,[33323]=true,[4121132]=true,[31221113]=true,[242222]=true,[3224111]=true,[4133]=true,[411111131]=true,[11211314]=true,[111311411]=true,[33332]=true,[231111221]=true,[1223222]=true,[1133111]=true,[144311]=true,[114111311]=true,[1133114]=true,[11211323]=true,[22211132]=true,[33341]=true,[42211112]=true,[2114111]=true,[31211111]=true,[1141313]=true,[2114114]=true,[21113411]=true,[11211332]=true,[11121221]=true,[113222]=true,[23111]=true,[11121224]=true,[23311211]=true,[23114]=true,[4123211]=true,[13131221]=true,[11211341]=true,[1123133]=true,[31111412]=true,[111114221]=true,[31212113]=true,[2122322]=true,[21232211]=true,[3312212]=true,[2331221]=true,[111131222]=true,[114113111]=true,[12223211]=true,[2241113]=true,[31322]=true,[211141211]=true,[1134221]=true,[3312221]=true,[112112222]=true,[131222111]=true,[1222241]=true,[3222113]=true,[114233]=true,[11213411]=true,[1311332]=true,[23141]=true,[31334]=true,[2411111]=true,[23144]=true,[1131113]=true,[2411114]=true,[12323111]=true,[111112421]=true,[123323]=true,[214133]=true,[31343]=true,[11123312]=true,[2112113]=true,[1421111]=true,[3222131]=true,[1241411]=true,[21111413]=true,[32111222]=true,[11211242]=true,[111224]=true,[21113]=true,[1221242]=true,[132121211]=true,[12341]=true,[324221]=true,[11212241]=true,[111313211]=true,[11242112]=true,[234113]=true,[11222231]=true,[1313411]=true,[1122323]=true,[33413]=true,[11322131]=true,[242111111]=true,[11411111]=true,[114111113]=true,[111242]=true,[113141]=true,[311121221]=true,[22211213]=true,[33422]=true,[2112143]=true,[1221224]=true,[242321]=true,[11111441]=true,[1432211]=true,[41112212]=true,[11211413]=true,[12321131]=true,[33431]=true,[1232213]=true,[412313]=true,[1233212]=true,[114111131]=true,[311411111]=true,[222111311]=true,[11211422]=true,[3134111]=true,[22211231]=true,[2221223]=true,[22311131]=true,[322211]=true,[1141412]=true,[1232231]=true,[322214]=true,[11211431]=true,[122131112]=true,[2332112]=true,[111111311]=true,[313111211]=true,[11111231]=true,[1141421]=true,[2114222]=true,[21224111]=true,[411112112]=true,[1111223]=true,[142211]=true,[14111411]=true,[11121332]=true,[1311413]=true,[23222]=true,[211133111]=true,[322232]=true,[1121213]=true,[1122212]=true,[112321211]=true,[1221113]=true,[31212221]=true,[441131]=true,[1221311]=true,[31424]=true,[322241]=true,[1221314]=true,[12221123]=true,[311121113]=true,[2241221]=true,[1113134]=true,[222311111]=true,[331111112]=true,[31433]=true,[11131211]=true,[111211211]=true,[12221132]=true,[3222221]=true,[111211214]=true,[4412111]=true,[11211134]=true,[3132113]=true,[111314]=true,[11123411]=true,[1221332]=true,[1131221]=true,[2411222]=true,[132113111]=true,[1131224]=true,[4113113]=true,[11212133]=true,[111323]=true,[11111132]=true,[2112221]=true,[433211]=true,[22211123]=true,[2112224]=true,[21222113]=true,[11111123]=true,[11242211]=true,[111332]=true,[21221]=true,[2111414]=true,[443111]=true,[21224]=true,[211131113]=true,[111114311]=true,[242411]=true,[113441]=true,[234221]=true,[11112413]=true,[1424111]=true,[111344]=true,[144113]=true,[1122242]=true,[1223411]=true,[11412212]=true,[114111221]=true,[1222142]=true,[23141111]=true,[1232132]=true,[1113323]=true,[411113]=true,[11113211]=true,[412412]=true,[11412221]=true,[11113214]=true,[314111]=true,[1133312]=true,[11322113]=true,[314114]=true,[113411]=true,[11111423]=true,[412421]=true,[113414]=true,[13122311]=true,[4111112]=true,[132111113]=true,[111141311]=true,[314123]=true,[111123212]=true,[11214131]=true,[12213131]=true,[113423]=true,[23312]=true,[1221413]=true,[322322]=true,[111131411]=true,[314132]=true,[1222412]=true,[2221412]=true,[13241111]=true,[1124411]=true,[11113241]=true,[11114123]=true,[322331]=true,[122423]=true,[314141]=true,[1121432]=true,[232223]=true,[142112]=true,[1422113]=true,[111411311]=true,[11141231]=true,[31122212]=true,[23333]=true,[4111142]=true,[3222311]=true,[422111111]=true,[122211113]=true,[124211]=true,[43111211]=true,[11133131]=true,[11111213]=true,[23342]=true,[12221231]=true,[141112112]=true,[312113]=true,[1141223]=true,[32111411]=true,[13111322]=true,[142133]=true,[1122413]=true,[3341111]=true,[112141112]=true,[1411223]=true,[111211322]=true,[122211131]=true,[1421213]=true,[3132221]=true,[111422]=true,[11234111]=true,[112113221]=true,[314]=true,[11111234]=true,[4121411]=true,[1131332]=true,[4113221]=true,[31211]=true,[413111111]=true,[311211311]=true,[112311113]=true,[111434]=true,[33211211]=true,[2112332]=true,[21222221]=true,[1133222]=true,[312143]=true,[31221131]=true,[11121143]=true,[411111311]=true,[111443]=true,[21332]=true,[211131221]=true,[41111231]=true,[212321111]=true,[4111223]=true,[41211131]=true,[4121213]=true,[11123111]=true,[2231132]=true,[144221]=true,[3431]=true,[1334111]=true,[31121123]=true,[1223141]=true,[111311]=true,[13114211]=true,[1121231]=true,[314213]=true,[31113131]=true,[211211111]=true,[312233]=true,[11141411]=true,[211211114]=true,[2114411]=true,[1121132]=true,[4141112]=true,[314222]=true,[224111]=true,[33111131]=true,[11232113]=true,[224114]=true,[23411]=true,[11234]=true,[132111221]=true,[23414]=true,[314231]=true,[43133]=true,[12213113]=true,[111311111]=true,[2233211]=true,[11132]=true,[4121231]=true,[11114411]=true,[23423]=true,[31114112]=true,[111124211]=true,[111224111]=true,[3214211]=true,[1422212]=true,[211211141]=true,[142214]=true,[31122311]=true,[112123211]=true,[4111241]=true,[11212421]=true,[232331]=true,[1121342]=true,[1422221]=true,[1123214]=true,[14132111]=true,[111412112]=true,[23441]=true,[11222411]=true,[2411411]=true,[312212]=true,[13112213]=true,[1122341]=true,[3132311]=true,[13321112]=true,[122121113]=true,[111113114]=true,[13211]=true,[11111324]=true,[2112413]=true,[13214]=true,[32222111]=true,[312224]=true,[142241]=true,[12211421]=true,[113122211]=true,[122213111]=true,[21413]=true,[12221411]=true,[222131111]=true,[31411112]=true,[1123241]=true,[31223]=true,[123212111]=true,[12321311]=true,[2231213]=true,[11111342]=true,[31112111]=true,[1332131]=true,[134312]=true,[31112114]=true,[222131]=true,[222113111]=true,[3212213]=true,[222134]=true,[2141111]=true,[22211411]=true,[13241]=true,[2141114]=true,[33121211]=true,[13244]=true,[12211133]=true,[1224131]=true,[222143]=true,[223112111]=true,[22311311]=true,[2231231]=true,[21443]=true,[223223]=true,[2331131]=true,[12211142]=true,[431111111]=true,[234212]=true,[111111113]=true,[11111411]=true,[3122123]=true,[11211311]=true,[31112141]=true,[23]=true,[1244111]=true,[1111241]=true,[314321]=true,[1121234]=true,[311123111]=true,[3122132]=true,[2141141]=true,[211211222]=true,[11441111]=true,[1221131]=true,[111113141]=true,[1222133]=true,[1121243]=true,[112112141]=true,[2311133]=true,[224222]=true,[134111]=true,[1414112]=true,[311111111]=true,[134114]=true,[31114211]=true,[21221111]=true,[12213221]=true,[122213]=true,[111111143]=true,[311131112]=true,[142313]=true,[31421111]=true,[214111211]=true,[111113]=true,[2311211]=true,[111113411]=true,[122211311]=true,[11243]=true,[1112243]=true,[142322]=true,[3124211]=true,[112112411]=true,[311112221]=true,[11111414]=true,[112133111]=true,[1232123]=true,[4141211]=true,[1123322]=true,[2231123]=true,[1111133]=true,[134141]=true,[1121123]=true,[113114111]=true,[11111333]=true,[1242113]=true,[11211233]=true,[312323]=true,[111143111]=true,[122121221]=true,[111113222]=true,[411311111]=true,[11111432]=true,[2223113]=true,[13322]=true,[31411211]=true,[312332]=true,[11214311]=true,[141422]=true,[1412111]=true,[222224]=true,[132113]=true,[1412114]=true,[1221431]=true,[1114313]=true,[31112213]=true,[123242]=true,[33113111]=true,[223142]=true,[222233]=true,[31111322]=true,[3421211]=true,[111143]=true,[11232221]=true,[31112222]=true,[4142111]=true,[131112113]=true,[3212321]=true,[222242]=true,[131122211]=true,[1111433]=true,[431141]=true,[2141222]=true,[113411111]=true,[3331112]=true,[3113]=true,[1221323]=true,[314411]=true,[1121324]=true,[1412141]=true,[2311214]=true,[132143]=true,[11131421]=true,[113112113]=true,[1113242]=true,[111413111]=true,[4111412]=true,[1121333]=true,[1114241]=true,["collect"]=true,[2221112]=true,[11241311]=true,[1124231]=true,[3131]=true,[11324]=true,[4111421]=true,[3134]=true,[12213311]=true,[2223131]=true,[111111233]=true,[1113131]=true,[11131313]=true,[11142212]=true,[11333]=true,[1241111]=true,[3143]=true,[1111112]=true,[33111113]=true,[111111242]=true,[311131211]=true,[142412]=true,[2221133]=true,[134222]=true,[111332111]=true,[11133311]=true,[1113431]=true,[112442]=true,[322223]=true,[322313]=true,[11312213]=true,[2221142]=true,[1332311]=true,[1112]=true,[1143131]=true,[311111114]=true,[44123]=true,[1411241]=true,[312413]=true,[41411]=true,[142112111]=true,[432221]=true,[142223]=true,[11314211]=true,[111322211]=true,[44132]=true,[1411133]=true,[1111142]=true,[222311]=true,[41131112]=true,[311211113]=true,[222314]=true,[11222123]=true,[141413]=true,[1242221]=true,[311113211]=true,[31111421]=true,[311213111]=true,[12211313]=true,[312212111]=true,[21124211]=true,[11222132]=true,[2223221]=true,[431222]=true,[341111]=true,[3122231]=true,[13433]=true,[341114]=true,[31321211]=true,[222332]=true,[132221]=true,[1412222]=true,[131114111]=true,[132224]=true,[3114113]=true,[222211211]=true,[341123]=true,[411113111]=true,[222341]=true,[1121414]=true,[314111111]=true,[1113224]=true,[34211]=true,[11121413]=true,[3331211]=true,[341132]=true,[412112111]=true,[41211311]=true,[1121423]=true,[412223]=true,[3122321]=true,[111111314]=true,[11411]=true,[422213]=true,[341141]=true,[11414]=true,[1112423]=true,[3224]=true,[3111131]=true,[2311322]=true,[224411]=true,[122111132]=true,[113112221]=true,[311213]=true,[11423]=true,[4222112]=true,[3233]=true,[33221111]=true,[4111133]=true,[111111332]=true,[21122213]=true,[3111431]=true,[131411111]=true,[11432]=true,[3411113]=true,[3242]=true,[343211]=true,[311243]=true,[111111341]=true,[411143]=true,[412142]=true,[3112112]=true,[11441]=true,[3114131]=true,[1324211]=true,[11444]=true,[44213]=true,[4113131]=true,[41213111]=true,[411413]=true,[2221241]=true,[3141131]=true,[3411131]=true,[331112111]=true,[23312111]=true,[114311]=true,[111314111]=true,[331223]=true,[11312321]=true,[341213]=true,[214211]=true,[441113]=true,[3112133]=true,[214214]=true,[44231]=true,[11431112]=true,[423113]=true,[122311211]=true,[41131211]=true,[1111244]=true,[222413]=true,[3112142]=true,[11132111]=true,[11113322]=true,[11113133]=true,[11132114]=true,[11114321]=true,[12211412]=true,[11124311]=true,[222422]=true,[31313111]=true,[112131221]=true,[1241]=true,[11213222]=true,[13141211]=true,[1244]=true,[211111133]=true,[112141211]=true,[1113311]=true,[111142112]=true,[214241]=true,[1113314]=true,[2141411]=true,[42212]=true,[1322213]=true,[341222]=true,[3323111]=true,[112241111]=true,[41211113]=true,[11324111]=true,[3122411]=true,[132332]=true,[3114221]=true,[34133]=true,[3311]=true,[122131211]=true,[111312113]=true,[3314]=true,[1221422]=true,[1113332]=true,[212213]=true,[122231111]=true,[21413111]=true,[31141112]=true,[42233]=true,[1222421]=true,[3323]=true,[3114311]=true,[1113341]=true,[111111422]=true,[211322111]=true,[1232411]=true,[21114113]=true,[42242]=true,[11134211]=true,[3332]=true,[22213211]=true,[2221421]=true,[332111111]=true,[22313111]=true,[31311113]=true,[2231411]=true,[134411]=true,[223241]=true,[3341]=true,[313211]=true,[33111311]=true,[3344]=true,[21122321]=true,[2331311]=true,[212243]=true,[122132]=true,[3411221]=true,[11213111]=true,[12212111]=true,[31113113]=true,[3321113]=true,[1111421]=true,[212221211]=true,[112131113]=true,[131112221]=true,[1121411]=true,[3112223]=true,[11114213]=true,[1313]=true,[11213114]=true,[1234211]=true,[11214113]=true,[1112441]=true,[1111334]=true,[322211111]=true,[122231]=true,[21411113]=true,[11133113]=true,[211111211]=true,[423212]=true,[11213141]=true,[211111214]=true,[1111343]=true,[1144112]=true,[3112241]=true,[214322]=true,[431411]=true,[1222313]=true,[423221]=true,[124214]=true,[13133111]=true,[12323]=true,[333113]=true,[2221313]=true,[1412411]=true,[3111143]=true,[132413]=true,[11132222]=true,[1343]=true,[34112]=true,[1314113]=true,[1111313]=true,[111142211]=true,[11213]=true,[1113413]=true,[413]=true,[42311]=true,[111134111]=true,[211111241]=true,[42314]=true,[333131]=true,[1121441]=true,[11421221]=true,[1113422]=true,[113243]=true,[11212112]=true,[1322321]=true,[12212411]=true,[42323]=true,[111312212]=true,[3413]=true,[22232111]=true,[3233111]=true,[1441112]=true,[41121113]=true,[431111]=true,[31141211]=true,[112133]=true,[111312221]=true,[3422]=true,[1142111]=true,[122123]=true,[212321]=true,[1142114]=true,[32122211]=true,[212324]=true,[42341]=true,[1221233]=true,[14411111]=true,[331112]=true,[13131113]=true,[3434]=true,[11133221]=true,[111431111]=true,[21114221]=true,[11212142]=true,[32111]=true,[1114421]=true,[11243111]=true,[32114]=true,[3443]=true,[1111412]=true,[31311221]=true,[12242111]=true,[212213111]=true,[1224311]=true,[3112313]=true,[122234]=true,[44411]=true,[2223311]=true,[331133]=true,[222431]=true,[22343]=true,[1111424]=true,[111431]=true,[11132141]=true,[122243]=true,[1412]=true,[3321221]=true,[331142]=true,[11423111]=true,[2111111]=true,[3231113]=true,[33131111]=true,[3112331]=true,[2113331]=true,[1421]=true,[11132411]=true,[112121231]=true,[1424]=true,[11124113]=true,[1111442]=true,[1144211]=true,[222323]=true,[21411221]=true,[1113233]=true,[331421]=true,[11342]=true,[1433]=true,[211111322]=true,[11341211]=true,[3411311]=true,[4111313]=true,[21421211]=true,[21112223]=true,[141311]=true,[11132321]=true,[124322]=true,[341411]=true,[141131111]=true,[333221]=true,[34214]=true,[14113211]=true,[31111241]=true,[212211113]=true,[21113141]=true,[11331221]=true,[141431]=true,[42413]=true,[14132]=true,[34223]=true,[141323]=true,[1224113]=true,[144131]=true,[122111411]=true,[311231111]=true,[31123211]=true,[42422]=true,[31133111]=true,[3112421]=true,[11421113]=true,[413114]=true,[1441211]=true,[311342]=true,[31223111]=true,[312341]=true,[32114111]=true,[411131111]=true,[34241]=true,[2114141]=true,[2422211]=true,[411242]=true,[1142213]=true,[412241]=true,[3143111]=true,[42212111]=true,[4221311]=true,[23111114]=true,[331211]=true,[422231]=true,[2123213]=true,[331214]=true,[112412111]=true,[212432]=true,[111132113]=true,[311231]=true,[114131]=true,[122324]=true,[413141]=true,[114134]=true,[14321111]=true,[41213]=true,[112113113]=true,[31112411]=true,[13212221]=true,[3112412]=true,[122333]=true,[32222]=true,[1312223]=true,[1222112]=true,[412133]=true,[422123]=true,[311123]=true,[31142111]=true,[311111141]=true,[122342]=true,[13211111]=true,[4113311]=true,[31131113]=true,[13211114]=true,[113311211]=true,[243113]=true,[241133]=true,[31142]=true,[311423]=true,[112112]=true,[32112113]=true,[32213]=true,[32243]=true,[3141311]=true,[3231221]=true,[31412]=true,[131141111]=true,[113221112]=true,[3141113]=true,[34112111]=true,[411131]=true,[341231]=true,[11124221]=true,[411134]=true,[333311]=true,[34142]=true,[11123141]=true,[11411114]=true,[111222311]=true,[11122331]=true,[13211141]=true,[111422111]=true,[3311111]=true,[112111112]=true,[34313]=true,[3311114]=true,[21112331]=true,[112311221]=true,[2322311]=true,[112142]=true,[112421111]=true,[331111211]=true,[1134311]=true,[34322]=true,[3311123]=true,[12231221]=true,[243221]=true,[122411111]=true,[1433111]=true,[12241211]=true,[11212313]=true,[12341111]=true,[34331]=true,[3311132]=true,[1224221]=true,[11231111]=true,[2414111]=true,[111212213]=true,[1134113]=true,[1113221]=true,[1123211]=true,[1112111]=true,[3311141]=true,[413222]=true,[323111]=true,[111211241]=true,[11331113]=true,[323114]=true,[122411]=true,[111311141]=true,[114221]=true,[122414]=true,[11122223]=true,[114224]=true,[24113]=true,[11131214]=true,[11132213]=true,[3142211]=true,[112421]=true,[23111222]=true,[111341111]=true,[11122232]=true,[2123321]=true,[331322]=true,[241211]=true,[111211133]=true,[111132221]=true,[241214]=true,[31221311]=true,[122432]=true,[32321]=true,[114242]=true,[112121411]=true,[32324]=true,[323141]=true,[1113113]=true,[233111111]=true,[3223112]=true,[1431113]=true,[11131133]=true,[1312331]=true,[11231]=true,[32333]=true,[1142]=true,[24143]=true,[112313111]=true,[2412113]=true,[11411141]=true,[41111123]=true,[1334]=true,[31131221]=true,[13211222]=true,[32321111]=true,[411224]=true,[321113]=true,[112313]=true,[1113143]=true,[41111132]=true,[32112221]=true,[1223]=true,[112223]=true,[12233111]=true,[411233]=true,[122441]=true,[13343]=true,[4122212]=true,[3141221]=true,[111231113]=true,[4331111]=true,[1112411]=true,[111341]=true,[31211114]=true,[131311211]=true,[34412]=true,[3311213]=true,[12233]=true,[11123]=true,[114112112]=true,[112241]=true,[112343]=true,[111233]=true,[112244]=true,[34421]=true,[3311222]=true,[321143]=true,[1142222]=true,[21141113]=true,[3221114]=true,[41113211]=true,[11212412]=true,[1143221]=true,[114422]=true,[3311231]=true,[1143113]=true,[1142141]=true,[114314]=true,[111214211]=true,[14121221]=true,[31211141]=true,[114341]=true,[1343111]=true,[34111112]=true,[112111241]=true,[2111114]=true,[1142411]=true,[141311111]=true,[323213]=true,[1413221]=true,[122132111]=true,[14231111]=true,[2441]=true,[142421]=true,[114323]=true,[331412]=true,[3221141]=true,[323222]=true,[233111]=true,[14231]=true,[11241113]=true,[233114]=true,[32411]=true,[114332]=true,[24221]=true,[32414]=true,[112113311]=true,[24224]=true,[14123111]=true,[141341]=true,[233123]=true,[14123]=true,[2111141]=true,[24111113]=true,[32423]=true,[2111144]=true,[24233]=true,[241322]=true,[11241131]=true,[233132]=true,[41111213]=true,[1442]=true,[411311]=true,[32432]=true,[21132311]=true,[411314]=true,[11411123]=true,[32221211]=true,[233141]=true,[411211211]=true,[41121221]=true,[3122213]=true,[1341113]=true,[131111]=true,[411323]=true,[11411132]=true,[2412221]=true,[43211111]=true,[1132223]=true,[4114112]=true,[1133]=true,[4223111]=true,[211222211]=true,[411332]=true,[321221]=true,[134111111]=true,[2113223]=true,[321224]=true,[231113]=true,[211211]=true,[111122123]=true,[241211111]=true,[411341]=true,[112334]=true,[22223]=true,[2411141]=true,[112111313]=true,[41123111]=true,[1142321]=true,[111122132]=true,[3242111]=true,[31211222]=true,[4241111]=true,[22232]=true,[2144]=true,[3313211]=true,[11413211]=true,[33242]=true,[441311]=true,[33131]=true,[331313]=true,[124133]=true,[312111221]=true,[3413111]=true,[413411]=true,[33134]=true,[21141221]=true,[3221222]=true,[22331111]=true,[4411112]=true,[224111111]=true,[3131114]=true,[322111211]=true,[31121132]=true,[114413]=true,[134]=true,[4112111]=true,[323312]=true,[21332111]=true,[4112114]=true,[311111411]=true,[11322311]=true,[311441]=true,[2111222]=true,[24311]=true,[1132331]=true,[323321]=true,[21221114]=true,[211211411]=true,[3221]=true,[233213]=true,[1341221]=true,[114431]=true,[442112]=true,[2333111]=true,[1141322]=true,[1311143]=true,[12222212]=true,[3131141]=true,[233222]=true,[143111]=true,[124111211]=true,[12411221]=true,[143114]=true,[24211211]=true,[24332]=true,[4112141]=true,[241111211]=true,[233231]=true,[122212112]=true,[3113141]=true,[132221111]=true,[13211411]=true,[11112212]=true,[21221141]=true,[11411222]=true,[141113111]=true,[211133]=true,[1132313]=true,[1311221]=true,[1124123]=true,[112412]=true,[323111111]=true,[411422]=true,[211214111]=true,[332411]=true,[111212321]=true,[11412113]=true,[12411113]=true,[1124132]=true,[143141]=true,[21121241]=true,[411431]=true,[112424]=true,[22313]=true,[233]=true,[14311211]=true,[4331]=true,[313133]=true,[3241211]=true,[4231211]=true,[41411111]=true,[112433]=true,[11112242]=true,[3311411]=true,[321332]=true,[231221]=true,[113141111]=true,[32141111]=true,[231224]=true,[141113]=true,[1421114]=true,[22331]=true,[11414111]=true,[112111421]=true,[22334]=true,[44321]=true,[124241]=true,[23122211]=true,[224141]=true,[1421123]=true,[34211111]=true,[1131413]=true,[211241]=true,[311111]=true,[113144]=true,[141111113]=true,[311114]=true,[141131]=true,[1421132]=true,[2133311]=true,[141134]=true,[31121231]=true,[323]=true,[211212113]=true,[341111111]=true,[323411]=true,[213323]=true,[1421141]=true,[3131222]=true,[141143]=true,[1431221]=true,[4442]=true,[1313222]=true,[141111131]=true,[311132]=true,[24413]=true,[4112222]=true,[311222111]=true,[12214112]=true,[21111143]=true,[1133141]=true,[442211]=true,[1313141]=true,[311141]=true,[21221222]=true,[23114111]=true,[311144]=true,[11333111]=true,[1133411]=true,[1423211]=true,[22433]=true,[143213]=true,[32141]=true,[2144111]=true,[113333]=true,[32144]=true,[143111111]=true,[41111411]=true,[31133]=true,[1124213]=true,[143222]=true,[231221111]=true,[1333112]=true,[1314221]=true,[24113111]=true,[312121211]=true,[14321]=true,[3211133]=true,[313214]=true,[13322111]=true,[23112113]=true,[111114113]=true,[21111221]=true,[11112323]=true,[311311211]=true,[321413]=true,[14243]=true,[313223]=true,[223112]=true,[3113411]=true,[11231114]=true,[42211211]=true,[23111111]=true,[13212113]=true,[324311]=true,[31412111]=true,[41311211]=true,[4131221]=true,[12212114]=true,[31211411]=true,[2232212]=true,[11112341]=true,[32411111]=true,[2441111]=true,[22424]=true,[313241]=true,[14234]=true,[14221211]=true,[2331113]=true,[223133]=true,[413111]=true,[3422111]=true,[112222112]=true,[2142113]=true,[31421]=true,[3221411]=true,[231332]=true,[11231141]=true,[1421222]=true,[124211111]=true,[141224]=true,[111411113]=true,[22442]=true,[32311211]=true,[321121211]=true,[12212141]=true,[13111214]=true,[1421231]=true,[111112112]=true,[141233]=true,[31112321]=true,[2111411]=true,[12212]=true,[4133111]=true,[311222]=true,[212211221]=true,[32221112]=true,[1122233]=true,[141242]=true,[4321211]=true,[31214111]=true,[211212221]=true,[242213]=true,[434111]=true,[3431111]=true,[311111222]=true,[311234]=true,[233411]=true,[21143111]=true,[111112133]=true,[241241]=true,[114311111]=true,[31111112]=true,[13111241]=true,[21143]=true,[3211211]=true,[3221111]=true,[24311111]=true,[3211214]=true,[311132111]=true,[13111211]=true,[2111441]=true,[12242]=true,[11411411]=true,[13111133]=true,[32441]=true,[24314]=true,[312113111]=true,[14213]=true,[143321]=true,[24341]=true,[231143]=true,[34111211]=true,[31111133]=true,[23111411]=true,[13411211]=true,[311141111]=true,[1124321]=true,[33111221]=true,[2314211]=true,[321111113]=true,[321113111]=true,[31111142]=true,[111323111]=true,[331241]=true,[3211241]=true,[313322]=true,[111122411]=true,[23222111]=true,[3121133]=true,[2111333]=true,[312221]=true,[2224112]=true,[432113]=true,[24121211]=true,[313331]=true,[14324]=true,[231413]=true,[11231222]=true,[14213111]=true,[31241111]=true,[1413113]=true,[312221111]=true,[111241211]=true,[42311111]=true,[14333]=true,[12212222]=true,[31322111]=true,}
local E, L, V, P, G, _ = unpack(ElvUI); --Inport: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local R = E:NewModule('RLBox', 'AceEvent-3.0', 'AceTimer-3.0') RLBox = R local LibGroupInspect = LibStub("LibGroupInSpecT-1.1") if not LibGroupInspect then return; end local WPCache = {} local WHISPERMSG = "EUI:".. L["Group %s has been casted and ending in %d seconds, Prepare!"]; local SPELLID_SOULSTONERESURRECTION = 20707 local SPELLID_SOULSTONERESURRECTION_WHENDEAD = 95750 local castMsg = "EUI:%s ".. L['Casted'].." \124cff71d5ff\124Hspell:%d\124h[%s]\124h\124r!"..L['Duration']..":%ss"; local readyMsg = "EUI:%s 's \124cff71d5ff\124Hspell:%d\124h[%s]\124h\124r ".. READY..'!'; local OFFLINETEXTURE = 137007; local len, gmatch, tsort, ceil, format, floor = string.len, string.gmatch, table.sort, math.ceil, string.format, math.floor local pairs, tostring, unpack, tonumber, select = pairs, tostring, unpack, tonumber, select local IsInInstance = IsInInstance local GetInstanceInfo = GetInstanceInfo local GetNumGroupMembers = GetNumGroupMembers local GetNumSubgroupMembers = GetNumSubgroupMembers local UnitGUID = UnitGUID local UnitFactionGroup = UnitFactionGroup local UnitName = UnitName local UnitLevel = UnitLevel local UnitRace = UnitRace local IsPartyLFG = IsPartyLFG local GetSpellInfo = GetSpellInfo local CUSTOM_CLASS_COLORS, RAID_CLASS_COLORS = CUSTOM_CLASS_COLORS, RAID_CLASS_COLORS local SendChatMessage = SendChatMessage local collectgarbage = collectgarbage local PLAYER_IS_WARLOCK local unusedOverlays = {} local RCOLOR = { {.31,.31,.31}, {234/255,18/255,0}, {234/255,134/255,0}, {233/255,220/255,0}, {146/255,232/255,2/255}, {0,233/255,24/255}, {2/255,233/255,174/255}, {2/255,146/255,232/255}, {226/255,2/255,232/255}, {1,1,1} } local REQUIREMENT_KEYS = { --note that class isn't a requirement because it's specified by the spell PLAYER_LEVEL = 10, PLAYER_NAMES = 15, PLAYER_RACE = 20, TALENT_NAME = 25, TALENT_SPEC = 30, } local ADJUSTMENT_KEYS = { PLAYER_NAME = 5, PLAYER_LEVEL = 10, TALENT_NAME = 25, TALENT_SPEC = 30, } local function FormatTime(time) if time >= 60 then return format("%.2d:%.2d", floor(time / 60), time % 60) else return format("%.2d", time) end end local function BuildPlayerList(guid, info, unit) if not R.Players[guid] then R.Players[guid] = {} end local player = R.Players[guid] player.info = info player.guid = guid player.name = info.name player.realm = info.realm player.class = info.class player.unit = unit return player end local function GetKVTableLength(tab) if not tab then return; end local num = 0 for k, v in pairs(tab) do num = num + 1 end return num end local function GetSpellDuration(spellID) if spellID and E.global.RLBox.SPELL_MONITOR_SCHEMA.spellmetadata[spellID] and E.global.RLBox.SPELL_MONITOR_SCHEMA.spellmetadata[spellID].duration then return tonumber(E.global.RLBox.SPELL_MONITOR_SCHEMA.spellmetadata[spellID].duration) end return -1 end local function CheckUnitIsOut(unit) if not unit then return true; end local inInstance, instanceType = IsInInstance() local _, _, _, _, maxPlayers, _, _ = GetInstanceInfo() local raidNum = GetNumGroupMembers() if inInstance and instanceType == "raid" then raidNum = maxPlayers end if unit and unit:find('raid') and tonumber(string.sub(unit, 5))>raidNum then return true; end return false; end local function ConvertSpellIdIfSoulstone(spellID) if spellID == SPELLID_SOULSTONERESURRECTION or spellID == SPELLID_SOULSTONERESURRECTION_WHENDEAD then return SPELLID_SOULSTONERESURRECTION else return spellID end end local function GetUnitFromName(name, guid) --改为GUID判断识别玩家 if IsInRaid() then local numRaidMembers = GetNumGroupMembers() for i = 1, numRaidMembers do local unit = "raid"..i if UnitGUID(unit) == guid then return unit end end elseif UnitInParty("player") then local numPartyMembers = GetNumSubgroupMembers() for i = 1, numPartyMembers do local unit = "party"..i if UnitGUID(unit) == guid then return unit end end else if UnitGUID('player') == guid then return 'player' end --error("this function wasn't supposed to be called while not in a group. Please report to author") end return nil end local function CheckAlliance(unit, alliance) local playerAlliance = select(1, UnitFactionGroup('player')) if not alliance or playerAlliance == alliance or alliance == 'NONE' then return true else return false end end local function CheckName(unit, name) return UnitName(unit) == name end local function CheckNames(unit, names) if not names then return true end if len(names) == 0 then return true end for v in gmatch(names, "[^ ]+") do if CheckName(unit, v) == true then return true end end return false end local function CheckLevel(unit, level) return UnitLevel(unit) >= level end local function CheckRace(unit, race) return UnitRace(unit) == race end local function IsTalentAvailable(guid, talent_id) local info = LibGroupInspect:GetCachedInfo(guid) if not info then return false end -- We're still waiting to get this data local available = false for key, spellInfo in pairs(info.talents) do if (spellInfo.talent_id == talent_id) then available = true break end end return available; end local function GetPrimarySpecializationForGuid(guid) local info = LibGroupInspect:GetCachedInfo(guid); if not info then return nil end -- We're still waiting to get this data return info.global_spec_id; end local function CheckTalentName(guid, talent_id) if not talent_id or talent_id == 0 then return; end local available = IsTalentAvailable(guid, talent_id); return available; end local function CheckTalentSpec(guid, specializationId, specializationId2) if not specializationId or specializationId == 0 then return true; end local specId = GetPrimarySpecializationForGuid(guid) --returns the name of the primary talent tree return ((specId == specializationId) or (specId == specializationId2)) end local function CheckRequirement(guid, unit, requirement) if requirement.k == REQUIREMENT_KEYS.PLAYER_LEVEL then return CheckLevel(unit, requirement.level) elseif requirement.k == REQUIREMENT_KEYS.PLAYER_RACE then return CheckRace(unit, requirement.race) elseif requirement.k == REQUIREMENT_KEYS.PLAYER_NAMES then return CheckNames(unit, requirement.names) elseif requirement.k == REQUIREMENT_KEYS.TALENT_NAME then if (requirement.talent_id ~= nil) then return CheckTalentName(guid, requirement.talent_id) end elseif requirement.k == REQUIREMENT_KEYS.TALENT_SPEC then return CheckTalentSpec(guid, requirement.specialization, requirement.specialization2) end end local function CheckSpellRequirements(guid, unit, spellid, specid, specidx) --if we make it through all of the requirements without one returning nil, then return success if specid then if not CheckTalentSpec(guid, specid) then return nil end end if specidx then if (not CheckTalentName(guid, specidx)) then return nil end end for reqSpellId, reqs in pairs(E.global.RLBox.SPELL_MONITOR_SCHEMA.requirements) do if reqSpellId == spellid then for reqindex, req in pairs(reqs) do if not CheckRequirement(guid, unit, req) then return nil end end end end return 1 end local function GetAdjustmentOffset(unit, guid, adjustment) if adjustment.k == ADJUSTMENT_KEYS.PLAYER_NAME then if CheckName(unit, adjustment.name) == true then return adjustment.o end elseif adjustment.k == ADJUSTMENT_KEYS.PLAYER_LEVEL then if CheckLevel(unit, adjustment.level) == true then return adjustment.o end elseif adjustment.k == ADJUSTMENT_KEYS.TALENT_NAME then if CheckTalentName(unit, adjustment.talentIndex) == true then return adjustment.o end elseif adjustment.k == ADJUSTMENT_KEYS.TALENT_SPEC then if CheckTalentSpec(guid, adjustment.specialization) == true then return adjustment.offset end end return nil --no offset end local function GetAdjustedDuration(unit, guid, spellid, duration) local adjusted = duration --if we make it through all of the requirements without one returning nil, then return success for adjSpellId, adjs in pairs(E.global.RLBox.SPELL_MONITOR_SCHEMA.adjustments) do if adjSpellId == spellid then --loop through the adjustments of this spell for adjindex, adj in pairs(adjs) do local offset = GetAdjustmentOffset(unit, guid, adj) if offset then adjusted = adjusted + offset end end end end return adjusted end local function createOverlay(btn) local isize = btn:GetWidth() local overlay = tremove(unusedOverlays) if not overlay then overlay = CreateFrame("Frame", nil, btn, "RLBoxSpellActivationAlert") end overlay:ClearAllPoints() overlay:SetParent(btn) overlay:SetAlpha(0.7) overlay:SetPoint("TOPLEFT", btn, "TOPLEFT", -isize * 0.4, isize * 0.4) overlay:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", isize * 0.4, -isize * 0.4); btn.overlay = overlay overlay.animIn:Play() end function R:OverlayGlowAnimOutFinished(animGroup) local overlay = animGroup:GetParent() overlay:Hide() tinsert(unusedOverlays, overlay) end function R:BuildPlayerSpellCache(player, guid) if player.spellcache then wipe(player.spellcache) end player.spellcache = {} local unit = GetUnitFromName(player.name, guid) if not unit then --error("GetUnitFromName returned nil") return nil --something wrong happened, just return as though they didn't meet requirement. I've seen this before after reloading UI while in a raid end for i = 1, 3 do local anchor = _G['EUIRaidToolBox'..i] local tmptable if anchor then if anchor.ID == 1 then tmptable = E.global.RLBox.DEFAULT_SPELLS end if anchor.ID == 2 then tmptable = E.global.RLBox.OTHER_SPELLS end if anchor.ID == 3 then tmptable = E.global.RLBox.MISC_SPELLS end for _, spell in pairs(tmptable) do local class = spell[1] local spellid = spell[2] local enabled = spell[3] local alliance = spell[4] local cooldown = spell[5] local specid = spell[6] local specidx = spell[7] if enabled and (class == "ANY" or class == player.class) and CheckSpellRequirements(guid, unit, spellid, specid, specidx) and CheckAlliance(unit, alliance) then -- local name, rank, icon, cost, funnel, powerType, castTime, minRange, maxRange = GetSpellInfo(spell.id); --spells without a base duration are NOT followed through with local cds = cooldown or E.global.RLBox.SPELL_MONITOR_SCHEMA.cooldowns[spellid] if cds then --dbg.classes[player.class] then local duration = GetAdjustedDuration(unit, guid, spellid, cds) player.spellcache[spellid] = duration end end end end end end function R:GroupInSpecT_Update(event, guid, unit, info) if info and info.name and info.class_id then local player = BuildPlayerList(guid, info, unit) R:BuildPlayerSpellCache(player, guid) R:CalcBarsNum() end end function R:GroupInSpecT_Remove(guid) if R.Players[guid] and R.Players[guid].name then R.Players[guid] = nil end end local function StopTimer(icon) icon.right:SetText(' ') icon.bar:SetValue(0) icon.bar:SetScript("OnUpdate", nil) WPCache['p'..icon.partyno] = false icon:GetNormalTexture():SetDesaturated(false); if icon.overlay then if icon.overlay.animIn:IsPlaying() then icon.overlay.animIn:Stop() end icon.overlay.animOut:Play() icon.overlay = nil end end local function OnEnter(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT") GameTooltip:AddDoubleLine(self.partytext:GetText()..self.left:GetText()..'-'..self.spellname, self.right:GetText()) GameTooltip:SetClampedToScreen(true) GameTooltip:Show() end local function OnLeave(self) GameTooltip:Hide() end local function OnMouseDown(self, button) if button == "LeftButton" then local channel = self.StartChannel if not channel or channel == 'NONE' then return; end if channel == 'RAID' and IsPartyLFG() then channel = 'INSTANCE_CHAT' end SendChatMessage(format("EUI:%s: %s", (self.partytext:GetText() or ' ')..(self.left:GetText() or ' ')..'-'..(self.spellname or ' '), self.right:GetText() or ' '), channel) elseif button == "RightButton" then StopTimer(self) end end local function PostionBar(anchor, DB) if anchor and anchor.Bars and #anchor.Bars > 0 then if R.db.party then tsort(anchor.Bars, function(a, b) return a.partyno < b.partyno end) else tsort(anchor.Bars, function(a, b) return a.spellid < b.spellid end) end local perrow = ceil(1 + #anchor.Bars /2) if perrow < DB.minperrow then perrow = DB.minperrow end if R.db.UIType == 'bar' then for i = 1, #anchor.Bars do local Icon = anchor.Bars[i] Icon:ClearAllPoints() if i == 1 then Icon:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 2, -6) elseif (i % perrow) == 0 then Icon:SetPoint("LEFT", anchor.Bars[1].bar, "RIGHT", 6, DB.BarHeight + 2) else Icon:SetPoint("TOP", anchor.Bars[i-1], "BOTTOM", 0, -6) end end else for i = 1, #anchor.Bars do local Icon = anchor.Bars[i] Icon:ClearAllPoints() local lastColumnButton = anchor.Bars[i-DB.rownums] if i == 1 then Icon:SetPoint("TOPLEFT", anchor, "BOTTOMLEFT", 2, -6) elseif (i-1) % DB.rownums == 0 then Icon:SetPoint("TOP", lastColumnButton, "BOTTOM", 0, -(DB.FontSize + 6)) else Icon:SetPoint("LEFT", anchor.Bars[i-1], "RIGHT", DB.IconSize/3, 0) end end end end end local function CalcMaxPartyNO()--查询现有减伤条中最大的分组号 local no = 1 local anchor = _G['EUIRaidToolBox1'] if anchor.Bars and #anchor.Bars > 0 then for k = 1, #anchor.Bars -1 do local icon = anchor.Bars[k] no = icon.partyno > no and icon.partyno or no end end return no end local function SendCooldownInfo(partyno, wpTime)--向下一组分组的成员发送密语信息,如果已是最大组则向第一组发送 local anchor = _G['EUIRaidToolBox1'] if anchor.Bars and #anchor.Bars > 0 then for i = 1, #anchor.Bars -1 do local icon = anchor.Bars[i] local target = icon.playername local realm = icon.realm if realm and realm ~= GetRealmName() then target = target..'-'..realm end local msg = format(WHISPERMSG, partyno, wpTime) if (icon.partyno == partyno + 1) or (partyno > 1 and partyno == CalcMaxPartyNO() and icon.partyno == 1) then if icon.curtex ~= OFFLINETEXTURE then SendChatMessage(msg, "WHISPER", nil, target) end end end end end local function iconOnUpdate(self) if self.endTime and self.duration then local time = GetTime(); if (time > self.endTime) then self.endTime = nil self.duration = nil self.durationtext:SetText(' ') if R.db.UIType == 'icon' and self.overlay then if self.overlay.animIn:IsPlaying() then self.overlay.animIn:Stop() end self.overlay.animOut:Play() self.overlay = nil end else local remaining = format('%d', self.endTime - time) self.durationtext:SetText(remaining) if not WPCache['p'..self.partyno] and E.db.RLBox.wpTime > 0 and tonumber(remaining) == E.db.RLBox.wpTime then SendCooldownInfo(self.partyno, E.db.RLBox.wpTime) WPCache['p'..self.partyno] = true end if R.db.UIType == 'icon' and not self.overlay then self:CreateOverlay(); end end end local unit = GetUnitFromName(self.playername, self.guid) if unit and (UnitIsDeadOrGhost(unit) or not UnitIsConnected(unit)) then if self.curtex ~= OFFLINETEXTURE then self:SetNormalTexture(OFFLINETEXTURE) self:GetNormalTexture():SetTexCoord(0.5, 0.75, 0.25, 0.5) self.curtex = OFFLINETEXTURE end else if self.curtex ~= self.oldicon then self:SetNormalTexture(self.oldicon) self:GetNormalTexture():SetTexCoord(0.1, 0.9, 0.1, 0.9) self.curtex = self.oldicon end end if self.curtex == OFFLINETEXTURE then -- E:StopFlash(self) E:Flash(self, 1.2) else E:StopFlash(self) end end function R:UpdateBoxUI(anchor, toggle) if not anchor then return; end if InCombatLockdown() then E:Print(L["ATTENTION_TIP4"]); return; end if #anchor.Bars > 0 then for n = 1, #anchor.Bars do if anchor.Bars[n] then anchor.Bars[n]:Hide() if toggle then StopTimer(anchor.Bars[n]) end -- anchor.Bars[n] = nil end end wipe(anchor.Bars) end local tmptable, DB if anchor.ID == 1 then tmptable = E.global.RLBox.DEFAULT_SPELLS DB = R.db.DEFAULT end if anchor.ID == 2 then tmptable = E.global.RLBox.OTHER_SPELLS DB = R.db.OTHER end if anchor.ID == 3 then tmptable = E.global.RLBox.MISC_SPELLS DB = R.db.MISC end local barid = 0 for i, default in pairs(tmptable) do local class = default[1] local spellid = default[2] local enabled = default[3] local alliance = default[4] local cooldown = default[5] local title,_, icon = GetSpellInfo(spellid) if not class then class = "PRIEST" end local color = (CUSTOM_CLASS_COLORS and CUSTOM_CLASS_COLORS[class] or RAID_CLASS_COLORS[class]) if enabled then for playerGuid, player in pairs(R.Players) do local unit = GetUnitFromName(player.name, playerGuid) -- local cds = cooldown or player.spellcache[spellid] local cds = player.spellcache[spellid] if cds and CheckAlliance(alliance) and not CheckUnitIsOut(unit) and class == player.class then barid = barid + 1 local Icon if R.db.UIType == 'bar' then Icon = R:CreateIconBar(anchor, barid, DB); else Icon = R:CreateIconModule(anchor, barid, DB); end Icon.left:SetText(E:ShortenString(player.name, R.db.UIType == 'bar' and 4 or 2)) Icon.left:SetTextColor(color.r, color.g, color.b) Icon:SetNormalTexture(icon) Icon:GetNormalTexture():SetTexCoord(0.1, 0.9, 0.1, 0.9) Icon.cds = cds Icon.oldicon = icon Icon.curtex = icon Icon.spellname = title Icon.spellid = spellid Icon.guid = playerGuid Icon.playername = player.name Icon.realm = player.realm Icon.StartChannel = DB.sendStartMsg Icon.EndChannel = DB.sendEndMsg Icon:SetScript("OnUpdate", iconOnUpdate) Icon.bar:SetMinMaxValues(0, cds) Icon.bar:SetValue(0) Icon.bar:SetStatusBarColor(color.r, color.g, color.b) Icon.bar.bg:SetVertexColor(color.r, color.g, color.b, 0.25) Icon:Show() tinsert(anchor.Bars, Icon) end end end end anchor.title:SetText(L['EUIRaidToolBox'..anchor.ID]..': '..#anchor.Bars..'/'..#anchor.Bars) PostionBar(anchor, DB) end function R:CreateIconBar(parent, id, DB) if _G["EUIRLBox"..parent:GetName().."Icon"..id] then local icon = _G["EUIRLBox"..parent:GetName().."Icon"..id] icon:Size(DB.IconSize) icon.durationtext:FontTemplate(nil, DB.IconSize -6 , 'OUTLINE') icon.bar:Size(DB.BarWidth, DB.BarHeight) icon.right:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.left:FontTemplate(nil, DB.FontSize, 'OUTLINE') if icon.add then icon.add:Size(floor(DB.IconSize/2)) end if icon.sut then icon.sut:Size(floor(DB.IconSize/2)) end icon.partytext:FontTemplate(nil, DB.FontSize-2, 'OUTLINE') return _G["EUIRLBox"..parent:GetName().."Icon"..id]; end local icon = CreateFrame("Button", "EUIRLBox"..parent:GetName().."Icon"..id, parent) icon:Size(DB.IconSize) icon.id = id icon.spellname = ' ' icon.backdrop = CreateFrame("Frame", nil, icon) icon.backdrop:Point("TOPLEFT", -2, 2) icon.backdrop:Point("BOTTOMRIGHT", 2, -2) icon.backdrop:SetTemplate() icon.backdrop:SetFrameStrata("BACKGROUND") icon.partyno = 1 icon.durationtext = icon:CreateFontString(nil, 'OVERLAY') icon.durationtext:FontTemplate(nil, DB.IconSize -6 , 'OUTLINE') icon.durationtext:SetText('') icon.durationtext:SetPoint('CENTER') icon.durationtext:SetJustifyH('CENTER') icon.durationtext:SetTextColor(1, 0.5, 0) icon.bar = CreateFrame("Statusbar", nil, icon) icon.bar:SetFrameStrata("LOW") icon.bar:Size(DB.BarWidth, DB.BarHeight) icon.bar:SetStatusBarTexture(E["media"].normTex) icon.bar:SetPoint("BOTTOMLEFT", icon, "BOTTOMRIGHT", 6, 0) icon.bar:SetOrientation("HORIZONTAL") icon.bar.backdrop = CreateFrame("Frame", nil, icon.bar) icon.bar.backdrop:Point("TOPLEFT", -2, 2) icon.bar.backdrop:Point("BOTTOMRIGHT", 2, -2) icon.bar.backdrop:SetTemplate() icon.bar.backdrop:SetFrameStrata("BACKGROUND") icon.bar.bg = icon.bar:CreateTexture(nil, "BACKGROUND") icon.bar.bg:SetAllPoints(icon.bar) icon.bar.bg:SetTexture(E["media"].glossTex) if R.db.party then icon.add = CreateFrame("Button", nil, icon) icon.add:Size(floor(DB.IconSize/2)) icon.add:Point('BOTTOMRIGHT', icon.bar, 'TOPRIGHT', -floor(DB.IconSize/2), 4) icon.add:SetTemplate('Transparent') icon.add:StyleButton() icon.add:SetFrameLevel(icon:GetFrameLevel() + 2) icon.add.text = icon.add:CreateFontString(nil, 'OVERLAY') icon.add.text:FontTemplate() icon.add.text:SetText('+') icon.add.text:SetPoint('CENTER') icon.add.text:SetJustifyH('CENTER') icon.add:SetScript('OnClick', function(self) local icon = self:GetParent() icon.partyno = icon.partyno +1; if icon.partyno > 10 then icon.partyno = 10 end icon.partytext:SetText(tostring(icon.partyno)..'-') icon.partytext:SetTextColor(unpack(RCOLOR[icon.partyno])) icon.backdrop:SetBackdropBorderColor(unpack(RCOLOR[icon.partyno])) end) icon.add:SetAlpha(0) icon.add:SetScript("OnEnter", function(self) E:UIFrameFadeIn(self, 0.2, self:GetAlpha(), 1) E:UIFrameFadeIn(self:GetParent().sut, 0.2, self:GetParent().sut:GetAlpha(), 1) end) icon.add:SetScript("OnLeave", function(self) E:UIFrameFadeOut(self, 0.2, self:GetAlpha(), 0) E:UIFrameFadeOut(self:GetParent().sut, 0.2, self:GetParent().sut:GetAlpha(), 0) end) icon.sut = CreateFrame("Button", nil, icon) icon.sut:Size(floor(DB.IconSize/2)) icon.sut:Point('BOTTOMRIGHT', icon.bar, 'TOPRIGHT', 2, 4) icon.sut:SetTemplate('Transparent') icon.sut:StyleButton() icon.sut:SetFrameLevel(icon:GetFrameLevel() + 2) icon.sut.text = icon.sut:CreateFontString(nil, 'OVERLAY') icon.sut.text:FontTemplate() icon.sut.text:SetText('-') icon.sut.text:SetPoint('CENTER') icon.sut.text:SetJustifyH('CENTER') icon.sut:SetScript('OnClick', function(self) local icon = self:GetParent() icon.partyno = icon.partyno -1; if icon.partyno < 1 then icon.partyno = 1 end icon.partytext:SetText(tostring(icon.partyno)..'-') icon.partytext:SetTextColor(unpack(RCOLOR[icon.partyno])) icon.backdrop:SetBackdropBorderColor(unpack(RCOLOR[icon.partyno])) end) icon.sut:SetAlpha(0) icon.sut:SetScript("OnEnter", function(self) E:UIFrameFadeIn(self, 0.2, self:GetAlpha(), 1) E:UIFrameFadeIn(self:GetParent().add, 0.2, self:GetParent().add:GetAlpha(), 1) end) icon.sut:SetScript("OnLeave", function(self) E:UIFrameFadeOut(self, 0.2, self:GetAlpha(), 0) E:UIFrameFadeOut(self:GetParent().add, 0.2, self:GetParent().add:GetAlpha(), 0) end) end icon.right = icon.bar:CreateFontString(nil, "OVERLAY") icon.right:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.right:Point("BOTTOMRIGHT", icon.bar, "TOPRIGHT", 1, 3) icon.right:SetJustifyH("RIGHT") icon.right:SetText(' ') icon.left = icon.bar:CreateFontString(nil, "OVERLAY") icon.left:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.left:Point("BOTTOMLEFT", icon.bar, "TOPLEFT", 8, 3) icon.left:SetJustifyH("CENTER") icon.left:SetText(' ') icon.partytext = icon.bar:CreateFontString(nil, "OVERLAY") icon.partytext:FontTemplate(nil, DB.FontSize-2, 'OUTLINE') icon.partytext:SetPoint("BOTTOMLEFT", icon.bar, "TOPLEFT", -2, 3) icon.partytext:SetJustifyH('LEFT') icon.partytext:SetText('1-') icon.partytext:SetTextColor(unpack(RCOLOR[1])) icon.backdrop:SetBackdropBorderColor(unpack(RCOLOR[1])) icon:SetScript("OnEnter", OnEnter) icon:SetScript("OnLeave", OnLeave) icon:SetScript("OnMouseDown", OnMouseDown) return icon end function R:CreateIconModule(parent, id, DB) if _G["EUIRLBox"..parent:GetName().."IconModule"..id] then local icon = _G["EUIRLBox"..parent:GetName().."IconModule"..id] icon:Size(DB.IconSize) icon.durationtext:FontTemplate(nil, DB.IconSize -6 , 'OUTLINE') icon.bar:Size(6, DB.IconSize) if icon.add then icon.add:Size(floor(DB.IconSize/2)) end if icon.sut then icon.sut:Size(floor(DB.IconSize/2)) end icon.right:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.left:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.partytext:FontTemplate(nil, DB.FontSize, 'OUTLINE') return _G["EUIRLBox"..parent:GetName().."IconModule"..id]; end local icon = CreateFrame("Button", "EUIRLBox"..parent:GetName().."IconModule"..id, parent) icon:Size(DB.IconSize) icon.id = id icon.spellname = ' ' icon.CreateOverlay = createOverlay icon.backdrop = CreateFrame("Frame", nil, icon) icon.backdrop:Point("TOPLEFT", -2, 2) icon.backdrop:Point("BOTTOMRIGHT", 2, -2) icon.backdrop:SetTemplate() icon.backdrop:SetFrameStrata("BACKGROUND") icon.partyno = 1 icon.durationtext = icon:CreateFontString(nil, 'OVERLAY') icon.durationtext:FontTemplate(nil, DB.IconSize -6 , 'OUTLINE') icon.durationtext:SetText('') icon.durationtext:SetPoint('CENTER') icon.durationtext:SetJustifyH('CENTER') icon.durationtext:SetTextColor(1, 0.5, 0) icon.bar = CreateFrame("Statusbar", nil, icon) --图标模式下不显示计时条 icon.bar:SetFrameStrata("LOW") icon.bar:Size(6, DB.IconSize) icon.bar:SetStatusBarTexture(E["media"].normTex) -- icon.bar:SetPoint("LEFT", icon, "RIGHT", 2, 0) icon.bar:SetOrientation("VERTICAL")--HORIZONTAL icon.bar.backdrop = CreateFrame("Frame", nil, icon.bar) icon.bar.backdrop:Point("TOPLEFT", -2, 2) icon.bar.backdrop:Point("BOTTOMRIGHT", 2, -2) icon.bar.backdrop:SetTemplate() icon.bar.backdrop:SetFrameStrata("BACKGROUND") icon.bar.bg = icon.bar:CreateTexture(nil, "BACKGROUND") icon.bar.bg:SetAllPoints(icon.bar) icon.bar.bg:SetTexture(E["media"].glossTex) if R.db.party then icon.add = CreateFrame("Button", nil, icon) icon.add:Size(floor(DB.IconSize/2)) icon.add:Point('TOPLEFT', icon, 'TOPLEFT', 1, -1) icon.add:SetTemplate('Transparent') icon.add:StyleButton() icon.add:SetFrameLevel(icon:GetFrameLevel() + 2) icon.add.text = icon.add:CreateFontString(nil, 'OVERLAY') icon.add.text:FontTemplate() icon.add.text:SetText('+') icon.add.text:SetPoint('CENTER') icon.add.text:SetJustifyH('CENTER') icon.add:SetScript('OnClick', function(self) local icon = self:GetParent() icon.partyno = icon.partyno +1; if icon.partyno > 10 then icon.partyno = 10 end icon.partytext:SetText(tostring(icon.partyno)..'-') icon.partytext:SetTextColor(unpack(RCOLOR[icon.partyno])) icon.backdrop:SetBackdropBorderColor(unpack(RCOLOR[icon.partyno])) end) icon.add:SetAlpha(0) icon.add:SetScript("OnEnter", function(self) E:UIFrameFadeIn(self, 0.2, self:GetAlpha(), 1) E:UIFrameFadeIn(self:GetParent().sut, 0.2, self:GetParent().sut:GetAlpha(), 1) end) icon.add:SetScript("OnLeave", function(self) E:UIFrameFadeOut(self, 0.2, self:GetAlpha(), 0) E:UIFrameFadeOut(self:GetParent().sut, 0.2, self:GetParent().sut:GetAlpha(), 0) end) icon.sut = CreateFrame("Button", nil, icon) icon.sut:Size(floor(DB.IconSize/2)) icon.sut:Point('BOTTOMLEFT', icon, 'BOTTOMLEFT', 1, 1) icon.sut:SetTemplate('Transparent') icon.sut:StyleButton() icon.sut:SetFrameLevel(icon:GetFrameLevel() + 2) icon.sut.text = icon.sut:CreateFontString(nil, 'OVERLAY') icon.sut.text:FontTemplate() icon.sut.text:SetText('-') icon.sut.text:SetPoint('CENTER') icon.sut.text:SetJustifyH('CENTER') icon.sut:SetScript('OnClick', function(self) local icon = self:GetParent() icon.partyno = icon.partyno -1; if icon.partyno < 1 then icon.partyno = 1 end icon.partytext:SetText(tostring(icon.partyno)..'-') icon.partytext:SetTextColor(unpack(RCOLOR[icon.partyno])) icon.backdrop:SetBackdropBorderColor(unpack(RCOLOR[icon.partyno])) end) icon.sut:SetAlpha(0) icon.sut:SetScript("OnEnter", function(self) E:UIFrameFadeIn(self, 0.2, self:GetAlpha(), 1) E:UIFrameFadeIn(self:GetParent().add, 0.2, self:GetParent().add:GetAlpha(), 1) end) icon.sut:SetScript("OnLeave", function(self) E:UIFrameFadeOut(self, 0.2, self:GetAlpha(), 0) E:UIFrameFadeOut(self:GetParent().add, 0.2, self:GetParent().add:GetAlpha(), 0) end) end icon.right = icon:CreateFontString(nil, "OVERLAY") icon.right:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.right:Point("CENTER", icon, "CENTER", 0, 0) icon.right:SetJustifyH("CENTER") icon.right:SetText(' ') icon.right:SetTextColor(1, 0.1, 0) icon.left = icon:CreateFontString(nil, "OVERLAY") icon.left:FontTemplate(nil, DB.FontSize, 'OUTLINE') icon.left:Point("TOP", icon, "BOTTOM", 0, -3) icon.left:SetJustifyH("CENTER") icon.left:SetText(' ') icon.partytext = icon:CreateFontString(nil, "OVERLAY") icon.partytext:FontTemplate(nil, DB.FontSize, 'OUTLINE') if R.db.party then icon.partytext:SetPoint("BOTTOMLEFT", icon, "BOTTOMLEFT", 0, 0) end icon.partytext:SetJustifyH('LEFT') icon.partytext:SetText('1-') icon.partytext:SetTextColor(unpack(RCOLOR[1])) icon.backdrop:SetBackdropBorderColor(unpack(RCOLOR[1])) icon:SetScript("OnEnter", OnEnter) icon:SetScript("OnLeave", OnLeave) icon:SetScript("OnMouseDown", OnMouseDown) return icon end local function barOnUpdate(self) local time = GetTime(); local icon = self:GetParent() if (time > self.endTime) then self.endTime = 0 icon.right:SetText('') self:SetValue(0) self:SetScript("OnUpdate", nil) icon:GetNormalTexture():SetDesaturated(false); if not icon.sendready then if icon.EndChannel and icon.EndChannel ~= 'NONE' then if icon.EndChannel == 'RAID' and IsPartyLFG() then icon.EndChannel = 'INSTANCE_CHAT' end SendChatMessage(format(readyMsg, icon.partytext:GetText()..icon.playername, icon.spellid, icon.spellname), icon.EndChannel) end icon.sendready = true icon.sendcast = false end WPCache['p'..icon.partyno] = false -- E:StopFlash(icon) E:Flash(icon, 1) else local remaining = self.endTime - time if R.db.UIType == 'icon' then if (not icon.duration) or (icon.duration and icon.duration < 0) then --无持续时间显示时才显示CD计时 icon.right:SetText(FormatTime(self.endTime - time)) end else icon.right:SetText(FormatTime(self.endTime - time)) end self:SetValue(math.floor(remaining)) icon:GetNormalTexture():SetDesaturated(true); end end function R:COMBAT_LOG_EVENT_UNFILTERED(...) local _, event, _, sourceGUID, sourceName, _, _, _, _, _, _, spellID = CombatLogGetCurrentEventInfo() if event ~= "SPELL_RESURRECT" and event ~= "SPELL_CAST_SUCCESS" and event ~= "SPELL_AURA_APPLIED" then return end if not sourceName or not spellID or not sourceGUID then return end spellID = ConvertSpellIdIfSoulstone(spellID) if spellID == 61391 then spellID = 132469 end --转换台风技能 if not GetSpellInfo(spellID) then return; end for k=1, 3 do local f = _G["EUIRaidToolBox"..k] if f and f.Bars and #f.Bars > 0 then for i=1, #f.Bars do if f.Bars[i].spellid == spellID and f.Bars[i].guid == sourceGUID then local icon = f.Bars[i] if icon.cds and icon.cds > 0 then icon.duration = GetSpellDuration(spellID) if not icon.sendcast then local channel = icon.StartChannel if channel and channel ~= 'NONE' then if channel == 'RAID' and IsPartyLFG() then channel = 'INSTANCE_CHAT' end SendChatMessage(format(castMsg, icon.partytext:GetText()..icon.playername, spellID, icon.spellname, icon.duration or NONE), channel) end icon.sendcast = true; icon.sendready = false end if icon.duration and icon.duration > 0 then icon.startTime = GetTime() icon.endTime = GetTime() + icon.duration -- icon:SetScript('OnUpdate', iconDurationOnUpdate) end icon.bar.startTime = GetTime(); icon.bar.endTime = GetTime() + icon.cds; icon.bar:SetMinMaxValues(0, icon.cds); icon.bar:SetScript('OnUpdate', barOnUpdate) end break; end end end end end local function resetbars(f) if f and f.Bars and #f.Bars > 0 then for i=1, #f.Bars do f.Bars[i]:Hide() f.Bars[i] = nil end f.Bars = nil f.Bars = {} f.title:SetText(L['EUIRaidToolBox'..f.ID]) end end function R:ResetBars(f, all) if not f or all then for i = 1, 3 do resetbars(_G['EUIRaidToolBox'..i]) end else resetbars(f) end if all and R.Players then for k, v in pairs(R.Players) do if v.spellcache then wipe(v.spellcache) end end wipe(R.Players) R.Players = nil R.Players = {} end collectgarbage("collect"); end local function createAnchor(i) local frame = CreateFrame("Button", "EUIRaidToolBox"..i, E.UIParent) frame:StyleButton() frame:SetTemplate("Transparent") frame:RegisterForClicks('AnyUp', 'AnyDown') frame:SetScript("OnClick", function(self, btn) if btn == 'RightButton' then R:ResetBars(self, IsShiftKeyDown()); else R:UpdateBoxUI(self, true); end end) frame:SetSize(18, 18) frame:SetNormalTexture("Interface\\AddOns\\ElvUI\\media\\textures\\reload.tga") frame:SetPushedTexture("Interface\\AddOns\\ElvUI\\media\\textures\\reload.tga") frame:SetScript("OnEnter", function(self) GameTooltip:SetOwner(self, "ANCHOR_RIGHT") GameTooltip:AddDoubleLine(L["Left button:"], REFRESH, .6, .6, .6, 1, 1, 1) GameTooltip:AddDoubleLine(L["Right button:"], RESET, .6, .6, .6, 1, 1, 1) GameTooltip:AddDoubleLine(L["shiftztype2"], RESET..ALL, .6, .6, .6, 1, 1, 1) GameTooltip:SetClampedToScreen(true) GameTooltip:Show() end) frame:SetScript("OnLeave", function() GameTooltip:Hide() end) frame:SetClampedToScreen(true) if i == 1 then frame:Point("TOPLEFT", 4, -28) elseif i == 2 then frame:Point("TOPLEFT", 328, -28) else frame:Point("TOPLEFT", 488, -28) end frame.ID = i frame.Bars = {} E:CreateMover(frame, "EUIRaidToolBox"..i.."Mover", L['EUIRaidToolBox'..i], nil, nil, nil, "ALL,EUI", nil, "euiscript,RLBox", "db,RLBox,enable") frame.title = frame:CreateFontString(nil, 'OVERLAY') frame.title:FontTemplate(nil, R.db.TitleFontSize, 'OUTLINE') frame.title:Point("LEFT", frame, "RIGHT", 2, 0) frame.title:SetJustifyH("LEFT") frame.title:SetText(L['EUIRaidToolBox'..i]) frame.title:SetTextColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b) end function R:CreateAnchor(toggle) if not toggle then for i=1, 3 do local f = _G["EUIRaidToolBox"..i] if f then f:Hide(); R:ResetBars(f) end end return; end for i=1, 3 do if i == 1 and self.db.DEFAULT.enable then createAnchor(i); end if i == 2 and self.db.OTHER.enable then createAnchor(i); end if i == 3 and self.db.MISC.enable then createAnchor(i); end end end function R:CalcBarsNum() if R.Players then for i = 1, 3 do local num = 0 local anchor = _G['EUIRaidToolBox'..i] if anchor then local tmptable if anchor.ID == 1 then tmptable = E.global.RLBox.DEFAULT_SPELLS end if anchor.ID == 2 then tmptable = E.global.RLBox.OTHER_SPELLS end if anchor.ID == 3 then tmptable = E.global.RLBox.MISC_SPELLS end for i, default in pairs(tmptable) do local class = default[1] local spellid = default[2] for playerGuid, player in pairs(R.Players) do local cds = player.spellcache[spellid] if cds then num = num + 1 end end end if num ~= #anchor.Bars then if not InCombatLockdown() then R:UpdateBoxUI(anchor) else num = E.ValColor..num..'|r' R:RegisterEvent('PLAYER_REGEN_ENABLED') end end anchor.title:SetText(L['EUIRaidToolBox'..i]..': '..num..'/'..#anchor.Bars) end end end end function R:PLAYER_REGEN_ENABLED() if InCombatLockdown() then return; end for i = 1, 3 do local num = 0 local anchor = _G['EUIRaidToolBox'..i] if anchor then R:UpdateBoxUI(anchor) end end R:UnregisterEvent('PLAYER_REGEN_ENABLED') end function R:GROUP_ROSTER_UPDATE() if not R.Players then return; end if not IsInRaid() then R:ResetBars(); return end local inInstance, instanceType = IsInInstance() local _, _, _, _, maxPlayers, _, _ = GetInstanceInfo() local raidNum = GetNumGroupMembers() if inInstance and instanceType == "raid" then raidNum = maxPlayers end for i = 1, raidNum do local unit = "raid"..i local guid = UnitGUID(unit) local info = LibGroupInspect:GetCachedInfo(guid) if info and info.name and info.class_id then local player = BuildPlayerList(guid, info, unit) R:BuildPlayerSpellCache(player, guid) end end for guid, player in pairs(R.Players) do local unit = GetUnitFromName(player.name, guid) if CheckUnitIsOut(unit) then if player.spellcache then wipe(player.spellcache) player.spellcache = nil end R.Players[guid] = nil; end end R:CalcBarsNum() end function R:ZONE_CHANGED() if not IsInInstance() then R:ResetBars(); end end function R:Toggle() if E.db.RLBox.enable then wipe(R.Players) self:CreateAnchor(true) LibGroupInspect.RegisterCallback(R, "GroupInSpecT_Update"); LibGroupInspect.RegisterCallback(R, "GroupInSpecT_Remove"); self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterEvent("GROUP_ROSTER_UPDATE") self:RegisterEvent("ZONE_CHANGED") else self:CreateAnchor(false) LibGroupInspect.UnregisterCallback(R, "GroupInSpecT_Update"); LibGroupInspect.UnregisterCallback(R, "GroupInSpecT_Remove"); self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:UnregisterEvent("GROUP_ROSTER_UPDATE") self:UnregisterEvent("ZONE_CHANGED") end end function R:Initialize() self.db = E.db.RLBox if not self.db then return; end R.Players = {} self:Toggle() end local function InitializeCallback() R:Initialize() end E:RegisterModule(R:GetName(), InitializeCallback)
a = 100 b = 110 print(a+b) print("Hello World") for i=0,10000 do print(i) end
----------------------------------- -- Area: Dynamis - Buburimu -- Mob: Apocalyptic Beast -- Note: Mega Boss ----------------------------------- require("scripts/globals/dynamis") ----------------------------------- function onMobDeath(mob, player, isKiller) dynamis.megaBossOnDeath(mob, player, isKiller) end
local Config = require('config') local GPS = require('gps') local turtle = _G.turtle local Home = { } function Home.go() local config = { } Config.load('gps', config) if config.home then if turtle.enableGPS() then return turtle.pathfind(config.home) end end end function Home.set() local config = { } Config.load('gps', config) local pt = GPS.getPoint() if pt then local originalHeading = turtle.point.heading local heading = GPS.getHeading() if heading then local turns = (turtle.point.heading - originalHeading) % 4 pt.heading = (heading - turns) % 4 config.home = pt Config.update('gps', config) pt = GPS.getPoint() pt.heading = heading turtle.setPoint(pt, true) turtle._goto(config.home) return config.home end end end return Home
local System = System local SystemNumerics = System.Numerics local tan = math.tan local cos = math.cos local sin = math.sin local abs = math.abs local new = function (cls, ...) local this = setmetatable({}, cls) return this, cls.__ctor__(this, ...) end local Matrix3x2 = {} Matrix3x2.__ctor__ = function(this, m11, m12, m21, m22, m31, m32) this.M11 = m11 or 0 this.M12 = m12 or 0 this.M21 = m21 or 0 this.M22 = m22 or 0 this.M31 = m31 or 0 this.M32 = m32 or 0 local mt = getmetatable(this) mt.__unm = Matrix3x2.op_UnaryNegation setmetatable(this, mt) end Matrix3x2.getIdentity = function () return new(Matrix3x2, 1, 0, 0, 1, 0, 0) end Matrix3x2.getIsIdentity = function (this) return this.M11 == 1 and this.M22 == 1 and this.M12 == 0 and this.M21 == 0 and this.M31 == 0 and this.M32 == 0 end Matrix3x2.getTranslation = function (this) return SystemNumerics.Vector2(this.M31, this.M32) end Matrix3x2.setTranslation = function (this, value) this.M31 = value.X this.M32 = value.Y end Matrix3x2.CreateTranslation = function (position, yPosition) if yPosition == nil then -- Vector2 local result = new(Matrix3x2) result.M11 = 1.0 result.M12 = 0.0 result.M21 = 0.0 result.M22 = 1.0 result.M31 = position.X result.M32 = position.Y return result:__clone__() else -- singles local result = new(Matrix3x2) result.M11 = 1.0 result.M12 = 0.0 result.M21 = 0.0 result.M22 = 1.0 result.M31 = position result.M32 = yPosition return result:__clone__() end end Matrix3x2.CreateScale = function(val1, val2, val3) if val3 == nil then if val2 == nil then if val1.X == nil then -- CreateScale(Single) local result = new(Matrix3x2) result.M11 = val1 result.M12 = 0.0 result.M21 = 0.0 result.M22 = val1 result.M31 = 0.0 result.M32 = 0.0 return result:__clone__() else -- CreateScale(Vector2) local result = new(Matrix3x2) result.M11 = val1.X result.M12 = 0.0 result.M21 = 0.0 result.M22 = val1.Y result.M31 = 0.0 result.M32 = 0.0 return result:__clone__() end else if val2.X == nil then -- CreateScale(Single, Single) local result = new(Matrix3x2) result.M11 = val1 result.M12 = 0.0 result.M21 = 0.0 result.M22 = val2 result.M31 = 0.0 result.M32 = 0.0 return result:__clone__() else if val1.X == nil then -- CreateScale(Single, Vector2) local result = new(Matrix3x2) local tx = val2.X * (1 - val1) local ty = val2.Y * (1 - val1) result.M11 = val1 result.M12 = 0.0 result.M21 = 0.0 result.M22 = val1 result.M31 = tx result.M32 = ty return result:__clone__() else -- CreateScale(Vector2, Vector2) local result = new(Matrix3x2) local tx = val2.X * (1 - val1.X) local ty = val2.Y * (1 - val1.Y) result.M11 = val1.X result.M12 = 0.0 result.M21 = 0.0 result.M22 = val1.Y result.M31 = tx result.M32 = ty return result:__clone__() end end end else -- CreateScale(Single, Single, Vector2) local result = new(Matrix3x2) local tx = val3.X * (1 - val1) local ty = val3.Y * (1 - val2) result.M11 = val1 result.M12 = 0.0 result.M21 = 0.0 result.M22 = val2 result.M31 = tx result.M32 = ty return result:__clone__() end end Matrix3x2.CreateSkew = function (radiansX, radiansY, centerPoint) if centerPoint == nil then local result = new(Matrix3x2) local xTan = System.ToSingle(tan(radiansX)) local yTan = System.ToSingle(tan(radiansY)) result.M11 = 1.0 result.M12 = yTan result.M21 = xTan result.M22 = 1.0 result.M31 = 0.0 result.M32 = 0.0 return result:__clone__() else local result = new(Matrix3x2) local xTan = System.ToSingle(tan(radiansX)) local yTan = System.ToSingle(tan(radiansY)) local tx = - centerPoint.Y * xTan local ty = - centerPoint.X * yTan result.M11 = 1.0 result.M12 = yTan result.M21 = xTan result.M22 = 1.0 result.M31 = tx result.M32 = ty return result:__clone__() end end Matrix3x2.CreateRotation = function (radians, centerPoint) if centerPoint == nil then local result = new(Matrix3x2) radians = System.ToSingle(math.IEEERemainder(radians, 6.28318530717959 --[[Math.PI * 2]])) local c, s -- 0.1% of a degree if radians > - 1.745329E-05 --[[epsilon]] and radians < 1.745329E-05 --[[epsilon]] then -- Exact case for zero rotation. c = 1 s = 0 elseif radians > 1.57077887350062 --[[Math.PI / 2 - epsilon]] and radians < 1.57081378008917 --[[Math.PI / 2 + epsilon]] then -- Exact case for 90 degree rotation. c = 0 s = 1 elseif radians < -3.14157520029552 --[[-Math.PI + epsilon]] or radians > 3.14157520029552 --[[Math.PI - epsilon]] then -- Exact case for 180 degree rotation. c = - 1 s = 0 elseif radians > -1.57081378008917 --[[-Math.PI / 2 - epsilon]] and radians < -1.57077887350062 --[[-Math.PI / 2 + epsilon]] then -- Exact case for 270 degree rotation. c = 0 s = - 1 else -- Arbitrary rotation. c = System.ToSingle(cos(radians)) s = System.ToSingle(sin(radians)) end -- [ c s ] -- [ -s c ] -- [ 0 0 ] result.M11 = c result.M12 = s result.M21 = - s result.M22 = c result.M31 = 0.0 result.M32 = 0.0 return result:__clone__() else local result = new(Matrix3x2) radians = System.ToSingle(math.IEEERemainder(radians, 6.28318530717959 --[[Math.PI * 2]])) local c, s -- 0.1% of a degree if radians > - 1.745329E-05 --[[epsilon]] and radians < 1.745329E-05 --[[epsilon]] then -- Exact case for zero rotation. c = 1 s = 0 elseif radians > 1.57077887350062 --[[Math.PI / 2 - epsilon]] and radians < 1.57081378008917 --[[Math.PI / 2 + epsilon]] then -- Exact case for 90 degree rotation. c = 0 s = 1 elseif radians < -3.14157520029552 --[[-Math.PI + epsilon]] or radians > 3.14157520029552 --[[Math.PI - epsilon]] then -- Exact case for 180 degree rotation. c = - 1 s = 0 elseif radians > -1.57081378008917 --[[-Math.PI / 2 - epsilon]] and radians < -1.57077887350062 --[[-Math.PI / 2 + epsilon]] then -- Exact case for 270 degree rotation. c = 0 s = - 1 else -- Arbitrary rotation. c = System.ToSingle(cos(radians)) s = System.ToSingle(sin(radians)) end local x = centerPoint.X * (1 - c) + centerPoint.Y * s local y = centerPoint.Y * (1 - c) - centerPoint.X * s -- [ c s ] -- [ -s c ] -- [ x y ] result.M11 = c result.M12 = s result.M21 = - s result.M22 = c result.M31 = x result.M32 = y return result:__clone__() end end Matrix3x2.GetDeterminant = function (this) -- There isn't actually any such thing as a determinant for a non-square matrix, -- but this 3x2 type is really just an optimization of a 3x3 where we happen to -- know the rightmost column is always (0, 0, 1). So we expand to 3x3 format: -- -- [ M11, M12, 0 ] -- [ M21, M22, 0 ] -- [ M31, M32, 1 ] -- -- Sum the diagonal products: -- (M11 * M22 * 1) + (M12 * 0 * M31) + (0 * M21 * M32) -- -- Subtract the opposite diagonal products: -- (M31 * M22 * 0) + (M32 * 0 * M11) + (1 * M21 * M12) -- -- Collapse out the constants and oh look, this is just a 2x2 determinant! return (this.M11 * this.M22) - (this.M21 * this.M12) end Matrix3x2.Invert = function (matrix, result) local det = (matrix.M11 * matrix.M22) - (matrix.M21 * matrix.M12) if result == nil then result = new(Matrix3x2) end if abs(det) < 1.401298E-45 --[[Single.Epsilon]] then result = new(Matrix3x2, System.Single.NaN, System.Single.NaN, System.Single.NaN, System.Single.NaN, System.Single.NaN, System.Single.NaN) return false, result end local invDet = 1.0 / det result.M11 = matrix.M22 * invDet result.M12 = - matrix.M12 * invDet result.M21 = - matrix.M21 * invDet result.M22 = matrix.M11 * invDet result.M31 = (matrix.M21 * matrix.M32 - matrix.M31 * matrix.M22) * invDet result.M32 = (matrix.M31 * matrix.M12 - matrix.M11 * matrix.M32) * invDet return true, result end Matrix3x2.Lerp = function (matrix1, matrix2, amount) local result = new(Matrix3x2) -- First row result.M11 = matrix1.M11 + (matrix2.M11 - matrix1.M11) * amount result.M12 = matrix1.M12 + (matrix2.M12 - matrix1.M12) * amount -- Second row result.M21 = matrix1.M21 + (matrix2.M21 - matrix1.M21) * amount result.M22 = matrix1.M22 + (matrix2.M22 - matrix1.M22) * amount -- Third row result.M31 = matrix1.M31 + (matrix2.M31 - matrix1.M31) * amount result.M32 = matrix1.M32 + (matrix2.M32 - matrix1.M32) * amount return result:__clone__() end Matrix3x2.Negate = function (value) local result = new(Matrix3x2) result.M11 = - value.M11 result.M12 = - value.M12 result.M21 = - value.M21 result.M22 = - value.M22 result.M31 = - value.M31 result.M32 = - value.M32 return result:__clone__() end Matrix3x2.Add = function (value1, value2) local result = new(Matrix3x2) result.M11 = value1.M11 + value2.M11 result.M12 = value1.M12 + value2.M12 result.M21 = value1.M21 + value2.M21 result.M22 = value1.M22 + value2.M22 result.M31 = value1.M31 + value2.M31 result.M32 = value1.M32 + value2.M32 return result:__clone__() end Matrix3x2.Subtract = function (value1, value2) local result = new(Matrix3x2) result.M11 = value1.M11 - value2.M11 result.M12 = value1.M12 - value2.M12 result.M21 = value1.M21 - value2.M21 result.M22 = value1.M22 - value2.M22 result.M31 = value1.M31 - value2.M31 result.M32 = value1.M32 - value2.M32 return result:__clone__() end Matrix3x2.Multiply = function (value1, value2) if value2.M11 == nil then -- scalar local result = new(Matrix3x2) result.M11 = value1.M11 * value2 result.M12 = value1.M12 * value2 result.M21 = value1.M21 * value2 result.M22 = value1.M22 * value2 result.M31 = value1.M31 * value2 result.M32 = value1.M32 * value2 return result:__clone__() else -- matrix local result = new(Matrix3x2) -- First row result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 -- Second row result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 -- Third row result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31 result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32 return result:__clone__() end end Matrix3x2.op_UnaryNegation = function (value) local m = new(Matrix3x2) m.M11 = - value.M11 m.M12 = - value.M12 m.M21 = - value.M21 m.M22 = - value.M22 m.M31 = - value.M31 m.M32 = - value.M32 return m:__clone__() end Matrix3x2.op_Addition = function (value1, value2) local m = new(Matrix3x2) m.M11 = value1.M11 + value2.M11 m.M12 = value1.M12 + value2.M12 m.M21 = value1.M21 + value2.M21 m.M22 = value1.M22 + value2.M22 m.M31 = value1.M31 + value2.M31 m.M32 = value1.M32 + value2.M32 return m:__clone__() end Matrix3x2.op_Subtraction = function (value1, value2) local m = new(Matrix3x2) m.M11 = value1.M11 - value2.M11 m.M12 = value1.M12 - value2.M12 m.M21 = value1.M21 - value2.M21 m.M22 = value1.M22 - value2.M22 m.M31 = value1.M31 - value2.M31 m.M32 = value1.M32 - value2.M32 return m:__clone__() end Matrix3x2.op_Multiply = function (value1, value2) if value2.M11 == nil then -- scalar local result = new(Matrix3x2) result.M11 = value1.M11 * value2 result.M12 = value1.M12 * value2 result.M21 = value1.M21 * value2 result.M22 = value1.M22 * value2 result.M31 = value1.M31 * value2 result.M32 = value1.M32 * value2 return result:__clone__() else -- matrix local result = new(Matrix3x2) -- First row result.M11 = value1.M11 * value2.M11 + value1.M12 * value2.M21 result.M12 = value1.M11 * value2.M12 + value1.M12 * value2.M22 -- Second row result.M21 = value1.M21 * value2.M11 + value1.M22 * value2.M21 result.M22 = value1.M21 * value2.M12 + value1.M22 * value2.M22 -- Third row result.M31 = value1.M31 * value2.M11 + value1.M32 * value2.M21 + value2.M31 result.M32 = value1.M31 * value2.M12 + value1.M32 * value2.M22 + value2.M32 return result:__clone__() end end Matrix3x2.op_Equality = function (value1, value2) return (value1.M11 == value2.M11 and value1.M22 == value2.M22 and value1.M12 == value2.M12 and value1.M21 == value2.M21 and value1.M31 == value2.M31 and value1.M32 == value2.M32) end Matrix3x2.op_Inequality = function (value1, value2) return (value1.M11 ~= value2.M11 or value1.M12 ~= value2.M12 or value1.M21 ~= value2.M21 or value1.M22 ~= value2.M22 or value1.M31 ~= value2.M31 or value1.M32 ~= value2.M32) end Matrix3x2.Equals = function (this, other) if System.is(other, Matrix3x2) then return (this.M11 == other.M11 and this.M22 == other.M22 and this.M12 == other.M12 and this.M21 == other.M21 and this.M31 == other.M31 and this.M32 == other.M32) end return false end Matrix3x2.ToString = function (this) local sb = System.StringBuilder() sb:Append("{ ") sb:Append("{") sb:Append("M11: ") sb:Append(this.M11:ToString()) sb:Append(" M12: ") sb:Append(this.M12:ToString()) sb:Append("} ") sb:Append("{") sb:Append("M21: ") sb:Append(this.M21:ToString()) sb:Append(" M22: ") sb:Append(this.M22:ToString()) sb:Append("} ") sb:Append("{") sb:Append("M31: ") sb:Append(this.M31:ToString()) sb:Append(" M32: ") sb:Append(this.M32:ToString()) sb:Append("} ") sb:Append("}") return sb:ToString() end Matrix3x2.GetHashCode = function (this) return this.M11:GetHashCode() + this.M12:GetHashCode() + this.M21:GetHashCode() + this.M22:GetHashCode() + this.M31:GetHashCode() + this.M32:GetHashCode() end System.defStc("System.Numerics.Matrix3x2", Matrix3x2)
local modpath = minetest.get_modpath("mob_ai") dofile(modpath.."/api.lua") dofile(modpath.."/drivers.lua") dofile(modpath.."/spawn.lua") dofile(modpath.."/pathfinder.lua") minetest.register_chatcommand("pathtest",{ description = "generate path at players feet", func = function(name,param) local player = minetest.get_player_by_name(name) local pos = player:get_pos() local pos2 = {x=pos.x+10,y=pos.y+0,z=pos.z+10} local path = pathfinder.find_path(pos,pos2,{collisionbox = {0,0,0,0,2,0}},0) print(dump(path)) print(dump(pos)) print(dump(pos2)) if path then for _,step in pairs(path) do minetest.set_node(step,{name = "default:cloud"}) end end end })
local _, core = ...; core.Data = {} local Data = core.Data Data.roster = {} function Data:QueryForItem(id) itemId = tonumber(id) item = Item:CreateFromItemID(itemId) item:ContinueOnItemLoad(function() print(item:GetItemLink()) --local _, itemLink = GetItemInfo(id) --print(itemLink) end) end function Data:QueryForItemInstant(id) local item = {} item.itemId, item.itemType, item.itemSubType, item.itemEquipLoc, item.icon, item.classId, item.subClassId = GetItemInfoInstant(id) return item end function Data:QueryForItemByLink(link) item = Item:CreateFromItemLink(link) item:ContinueOnItemLoad(function() print(item:GetItemLink()) print(item:GetItemName()) --local _, itemLink = GetItemInfo(id) --print(itemLink) end) end -- function Data:AddMember(memberName) -- --Name provided must be a member of current guild. -- guildInfo = {GetGuildRosterInfo(memberName)} -- for i=1, -- end function Data:PrintKeys(o) for key,value in pairs(o) do print("found member" .. key) end end ------------------------------------- --GUILD INFO ------------------------------------- function Data:RetrieveGuildInfo() if Data.GuildMembers == nil then Data.GuildMembers = {} end local numGuildMembers = GetNumGuildMembers() if numGuildMembers ~= nil then for i=1,numGuildMembers do local guildMember = Data:RetrieveGuildMember(i) Data.GuildMembers[guildMember.name] = guildMember end end end function Data:RetrieveGuildMember(i) local results = {GetGuildRosterInfo(i)} local guildMember = {} guildMember.name = Data:SplitNameFromServer(results[1]) guildMember.rank = results[2] guildMember.rankIndex = results[3] guildMember.level = results[4] guildMember.class = results[5] return guildMember end function Data:PrintGuildMemberNames() if Data.GuildMembers ~= nil then local count = 0 for k, v in pairs(Data.GuildMembers) do print(k, Data:SplitNameFromServer(v["name"]), v["rank"], v["rankIndex"], v["level"], v["class"]) count = count + 1 end if count == 0 then print("No guild members!") end end end function Data:SplitNameFromServer(name) local dashLoc = name:find("-") if dashLoc == nil then return name end return name:sub(0, dashLoc - 1) end ------------------------------- -- ROSTER MANAGEMENT ------------------------------- -- Not to be mistaken with guild, these functions are responsible for adding or removing members to/from the roster. -- At the moment just supporting one roster but will eventually support multiple. function Data:AddToRoster(name) -- Try to find name in guild members if Data.roster[name] ~= nil then print(name .. " already present in roster!") return end if Data.GuildMembers[name] ~= nil then Data.roster[name] = Data:BuildRosterMember(Data.GuildMembers[name]) print("Inserted " .. name .. " into roster!") else print("Unable to find member in guild roster") end end function Data:BuildRosterMember(guildMember) local rosterMember = {} rosterMember.name = Data:SplitNameFromServer(guildMember.name) rosterMember.rank = guildMember.rank rosterMember.rankIndex = guildMember.rankIndex rosterMember.level = guildMember.level rosterMember.class = guildMember.class rosterMember.gear = {} return rosterMember end function Data:PrintRoster() if Data.roster ~= nil then local count = 0 for k, v in pairs(Data.roster) do print(k, v["name"], v["rank"], v["rankIndex"], v["level"], v["class"]) count = count + 1 end if count == 0 then print("No roster members!") end end end function Data:RemoveFromRoster(name) -- Try to find name in guild members if Data.roster[name] ~= nil then Data.roster[name] = nil print(name .. " removed from roster!") else print("Unable to find member in roster") end end -- Assumes that arguments are rosterMember objects function Data.defaultRosterSortOrder(member1, member2) if not member1 then return false end if not member2 then return false end if member1.rankIndex ~= member2.rankIndex then return member1.rankIndex < member2.rankIndex end if member1.class ~= member2.class then return member1.class < member2.class end return member1.name < member2.name end ------------------------------------ -- GEAR MANAGEMENT ------------------------------------ function Data:AddGearToMember(rosterMember, itemId) print(rosterMember .. " " .. itemId) print(table) if Data.roster[rosterMember] == nil then print("Unable to find member in roster") return end if Data.roster[rosterMember].gear == nil then Data.roster[rosterMember].gear = {} end table.insert(Data.roster[rosterMember].gear, itemId) end function Data:ListGear(rosterMember) if Data.roster[rosterMember] == nil then print("Unable to find member in roster") return end if Data.roster[rosterMember].gear ~= nil then local count = 0 for k, v in pairs(Data.roster[rosterMember].gear) do print(v) count = count + 1 end if count == 0 then print("No gear for " .. rosterMember .. "!") end end end function Data:BuildGearDetails(rosterMember) local gearDetails = {} print(rosterMember) print(Data.roster) if Data.roster[rosterMember].gear == nil then return gearDetails end for key, value in ipairs(Data.roster[rosterMember].gear) do local item = Data:QueryForItemInstant(value) if item ~= nil then table.insert(gearDetails, Data:QueryForItemInstant(value)) end end return gearDetails end -- Assumes that arguments are item objects function Data.defaultGearSortOrder(item1, item2) if item1.itemType ~= item2.itemType then return item1.itemType < item2.itemType end if item1.itemEquipLoc ~= item2.itemEquipLoc then return item1.itemEquipLoc < item2.itemEquipLoc end return item1.itemId < item2.itemId end
local handler = call ( getResourceFromName ( "rp_mysql" ), "getDbHandler") function getUserCharacters(thePlayer, userId) local query = dbQuery(handler, "SELECT * FROM lsrp_characters WHERE char_gid = '"..tonumber(userId).."'") local result = dbPoll(query, -1) if result and result[1] then charsarray = {} local index = 0 local char_num = table.getn(result) for i = 1, char_num do charsarray[index] = {} charsarray[index]["char_uid"] = result[i]["char_uid"] charsarray[index]["char_name"] = result[i]["char_name"] index = index + 1 end --outputChatBox("showPlayerCharactersList, num of chars: "..char_num) triggerClientEvent (thePlayer, "showPlayerCharactersList", thePlayer, charsarray) else showPopup(thePlayer, "Nie masz postaci!", 3) return end end --[[ LOGOWANIE NA KONTO GLOBALNE ]]-- function cef_submitServerLogin(thePlayer, login, password) if not login or not password then showPopup(source, "Uzupełnij wszystkie pola!", 3) return end if string.len(password) > 1 then local query = dbQuery(handler, "SELECT * FROM lsrp_members WHERE user_login = '".. login .."' AND user_passhash = MD5(CONCAT(MD5(user_salt), MD5('"..password.."')))") local result = dbPoll ( query, -1 ) if result and result[1] then local member_id = tonumber(result[1]["user_id"]) -- Active if tonumber(result[1]["user_active"]) <= 0 then kickPlayer(thePlayer, "Twoje konto nie jest aktywne.") return end -- Beta if tonumber(result[1]["user_beta_access"]) <= 0 then kickPlayer(thePlayer, "Nie masz dostępu do beta.") return end -- POBIERANIE USER_XXXXX setElementData(thePlayer, "player.admin", result[1]["user_admin"]) setElementData(thePlayer, "player.gname", result[1]["user_login"]) setElementData(thePlayer, "player.color", result[1]["user_color"]) setElementData(thePlayer, "player.showtags", tonumber(result[1]["user_showtags"])) setElementData(thePlayer, "player.shaders", tonumber(result[1]["user_shaders"])) setElementData(thePlayer, "player.gamescore", tonumber(result[1]["user_gamepoints"])) getUserCharacters(thePlayer, member_id) else showPopup(thePlayer, "Wprowadzono błędny login lub hasło!", 3) return end if query then dbFree(query) end else showPopup(thePlayer, "Podane hasło ma nieprawidłową długość!", 3) return end end addEvent("cefCheckLogin",true) addEventHandler("cefCheckLogin", root, cef_submitServerLogin) --[[ WYBÓR POSTACI ]]-- function onPlayerSelectCharacterByUid(thePlayer, char_uid) if thePlayer then -- nowe mysql local query = dbQuery(handler, "SELECT * FROM lsrp_characters WHERE char_uid = "..tonumber(char_uid)) local result = dbPoll ( query, -1 ) if result[1] and type(result) == 'table' then outputDebugString("[login] Gracz "..result[1]['char_name'].." (UID: "..result[1]['char_uid']..") zalogował się do gry") else --outputChatBox("#990000Wpisałeś błędne hasło!", client, 255, 255, 255, true); --triggerClientEvent(client, "setPlayerToLogin", client) return end -- tutaj sprawdzanie hasła i zapis wszystkiego i tak dalej setElementData(thePlayer, "player.displayname", result[1]['char_name']) setElementData(thePlayer, "player.originalname", result[1]['char_name']) -- zespawnuj gracza --[[setElementData(client, "player.logged", true) spawnPlayer(client, spawnX, spawnY, spawnZ) fadeCamera(client, true) setCameraTarget(client, client)]]-- -- Start: New spawning -- -- Some strange error when fresh connect. setElementData(thePlayer, "player.logged", true) if tonumber(result[1]["char_spawnplace"]) == 1 then -- znajdź drzwi o uid local uid = tonumber(result[1]["char_house"]) local door = exports.rp_doors:getDoorElementByUID(uid) if not door then spawnPlayer(thePlayer, spawnX, spawnY, spawnZ) else spawnPlayer(thePlayer, tonumber(getElementData(door, "door.exitx")), tonumber(getElementData(door, "door.exity")), tonumber(getElementData(door, "door.exitz"))) setElementDimension(thePlayer, tonumber(getElementData(door, "door.exitvw"))) setElementInterior(thePlayer, tonumber(getElementData(door, "door.exitint"))) end else spawnPlayer(thePlayer, spawnX, spawnY, spawnZ) end --fadeCamera(client, true) --setCameraTarget(client, client) -- END: New spawning -- -- przypisz wartości setElementModel(thePlayer, result[1]["char_skin"]) setPlayerMoney(thePlayer, result[1]["char_cash"]) setElementData(thePlayer, "player.cash", result[1]["char_cash"]) setElementData(thePlayer, "player.bankcash", result[1]["char_bankcash"]) setElementData(thePlayer, "player.uid", result[1]["char_uid"]) setElementData(thePlayer, "player.gid", result[1]["char_gid"]) setElementData(thePlayer, "player.skin", result[1]["char_skin"]) setElementData(thePlayer, "player.afk", 0) --setElementData(client, "player.admin", result[1]["user_admin"]) setElementData(thePlayer, "player.dl", 0) setElementData(thePlayer, "player.gtx", false) setElementData(thePlayer, "player.vehedit", nil) setElementData(thePlayer, "player.coledit", nil) --setElementData(client, "player.gname", result[1]["user_name"]) --setElementData(client, "player.color", result[1]["user_color"]) setElementData(thePlayer, "player.objedit", -1) --setElementData(client, "player.gamescore", tonumber(result[1]["user_gamepoints"])) setElementData(thePlayer, "player.logged", true) setElementData(thePlayer, "player.aj", result[1]["char_aj"]) setElementData(thePlayer, "player.hours", result[1]["char_hours"]) setElementData(thePlayer, "player.minutes", result[1]["char_minutes"]) setElementData(thePlayer, "player.weapons", nil) setElementData(thePlayer, "player.bw", tonumber(result[1]["char_bw"])) setElementData(thePlayer, "player.lastw", false) setElementData(thePlayer, "player.shooting", tonumber(result[1]["char_shooting"])) setElementData(thePlayer, "player.phonenumber", tonumber(0)) --setElementData(client, "player.showtags", tonumber(result[1]["user_showtags"])) --setElementData(client, "player.shaders", tonumber(result[1]["user_shaders"])) -- Miejsce na bronie setElementData(thePlayer, "player.pweapon", nil) setElementData(thePlayer, "player.sweapon", nil) local admin = tonumber(getElementData(thePlayer, "player.admin")) if admin ~= 0 then -- admin if admin > 0 then outputChatBox("#FF574F> Posiadasz uprawnienia administratora!", thePlayer, 255, 255, 255, true) else outputChatBox("#3399CC> Posiadasz uprawnienia supportera!", thePlayer, 255, 255, 255, true) end else -- nie admin -- kickPlayer(client, "Work in progress...") -- return end -- styl chodu dla faceta if result[1]["char_sex"] == 1 then setPedWalkingStyle(thePlayer, 118) end -- styl chodu dla baby if result[1]["char_sex"] == 2 then setPedWalkingStyle(thePlayer, 129) end -- opis setElementData(thePlayer, "player.describe", nil) -- Dodaj event triggerEvent ( "onPlayerLoginSQL", thePlayer) -- wyczyść pamięć if query then dbFree(query) end -- tepnij do AJa po reconnecie exports.rp_punish:checkJail(thePlayer) -- ustaw numer telefonu exports.rp_items:setPlayerPhoneNumberOnJoin(thePlayer) setPlayerNametagShowing(thePlayer, false) outputChatBox("#336699Witaj #FFFFFF".. getElementData(thePlayer, "player.gname") .."#336699! Zalogowałeś się do #FFFFFFLos Santos Role Play#336699, miłej gry!", thePlayer, 255, 255, 255, true) -- sprawdź czy ma BW setPlayerAfterLogBW(thePlayer, tonumber(result[1]["char_posx"]), tonumber(result[1]["char_posy"]), tonumber(result[1]["char_posz"]), tonumber(result[1]["char_int"]), tonumber(result[1]["char_vw"])) -- dodaj, że postać zalogowana local query = dbQuery(handler, "UPDATE lsrp_characters SET char_online = 1 WHERE char_uid = ".. getElementData(thePlayer, "player.uid") ..";") dbFree(query) -- HUD setPlayerHudComponentVisible( thePlayer, "radar", false ) setPlayerHudComponentVisible( thePlayer, "ammo", false ) setPlayerHudComponentVisible( thePlayer, "health", false ) setPlayerHudComponentVisible( thePlayer, "clock", false ) setPlayerHudComponentVisible( thePlayer, "money", false ) setPlayerHudComponentVisible( thePlayer, "armour", false ) setPlayerHudComponentVisible( thePlayer, "weapon", false ) -- Hotfix setPlayerName(thePlayer, result[1]['char_name']) -- Nowe logowanie if getElementDimension(thePlayer) == 0 then triggerClientEvent(thePlayer, "closePlayerLoginForm", thePlayer, false) else setCameraTarget(thePlayer, thePlayer) triggerClientEvent(thePlayer, "closePlayerLoginForm", thePlayer, true) end end end addEvent("onPlayerSelectCharacterByUid", true) addEventHandler("onPlayerSelectCharacterByUid", getRootElement(), onPlayerSelectCharacterByUid)
--- === hs.network === --- --- This module provides functions for inquiring about and monitoring changes to the network. local USERDATA_TAG = "hs.network" local module = {} -- module.reachability = require(USERDATA_TAG..".reachability") -- module.host = require(USERDATA_TAG..".host") -- module.configuration = require(USERDATA_TAG..".configuration") -- module.ping = require(USERDATA_TAG..".ping") -- auto-load submodules as needed local submodules = { reachability = USERDATA_TAG..".reachability", host = USERDATA_TAG..".host", configuration = USERDATA_TAG..".configuration", ping = USERDATA_TAG..".ping", } setmetatable(module, { __index = function(self, key) if submodules[key] then self[key] = require(submodules[key]) end return rawget(self, key) end, }) local inspect = require("hs.inspect") local fnutils = require("hs.fnutils") local log = require"hs.logger".new(USERDATA_TAG, require"hs.settings".get(USERDATA_TAG .. ".logLevel") or "error") module.log = log -- private variables and methods ----------------------------------------- -- Public interface ------------------------------------------------------ --- hs.network.interfaces() -> table --- Function --- Returns a list of interfaces currently active for the system. --- --- Parameters: --- * None --- --- Returns: --- * A table containing a list of the interfaces active for the system. Logs an error and returns nil if there was a problem retrieving this information. --- --- Notes: --- * The names of the interfaces returned by this function correspond to the interface's BSD name, not the user defined name that shows up in the System Preferences's Network panel. --- * This function returns *all* interfaces, even ones used by the system that are not directly manageable by the user. module.interfaces = function() local store = module.configuration.open() if not store then log.d("interfaces - unable to open system dynamic store") return nil end local queryResult = store:contents("State:/Network/Interface") local answer = queryResult and queryResult["State:/Network/Interface"] and queryResult["State:/Network/Interface"].Interfaces if not answer then log.df("interfaces - unexpected query results for State:/Network/Interface: %s", inspect(queryResult)) return nil end return answer end --- hs.network.interfaceDetails([interface | favorIPv6]) -> table --- Function --- Returns details about the specified interface or the primary interface if no interface is specified. --- --- Parameters: --- * interface - an optional string specifying the interface to retrieve details about. Defaults to the primary interface if not specified. --- * favorIPv6 - an optional boolean specifying whether or not to prefer the primary IPv6 or the primary IPv4 interface if `interface` is not specified. Defaults to false. --- --- Returns: --- * A table containing key-value pairs describing interface details. Returns an empty table if no primary interface can be determined. Logs an error and returns nil if there was a problem retrieving this information. --- --- Notes: --- * When determining the primary interface, the `favorIPv6` flag only determines interface search order. If you specify true for this flag, but no primary IPv6 interface exists (i.e. your DHCP server only provides an IPv4 address an IPv6 is limited to local only traffic), then the primary IPv4 interface will be used instead. module.interfaceDetails = function(interface) if type(interface) == "boolean" then interface, favorIPv6 = nil, interface end local store = module.configuration.open() if not store then log.d("interfaceDetails - unable to open system dynamic store") return nil end if not interface then local ipv4, ipv6 = module.primaryInterfaces() interface = (favorIPv6 and ipv6 or ipv4) or (ipv4 or ipv6) if not interface then log.d("interfaceDetails - unable to determine a global primary IPv4 or IPv6 interface") return nil end end local prefix = "State:/Network/Interface/" .. interface .. "/" local queryResult = store:contents(prefix .. ".*", true) if not queryResult then log.df("interfaceDetails - unexpected query results for State:/Network/Interface/%s/.*: %s", interface, inspect(queryResult)) return nil end local results = {} for k, v in pairs(queryResult) do local newK = k:match("^" .. prefix .. "(.*)$") or k results[newK] = v end return results end --- hs.network.primaryInterfaces() -> ipv4Interface, ipv6Interface --- Function --- Returns the names of the primary IPv4 and IPv6 interfaces. --- --- Parameters: --- * None --- --- Returns: --- * The name of the primary IPv4 interface or false if there isn't one, and the name of the IPv6 interface or false if there isn't one. Logs an error and returns a single nil if there was a problem retrieving this information. --- --- Notes: --- * The IPv4 and IPv6 interface names are often, but not always, the same. module.primaryInterfaces = function() local store = module.configuration.open() if not store then log.d("primaryInterfaces - unable to open system dynamic store") return nil end local queryResult = store:contents("State:/Network/Global/IPv[46]", true) if not queryResult then log.df("primaryInterfaces - unexpected query results for State:/Network/Global/IPv[46]: %s", inspect(queryResult)) return nil end return queryResult["State:/Network/Global/IPv4"] and queryResult["State:/Network/Global/IPv4"].PrimaryInterface or false, queryResult["State:/Network/Global/IPv6"] and queryResult["State:/Network/Global/IPv6"].PrimaryInterface or false end --- hs.network.addresses([interface, ...]) -> table --- Function --- Returns a list of the IPv4 and IPv6 addresses for the specified interfaces, or all interfaces if no arguments are given. --- --- Parameters: --- * interface, ... - The interface names to return the IP addresses for. It should be specified as one of the following: --- * one or more interface names, separated by a comma --- * if the first argument is a table, it is assumes to be a table containing a list of interfaces and this list is used instead, ignoring any additional arguments that may be provided --- * if no arguments are specified, then the results of [hs.network.interfaces](#interfaces) is used. --- --- Returns: --- * A table containing a list of the IP addresses for the interfaces as determined by the arguments provided. --- --- Notes: --- * The order of the IP addresses returned is undefined. --- * If no arguments are provided, then this function returns the same results as `hs.host.addresses`, but does not block. module.addresses = function(...) local interfaces = table.pack(...) if interfaces.n == 0 then interfaces = module.interfaces() end if type(interfaces[1]) == "table" then interfaces = interfaces[1] end local store = module.configuration.open() if not store then log.d("addresses - unable to open system dynamic store") return nil end local queryResult = store:contents("State:/Network/Interface/.*/IPv[46]", true) if not queryResult then log.df("addresses - unexpected query results for State:/Network/Interface/.*/IPv[46]: %s", inspect(queryResult)) return nil end local results = {} for k, v in pairs(queryResult) do local intf, prot = k:match("^State:/Network/Interface/([^/]+)/(IPv[46])$") if fnutils.contains(interfaces, intf) then local suffix = (prot == "IPv6") and ("%" .. intf) or "" for i2, v2 in ipairs(v.Addresses) do table.insert(results, v2 .. suffix) end end end return results end --- hs.network.interfaceName([interface | favorIPv6]) -> string --- Function --- Returns the user defined name for the specified interface or the primary interface if no interface is specified. --- * interface - an optional string specifying the interface to retrieve the name for. Defaults to the primary interface if not specified. --- * favorIPv6 - an optional boolean specifying whether or not to prefer the primary IPv6 or the primary IPv4 interface if `interface` is not specified. Defaults to false. --- --- Returns: --- * A string containing the user defined name for the interface, if one exists, or false if the interface does not have a user defined name. Logs an error and returns nil if there was a problem retrieving this information. --- --- Notes: --- * Only interfaces which show up in the System Preferences Network panel will have a user defined name. --- --- * When determining the primary interface, the `favorIPv6` flag only determines interface search order. If you specify true for this flag, but no primary IPv6 interface exists (i.e. your DHCP server only provides an IPv4 address an IPv6 is limited to local only traffic), then the primary IPv4 interface will be used instead. module.interfaceName = function(interface, favorIPv6) if type(interface) == "boolean" then interface, favorIPv6 = nil, interface end local store = module.configuration.open() if not store then log.d("interfaceName - unable to open system dynamic store") return nil end if not interface then local ipv4, ipv6 = module.primaryInterfaces() interface = (favorIPv6 and ipv6 or ipv4) or (ipv4 or ipv6) if not interface then log.d("interfaceName - unable to determine a global primary IPv4 or IPv6 interface") return nil end end local queryResult = store:contents("Setup:/Network/Service/.*/Interface", true) if not queryResult then log.df("interfaceName - unexpected query results for Setup:/Network/Service/.*/Interface: %s", inspect(queryResult)) return nil end local results = {} for k, v in pairs(queryResult) do if v.DeviceName == interface then return v.UserDefinedName end end return false end -- Return Module Object -------------------------------------------------- return module
-- ----------------------------------------------------------------------------- -- Temp fix to sasl logging issue -- ----------------------------------------------------------------------------- function logDebug(message) -- print(message) end -- ----------------------------------------------------------------------------- include "acars/acarsDatarefs.lua" require "extraMaths" network = require("network") include "acars/acarsHandlers.lua" include "settingsCore.lua"
//________________________________ // // NS2 Single-Player Mod // Made by JimWest, 2012 // //________________________________ // base class for spawning npcs class 'NpcQueueManager' (Entity) NpcQueueManager.kMapName = "npc_queue_manager" local kMaxQueueEntries = 30 local networkVars = { } if Server then local function UpdateQueue(self) if #self.kNpcQueue > 0 and NpcUtility_GetCanSpawnNpc() then for i, entry in ipairs(self.kNpcQueue) do NpcUtility_Spawn(entry.origin, entry.className, entry.values, entry.waypoint) table.remove(self.kNpcQueue, i) if not NpcUtility_GetCanSpawnNpc() then break end end end return true end function NpcQueueManager:OnCreate() end function NpcQueueManager:OnInitialized() self.kNpcQueue = {} self:AddTimedCallback(UpdateQueue, 1) end function NpcQueueManager:AddToQueue(values) table.insert(self.kNpcQueue, values) if #self.kNpcQueue > kMaxQueueEntries then // if there are to many entries, delete the oldest one table.remove(self.kNpcQueue, 1) end end function NpcQueueManager:Reset() kLastSpawnTime = 0 kSpawnedNpcs = 0 kNpcList = {} self.kNpcQueue = {} end function NpcQueueManager:GetIsMapEntity() return true end end Shared.LinkClassToMap("NpcQueueManager", NpcQueueManager.kMapName, networkVars)
local invisibleBarrier = {} invisibleBarrier.name = "MaxHelpingHand/OneWayInvisibleBarrierHorizontal" invisibleBarrier.fillColor = {0.4, 0.4, 0.4, 0.8} invisibleBarrier.borderColor = {0.0, 0.0, 0.0, 0.0} invisibleBarrier.canResize = {false, true} invisibleBarrier.placements = { { name = "left", data = { width = 8, height = 8, left = true, letSeekersThrough = false } }, { name = "right", data = { width = 8, height = 8, left = false, letSeekersThrough = false } } } return invisibleBarrier
local playsession = { {"CawaEast", {141906}}, {"HumaniTea", {143424}}, {"MrJSelig", {132928}}, {"LeeFactor", {3631}}, {"625dennis", {113905}}, {"James_Hackett", {77027}}, {"Llzzard", {61741}} } return playsession
require("arshlib.tables") require("arshlib.strings")
#!/usr/bin/lua --[[ includes ]]------------------------------------------------------------ require "luarocks.require" require "json" -- http://wiki.openwrt.org/doc/devel/uci-lua package.cpath = package.cpath .. ";/Users/antoine/afrimesh/ext/darwin/lib/lua5.1/?.so" package.cpath = package.cpath .. ";/usr/share/lua/5.1/?.so" uci = require("uci") uci = uci.cursor() --[[ utils ]]------------------------------------------------------------ require "common" --[[ logging ]]------------------------------------------------------------ require "logging" require "logging.file" logname = "/tmp/provision.log" os.pexecute("touch " .. logname) os.pexecute("chmod 0666 " .. logname) log = logging.file(logname) if not log then log = logging.file("/dev/null") end -- log:setLevel(logging.INFO) log:setLevel(logging.DEBUG) log:info("provision.lua starting") --[[ definitions ]]--------------------------------------------------------- function readconf() local factory = { mode = "ahdemo", ssid = "potato", bssid = "01:CA:FF:EE:BA:BE", channel = "1", network = "10.130.1.0", netmask = "255.255.255.0", root = "10.130.1.1", } local wireless = { } uci:foreach("wireless", "wifi-iface", function(entry) local wifi = { device = entry.device, ssid = entry.ssid, bssid = entry.bssid, mode = entry.mode } wifi.interface = uci:get("network", wifi.device, "ifname") wifi.address = uci:get("network", wifi.device, "ipaddr") wifi.mac = os.pexecute("ifconfig " .. wifi.interface .. " | grep HWaddr | awk '{ print $5 }'") wifi.mac = string.upper(wifi.mac) wifi.type = uci:get("wireless", wifi.device, "type") wifi.channel = uci:get("wireless", wifi.device, "channel") table.insert(wireless, wifi) end) local ethernet = { } ethernet.interface = uci:get("network.lan.ifname") ethernet.address = uci:get("network.lan.ipaddr") ethernet.mac = os.pexecute("ifconfig " .. ethernet.interface .. " | grep HWaddr | awk '{ print $5 }'") ethernet.mac = string.upper(ethernet.mac) local conf = { provision = "/cgi-bin/villagebus.lua/provision/router", deviceid = uci:get("afrimesh.settings.deviceid") or "", root = uci:get("afrimesh.settings.root") or factory.root, wireless = wireless, ethernet = ethernet, factory = factory } return conf end --[[ main ]]---------------------------------------------------------------- function main(arg) local conf = readconf(); log:info("root: " .. conf.root) log:info("id: " .. conf.deviceid) log:info("mac: " .. conf.wireless[1].mac) log:info("address: " .. conf.wireless[1].address) log:debug("conf : " .. json.encode(conf)) -- check if device has been provisioned common.REST({ host = conf.root, verb = "GET", path = conf.provision, query = { deviceid = conf.deviceid, mac = conf.wireless[1].mac, address = conf.wireless[1].address } }, function(error, data) if error then -- TODO print("Fail: " .. error) return end print("Got: " .. data) end) --[[ name="/cgi-bin/villagebus/db/provision:$self:mac" REQUEST="GET $name HTTP/1.0 " provisioned_mac=`echo -n "$REQUEST" | nc $root 80 | grep jsonp | cut -d\" -f 2` echo "provisioned: $provisioned_mac" echo [ "$wifi0_mac" == "$provisioned_mac" ] && { logger "$wifi0_mac ($self) already provisioned, exiting." echo "$wifi0_mac ($self) already provisioned, exiting." echo exit } # nuke any existing deviceid uci del afrimesh.settings.deviceid uci commit ]]-- end main(arg)
function DIALOG() NODE(0) GETGLOBALTRIGGER("talked_sk_aw") if result == 0 then --064 SAYSPEECH("Was wollen Sie? Ich hab nichts mehr! Das verdammte Terroristenpack hat mir alles abgenommen. Nur wertlosen Plunder und radioaktives Zeug haben sie mir gelassen. Sind das etwa die 'umfangreichen Sicherheitsmassnahmen', von denen die CityAdmin immer spricht?",3064) TRADE() ENDDIALOG() else if result == 1 then --64 SAYSPEECH("Was wollen Sie? Ich hab nichts mehr! Das verdammte Terroristenpack hat mir alles abgenommen. Nur wertlosen Plunder und radioaktives Zeug haben sie mir gelassen. Sind das etwa die 'umfangreichen Sicherheitsmassnahmen', von denen die CityAdmin immer spricht?",3064) --65 ANSWERSPEECH("Dieses 'radioaktive Zeug'... worum handelt es sich dabei?",1,3065) else --064 SAYSPEECH("Was wollen Sie? Ich hab nichts mehr! Das verdammte Terroristenpack hat mir alles abgenommen. Nur wertlosen Plunder und radioaktives Zeug haben sie mir gelassen. Sind das etwa die 'umfangreichen Sicherheitsmassnahmen', von denen die CityAdmin immer spricht?",3064) TRADE() ENDDIALOG() end end NODE(1) --067 SAYSPEECH("Keine Ahnung - Deulithium oder Thithium oder so... Die Typen hatten so `ne Art Geigerzaehler dabei, mit dem sie mein gesamtes Lager abgeleuchtet haben... bei dem Zeug spielte der Apparat total verrueckt, und sie liessen es fallen wie heisse Kartoffeln... Dabei soll es einiges wert sein...",3067) --068 ANSWERSPEECH("Gemaess Verordnung 17-TR-2 beschlagnahme ich das Deutrithium im Namen der Neocron City Administation. Geben Sie mir den Behaelter!",2,3068) --069 ANSWERSPEECH("Hoeren Sie... ich haette Verwendung fuer das Zeug. Ich bin Agent der CityAdmin. Geben Sie mir die Chemikalien in dem Bewusstsein, Ihrer Regierung einen wertvollen Dienst erweisen zu koennen.",3,3069) NODE(2) --071 SAYSPEECH("Die NCA ist auch nicht besser als der Twilight Guardian... alle denken, sie koennten sich einfach nehmen, was sie wollen... Verdammt... hier, nehmen Sie den Behaelter, und dann verschwinden Sie aus meinem Laden!",3071) GIVEITEM(714) SETGLOBALTRIGGER("talked_sk_aw",2) SENDLEVELMSG( "PAWNSHOP") ENDDIALOG() NODE(3) --073 SAYSPEECH("...einen wertvollen Dienst? Meinen Sie, dass der Regierung dieser Dienst 500 Maeuse wert ist? Die haette ich naemlich gern fuer das Zeug...",3073) --074 ANSWERSPEECH("Ersticken Sie nicht an Ihrer Liebe zur Regierung, Sir! - Hier haben Sie das Geld - und jetzt her mit dem Kanister!",4,3074) --075 ANSWERSPEECH("Ich habe nicht genug Geld bei mir... Ich komme wieder...",5,3075) NODE(4) TAKEMONEY(500) GIVEITEM(714) --078 SAYSPEECH("Es war mir ein Vergnuegen der Regierung gedient zu haben... Beehren Sie mich bald wieder... hehehe!",3078) SETGLOBALTRIGGER("talked_sk_aw",2) ENDDIALOG() NODE(5) GIVEITEM(714) --079 SAYSPEECH("Schon gut... wenn es so dringend ist, dann nehmen Sie den Kanister. Weiss zwar nicht, wofuer sie das Zeug brauchen, aber ich wuensch Ihnen viel Glueck damit...",3079) SETGLOBALTRIGGER("talked_sk_aw",2) SHOWTUTORIALTEXT(1232,1) ENDDIALOG() end
dofile(FullSpeedSwarm._path .. "mutators/mutatorbigparty.lua") local fs_original_mutatorsmanager_init = MutatorsManager.init function MutatorsManager:init() fs_original_mutatorsmanager_init(self) table.insert(self._mutators, MutatorBigParty:new(self)) local id = MutatorBigParty._type local data = Global.mutators.active_on_load[id] if data then local mutator = self:get_mutator_from_id(id) table.insert(self:active_mutators(), {mutator = mutator}) for key, value in pairs(data) do if Network:is_client() then mutator:set_host_value(key, value) end end mutator:setup(self) end end
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] local ZO_SoulGemItemCharger_Gamepad = ZO_InventoryItemImprovement_Gamepad:Subclass() function ZO_SoulGemItemCharger_Gamepad:New(...) return ZO_InventoryItemImprovement_Gamepad.New(self, ...) end function ZO_SoulGemItemCharger_Gamepad:Initialize(control) local function IsFilledSoulGem(bagId, slotIndex) return IsItemSoulGem(SOUL_GEM_TYPE_FILLED, bagId, slotIndex) end local function SortComparator(left, right) return GetSoulGemItemInfo(left.bag, left.index) < GetSoulGemItemInfo(right.bag, right.index) end ZO_InventoryItemImprovement_Gamepad.Initialize( self, control, GetString(SI_CHARGE_WEAPON_TITLE), "soulGemItemChargerGamepad", GetString(SI_CHARGE_WEAPON_SELECT), GetString(SI_CHARGE_WEAPON_NONE_FOUND), GetString(SI_CHARGE_WEAPON_CONFIRM), SOUNDS.INVENTORY_ITEM_APPLY_CHARGE, IsFilledSoulGem, SortComparator) end function ZO_SoulGemItemCharger_Gamepad:SetupScene() SOUL_GEM_ITEM_CHARGER_SCENE_GAMEPAD = ZO_Scene:New(self.sceneName, SCENE_MANAGER) SYSTEMS:RegisterGamepadRootScene("soulgem", SOUL_GEM_ITEM_CHARGER_SCENE_GAMEPAD) end function ZO_SoulGemItemCharger_Gamepad:UpdateTooltipOnSelectionChanged() GAMEPAD_TOOLTIPS:LayoutPendingItemCharge(GAMEPAD_LEFT_TOOLTIP, self.itemBag, self.itemIndex, self.improvementKitBag, self.improvementKitIndex) end function ZO_SoulGemItemCharger_Gamepad:PerformItemImprovement() ChargeItemWithSoulGem(self.itemBag, self.itemIndex, self.improvementKitBag, self.improvementKitIndex) end --[[ Globals ]]-- function ZO_Gamepad_SoulGemItemCharger_OnInitialize(control) SOUL_GEM_ITEM_CHARGER_GAMEPAD = ZO_SoulGemItemCharger_Gamepad:New(control) SYSTEMS:RegisterGamepadObject("soulgem", SOUL_GEM_ITEM_CHARGER_GAMEPAD) end
local _, Addon = ... -- if we don't have an extra action bar in this client, then quit local ZoneAbilityFrame = _G.ZoneAbilityFrame if not ZoneAbilityFrame then Addon.Layout.zone = Addon.Layout.noop Addon.Layout.zoneBar = Addon.Layout.noop return end -------------------------------------------------------------------------------- -- Blizzard Workarounds -------------------------------------------------------------------------------- -- tell the UIManager that we're handling the frame ZoneAbilityFrame.ignoreFramePositionManager = true -------------------------------------------------------------------------------- -- Layout Action -------------------------------------------------------------------------------- local DEFAULTS = { id = "zone", point = "BOTTOM", y = 160 } local function addZoneAbilityFrame(bar) bar:SetSize(ZoneAbilityFrame:GetSize()) bar:SetFrameStrata(ZoneAbilityFrame:GetFrameStrata()) ZoneAbilityFrame:ClearAllPoints() ZoneAbilityFrame:SetParent(bar) ZoneAbilityFrame:SetPoint("CENTER") end Addon.Layout.zone = function(options) options = Addon:CopyDefaults(options, DEFAULTS) local bar = Addon:CreateBar(options) addZoneAbilityFrame(bar) return bar end Addon.Layout.zoneBar = Addon.Layout.zone
-- ImageManager.lua -- The image manager for LoveExtension Library -- Copyright (c) 2011 Robert MacGregor local Image = { } Image.DataBase = { } function Image.loadImage(File) if (Image.getImageID(File) == nil) then local nImage = love.graphics.newImage(File) Image.DataBase[File] = nImage table.insert(Image.DataBase, nImage) return nImage else return Image.getImage(Image.getImageID(File)) end return nil end function Image.getImageID(File) if (Image.DataBase[File] == nil) then return nil end local nImage = Image.DataBase[File] for i = 0, table.getn(Image.DataBase) do if (Image.DataBase[i] == nImage) then return i end end return nil end function Image.getCount() return table.getn(Image.DataBase) end function Image.getImage(ID) return Image.DataBase[ID] end return Image
ESX = nil PlayerData = {} Citizen.CreateThread(function() while ESX == nil do Citizen.Wait(10) TriggerEvent("esx:getSharedObject", function(response) ESX = response end) end if ESX.IsPlayerLoaded() then PlayerData = ESX.GetPlayerData() RemoveVehicles() Citizen.Wait(500) LoadSellPlace() SpawnVehicles() end end) RegisterNetEvent("esx:playerLoaded") AddEventHandler("esx:playerLoaded", function(response) PlayerData = response LoadSellPlace() SpawnVehicles() end) RegisterNetEvent("esx-qalle-sellvehicles:refreshVehicles") AddEventHandler("esx-qalle-sellvehicles:refreshVehicles", function() RemoveVehicles() Citizen.Wait(500) SpawnVehicles() end) function LoadSellPlace() Citizen.CreateThread(function() local SellPos = Config.SellPosition local Blip = AddBlipForCoord(SellPos["x"], SellPos["y"], SellPos["z"]) SetBlipSprite (Blip, 147) SetBlipDisplay(Blip, 4) SetBlipScale (Blip, 0.8) SetBlipColour (Blip, 52) SetBlipAsShortRange(Blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString("Vente de voiture d'ocasion") EndTextCommandSetBlipName(Blip) while true do local sleepThread = 500 local ped = PlayerPedId() local pedCoords = GetEntityCoords(ped) local dstCheck = GetDistanceBetweenCoords(pedCoords, SellPos["x"], SellPos["y"], SellPos["z"], true) if dstCheck <= 10.0 then sleepThread = 5 if dstCheck <= 4.2 then ESX.Game.Utils.DrawText3D(SellPos, "Appuyez sur [E] pour ouvrir le menu", 0.4) if IsControlJustPressed(0, 38) then if IsPedInAnyVehicle(ped, false) then OpenSellMenu(GetVehiclePedIsUsing(ped)) else ESX.ShowNotification("Vous devez être dans un ~g~véhicule") end end end end for i = 1, #Config.VehiclePositions, 1 do if Config.VehiclePositions[i]["entityId"] ~= nil then local pedCoords = GetEntityCoords(ped) local vehCoords = GetEntityCoords(Config.VehiclePositions[i]["entityId"]) local dstCheck = GetDistanceBetweenCoords(pedCoords, vehCoords, true) if dstCheck <= 2.0 then sleepThread = 5 ESX.Game.Utils.DrawText3D(vehCoords, "[E] " .. Config.VehiclePositions[i]["price"] .. ":-", 0.4) if IsControlJustPressed(0, 38) then if IsPedInVehicle(ped, Config.VehiclePositions[i]["entityId"], false) then OpenSellMenu(Config.VehiclePositions[i]["entityId"], Config.VehiclePositions[i]["price"], true, Config.VehiclePositions[i]["owner"]) else ESX.ShowNotification("Vous devez être dans un ~g~véhicule") end end end end end Citizen.Wait(sleepThread) end end) end function OpenSellMenu(veh, price, buyVehicle, owner) local elements = {} if not buyVehicle then if price ~= nil then table.insert(elements, { ["label"] = "Changer le prix - " .. price .. " :-", ["value"] = "price" }) table.insert(elements, { ["label"] = "Put out for sale", ["value"] = "sell" }) else table.insert(elements, { ["label"] = "Set Price - :-", ["value"] = "price" }) end else table.insert(elements, { ["label"] = "Acheter " .. price .. " - :-", ["value"] = "buy" }) if owner then table.insert(elements, { ["label"] = "Enlever un véhicule", ["value"] = "remove" }) end end ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'sell_veh', { title = "Vehicle Menu", align = 'top-right', elements = elements }, function(data, menu) local action = data.current.value if action == "price" then ESX.UI.Menu.Open('dialog', GetCurrentResourceName(), 'sell_veh_price', { title = "Vehicle Price" }, function(data2, menu2) local vehPrice = tonumber(data2.value) menu2.close() menu.close() OpenSellMenu(veh, vehPrice) end, function(data2, menu2) menu2.close() end) elseif action == "sell" then local vehProps = ESX.Game.GetVehicleProperties(veh) ESX.TriggerServerCallback("esx-qalle-sellvehicles:isVehicleValid", function(valid) if valid then DeleteVehicle(veh) ESX.ShowNotification("You put out the ~g~vehicle~s~ for sale - " .. price .. " :-") menu.close() else ESX.ShowNotification("You must ~r~own~s~ the ~g~vehicle!~s~ / it's ~r~already~s~ " .. #Config.VehiclePositions .. " vehicles for sale!") end end, vehProps, price) elseif action == "buy" then ESX.TriggerServerCallback("esx-qalle-sellvehicles:buyVehicle", function(isPurchasable, totalMoney) if isPurchasable then DeleteVehicle(veh) ESX.ShowNotification("You ~g~bought~s~ the vehicle for " .. price .. " :-") menu.close() else ESX.ShowNotification("You ~r~don't~s~ have enough cash, it's missing " .. price - totalMoney .. " :-") end end, ESX.Game.GetVehicleProperties(veh), price) elseif action == "remove" then ESX.TriggerServerCallback("esx-qalle-sellvehicles:buyVehicle", function(isPurchasable, totalMoney) if isPurchasable then DeleteVehicle(veh) ESX.ShowNotification("You ~g~removed~s~ the vehicle") menu.close() end end, ESX.Game.GetVehicleProperties(veh), 0) end end, function(data, menu) menu.close() end) end function RemoveVehicles() local VehPos = Config.VehiclePositions for i = 1, #VehPos, 1 do local veh, distance = ESX.Game.GetClosestVehicle(VehPos[i]) if DoesEntityExist(veh) and distance <= 1.0 then DeleteEntity(veh) end end end function SpawnVehicles() local VehPos = Config.VehiclePositions ESX.TriggerServerCallback("esx-qalle-sellvehicles:retrieveVehicles", function(vehicles) for i = 1, #vehicles, 1 do local vehicleProps = vehicles[i]["vehProps"] LoadModel(vehicleProps["model"]) VehPos[i]["entityId"] = CreateVehicle(vehicleProps["model"], VehPos[i]["x"], VehPos[i]["y"], VehPos[i]["z"] - 0.975, VehPos[i]["h"], false) VehPos[i]["price"] = vehicles[i]["price"] VehPos[i]["owner"] = vehicles[i]["owner"] ESX.Game.SetVehicleProperties(VehPos[i]["entityId"], vehicleProps) FreezeEntityPosition(VehPos[i]["entityId"], true) SetEntityAsMissionEntity(VehPos[i]["entityId"], true, true) SetModelAsNoLongerNeeded(vehicleProps["model"]) end end) end LoadModel = function(model) while not HasModelLoaded(model) do RequestModel(model) Citizen.Wait(1) end end
local cjson = require("cjson") local _M = {} _M.mysql = {} function _M.mysql.replace_meta_value(store,key,value) return store:update({ sql = "replace into meta SET `key`=?, `value`=?", params = { key, value } }) end function _M.mysql.select_meta_value(store,key) return store:query({ sql = "select `value` from meta where `key`=?", params = { key } }) end function _M.mysql.select_redirect_rules(store) return store:query({ sql = "select `value` from redirect order by id asc" }) end function _M.mysql.insert_redirect_rules(store,key,value) return store:insert({ sql = "insert into redirect(`key`, `value`) values(?,?)", params = { key, cjson.encode(value)} }) end function _M.mysql.delete_redirect_rules(store,key) return store:delete({ sql = "delete from redirect where `key`=?", params = { key } }) end function _M.mysql.update_redirect_rules(store,key,value) return store:update({ sql = "update redirect set `value`=? where `key`=?", params = { cjson.encode(value), key } }) end _M.pgsql = {} function _M.pgsql.replace_meta_value(store,key,value) return store:update({ sql = "select replace_meta_value(?,?);", params = { key, value } }) end function _M.pgsql.select_meta_value(store,key) return store:query({ sql = "select value from meta where key=?", params = { key } }) end function _M.pgsql.select_redirect_rules(store) return store:query({ sql = "select value from redirect order by id asc" }) end function _M.pgsql.insert_redirect_rules(store,key,value) return store:insert({ sql = "insert into redirect(key, value) values(?,?)", params = { key, value} }) end function _M.pgsql.delete_redirect_rules(store,key) return store:delete({ sql = "delete from redirect where key=?", params = { key } }) end function _M.pgsql.update_redirect_rules(store,key,value) return store:update({ sql = "update redirect set value=? where key=?", params = { value, key } }) end function _M.replace_meta_value(store,key,value) return _M[store.store_type].replace_meta_value(store,key,value) end function _M.select_meta_value(store,key) return _M[store.store_type].select_meta_value(store,key) end function _M.select_redirect_rules(store) return _M[store.store_type].select_redirect_rules(store) end function _M.insert_redirect_rules(store,key,value) return _M[store.store_type].insert_redirect_rules(store,key,value) end function _M.delete_redirect_rules(store,key) return _M[store.store_type].delete_redirect_rules(store,key) end function _M.update_redirect_rules(store,key,value) return _M[store.store_type].update_redirect_rules(store,key,value) end return _M
-------------------------------------------------------------------------------- -- 81-703 controller panel -------------------------------------------------------------------------------- -- Copyright (C) 2013-2018 Metrostroi Team & FoxWorks Aerospace s.r.o. -- Contains proprietary code. See license.txt for additional information. -------------------------------------------------------------------------------- Metrostroi.DefineSystem("81_703_Panel") function TRAIN_SYSTEM:Initialize() -- Выключатель батареи (ВБ) self.Train:LoadSystem("VB","Relay","Switch", {bass = true}) self.Train:LoadSystem("AV","Relay","Switch", {bass = true}) self.Train:LoadSystem("VU","Relay","Switch", {bass = true,normally_closed = true}) self.Train:LoadSystem("VU1","Relay","Switch", {bass = true}) --Heater self.Train:LoadSystem("VU2","Relay","Switch", {bass = true}) --EmergencyLights self.Train:LoadSystem("VU3","Relay","Switch", {bass = true}) --CabLights -- Buttons on the panel self.Train:LoadSystem("KU1","Relay","Switch", {bass = true}) --MK self.Train:LoadSystem("KU2","Relay","Switch", {bass = true}) --VUD1 self.Train:LoadSystem("KU3","Relay","Switch", {bass = true,normally_closed = true}) --VUD2 self.Train:LoadSystem("KU4","Relay","Switch", {bass = true}) --Lights on self.Train:LoadSystem("KU5","Relay","Switch", {bass = true}) --Lights off self.Train:LoadSystem("KU6","Relay","Switch", {bass = true}) --KDL self.Train:LoadSystem("KU7","Relay","Switch", {bass = true}) --KDP self.Train:LoadSystem("KU6K","Relay","Switch", {bass = true}) --KDLK self.Train:LoadSystem("KU7K","Relay","Switch", {bass = true}) --KDPK self.Train:LoadSystem("KU8","Relay","Switch", {bass = true}) --KSN self.Train:LoadSystem("KU9","Relay","Switch", {bass = true}) --Vozvrat RP self.Train:LoadSystem("KU10","Relay","Switch", {bass = true}) --KRZD self.Train:LoadSystem("KU11","Relay","Switch", {bass = true}) --Door sig self.Train:LoadSystem("KU12","Relay","Switch", {bass = true}) --Scepleniye self.Train:LoadSystem("KU13","Relay","Switch", {bass = true}) --Left doors2 self.Train:LoadSystem("KU15","Relay","Switch", {bass = true}) --RezMK self.Train:LoadSystem("KU16","Relay","Switch", {bass = true}) --Headlights self.Train:LoadSystem("RCU","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_UNch","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_ZS","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_G","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Radio","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Program1","Relay","Switch", {bass = true}) self.Train:LoadSystem("R_Program2","Relay","Switch", {bass = true}) self.Train:LoadSystem("RST","Relay","Switch", {bass = true, normally_closed=true}) self.Train:LoadSystem("PanelLamp","Relay","Switch", {bass = true, normally_closed=true}) self.V1 = 0 self.GRP = 0 self.RRP = 0 self.TW18 = 0 self.SD = 0 self.Headlights1 = 0 self.Headlights2 = 0 self.RedLights = 0 self.EmergencyLights2 = 0 self.EmergencyLights1 = 0 self.MainLights1 = 0 self.MainLights2 = 0 self.PanelLights = 0 self.Ring = 0 self.VPR = 0 self.AnnouncerPlaying = 0 self.PCBKPower = 0 end function TRAIN_SYSTEM:ClientInitialize() end function TRAIN_SYSTEM:Outputs() return { "V1","GRP","RRP","TW18","SD","Headlights1","Headlights2","RedLights","EmergencyLights2","EmergencyLights1","MainLights1","MainLights2","PanelLights","AnnouncerPlaying","VPR","Ring","CBKIPower","PCBKPower"} end
--[[ 2020-2021 Xalalau Xubilozo. MIT License https://xalalau.com/ HACKS: For some reason these functions are EXTREMELY temperamental! I was unable to use the nested code, to pass arguments and even to freely write variables or acceptable syntax. They only work when it's this mess. Test each changed line if you want to touch them, or you'll regret it bitterly! Note: I can't check the stack in the wrong environment, so don't use this: table.insert(BS.locals, some_function) when there're _debug.getinfo or _debug.getlocal present. ]] -- I can't pass arguments or move the functions to our environment, so I copy my tables locally local BS_protectedCalls_Hack local BS_traceBank_Hack -- Protect against detouring and always get real results local _debug = {} _debug.getinfo = debug.getinfo _debug.getlocal = debug.getlocal local _string = {} _string.Explode = string.Explode _string.find = string.find local _tostring = tostring local _ipairs = ipairs local _pairs = pairs local __G = _G -- Workaround to pass arguments local argsPop = {} -- Copy some tables locally (also a workaround) function BS:Stack_Init() BS_protectedCalls_Hack = table.Copy(self.protectedCalls) BS_traceBank_Hack = self.traceBank end -- Insert arguments into argsPop local function InsertArgs(args) table.insert(argsPop, args) end table.insert(BS.locals, InsertArgs) -- Check for prohibited function combinations (scanning by address) -- If the stack is good, return false -- If the stack is bad, return "protected func name" local function Stack_Check() local vars = { -- Note: adding new variables outside this table can break the function for some reason increment = 1, detected = 0, currentFuncAddress, currentFuncName } -- This is how I'm passing arguments for k,arg in _ipairs(argsPop) do vars.currentFuncAddress = arg[1] vars.currentFuncName = arg[2] argsPop[k] = nil break end while true do local func = _debug.getinfo(vars.increment, "flnSu" ) if func == nil then break end local name, value = _debug.getlocal(1, 2, vars.increment) if value then -- Update the name and address using info from the trace bank, if it's the case local traceBank = BS_traceBank_Hack[_tostring(value.func)] if traceBank then local func = __G for k,v in _ipairs(_string.Explode(".", traceBank.name)) do func = func[v] end value.func = func -- Use the address of the last function from the older stack, so we can keep track of what's happening value.name = traceBank.name end -- Now we are going to check if it's a protected function call if value.func then -- Find the current call if vars.detected == 0 and _tostring(value.func) == _tostring(vars.currentFuncAddress) then -- I tried to compare the addresses directly but it doesn't work here -- Debug --print("---> FOUND CURRENT CALL") vars.detected = vars.detected + 1 value.name = vars.currentFuncName else -- Find a forbidden previous caller for funcName,funcAddress in _pairs(BS_protectedCalls_Hack) do -- I tried to use the function address as index but it doesn't work here if vars.detected == 1 and _tostring(value.func) == _tostring(funcAddress) then -- Debug --print("---> FOUND FORBIDDEN CALLER") vars.detected = vars.detected + 1 value.name = funcName end end end end end -- Debug --print(value.name and value.name or "") --print(value.func) -- Forbidden caller found if vars.detected == 2 then return value.name end vars.increment = vars.increment + 1 end return false end function BS:Stack_Check(funcName) InsertArgs({ self:Detours_GetFunction(funcName), funcName }) return Stack_Check() end -- Get the function of the higher call in the stack local function Stack_GetTopFunctionAddress() local vars = { increment = 1, func = nil } while true do local func = _debug.getinfo(vars.increment, "flnSu") local name, value = _debug.getlocal(1, 2, vars.increment) if func == nil then break end if value then vars.func = value.func end vars.increment = vars.increment + 1 end return vars.func end function BS:Stack_GetTopFunctionAddress() return Stack_GetTopFunctionAddress() end -- Return the result debug.getinfo result skipping our functions local function Stack_SkipBSFunctions() local vars = { -- Note: adding new variables outside this table can break the function for some reason increment = 1, skipLevel = false, foundGetinfo = false, foundBSAgain = false, requiredStackLevel, requiredFields, luaFolder, args } -- This is how I'm passing arguments for k,arg in _ipairs(argsPop) do vars.requiredStackLevel = arg[1] vars.requiredFields = arg[2] vars.luaFolder = arg[3] argsPop[k] = nil break end while true do local func = _debug.getinfo(vars.increment, "flnSu" ) if func == nil then break end local name, value = _debug.getlocal(1, 2, vars.increment) if value then -- Step 4: skip BS files. -- The correct result is the top of the stack. -- If the required stack level is out of bounds, this loop will break, because we skipped a level in step 2. if vars.foundBSAgain then local result = _debug.getinfo(vars.increment, vars.requiredFields) if not _string.find(_debug.getinfo(vars.increment,"S")["short_src"], "/lua/" .. vars.luaFolder) then if vars.requiredStackLevel == 1 then return result end vars.requiredStackLevel = vars.requiredStackLevel - 1 end -- Step 3: Keep going until stack level is 1 and return if it's not checking BS files. -- If BS files are found, skip then. elseif vars.foundGetinfo then local result = _debug.getinfo(vars.increment, vars.requiredFields) if result and _string.find(_debug.getinfo(vars.increment,"S")["short_src"], "/lua/" .. vars.luaFolder) then vars.foundBSAgain = true else if vars.requiredStackLevel == 1 then return result end vars.requiredStackLevel = vars.requiredStackLevel - 1 end -- Step 2: Skip a stack level, so we can check the stack locally using vars. elseif vars.skipLevel then vars.foundGetinfo = true -- Step 1: Find debug.getinfo. -- Return if the stack level is 1. elseif value.func == debug.getinfo then if vars.requiredStackLevel == 1 then return _debug.getinfo(vars.increment, vars.requiredFields) else vars.skipLevel = true vars.requiredStackLevel = vars.requiredStackLevel - 1 end end --Debug --print(value.name) --print(value.func == debug.getinfo) end vars.increment = vars.increment + 1 end end function BS:Stack_SkipBSFunctions(args) table.insert(args, self.folder.lua) InsertArgs(args) return Stack_SkipBSFunctions() end
-- Function values can be declared or assigned function odd(x) return x % 2 == 1 end square = function (x) return x * x end twice = function (f, x) return f(f(x)) end -- We can call anonymous functions assert((function (x) return x + 5 end)(10) == 15) -- We can pass function values to other functions assert(twice(square, -3) == 81) assert(twice(function (x) return x + 1 end, 5) == 7) -- We can create and return new functions on the fly function compose(f, g) return function (x) return f(g(x)) end end is_odd_when_squared = compose(odd, square) assert(is_odd_when_squared(7)) assert(not is_odd_when_squared(0)) -- Too many arguments are fine, extras are ignored assert((function (x) return x + 1 end)(8, 2) == 9) -- Not passing enough arguments is fine, extras get nil do (function (x, y) assert(y == nil) end)(1) end
-------------------------------- -- @module EaseRateAction -- @extend ActionEase -- @parent_module cc ---@class cc.EaseRateAction:cc.ActionEase local EaseRateAction = {} cc.EaseRateAction = EaseRateAction -------------------------------- --- brief Set the rate value for the ease rate action. --- param rate The value will be set. ---@param rate number ---@return cc.EaseRateAction function EaseRateAction:setRate(rate) end -------------------------------- --- brief Initializes the action with the inner action and the rate parameter. --- param pAction The pointer of the inner action. --- param fRate The value of the rate parameter. --- return Return true when the initialization success, otherwise return false. ---@param pAction cc.ActionInterval ---@param fRate number ---@return boolean function EaseRateAction:initWithAction(pAction, fRate) end -------------------------------- --- brief Get the rate value of the ease rate action. --- return Return the rate value of the ease rate action. ---@return number function EaseRateAction:getRate() end -------------------------------- --- ---@param action cc.ActionInterval ---@param rate number ---@return cc.EaseRateAction function EaseRateAction:create(action, rate) end return nil
-- See LICENSE for terms -- add some shortened func names dump = ChoGGi.ComFuncs.Dump dumplua = ChoGGi.ComFuncs.DumpLua dumptable = ChoGGi.ComFuncs.DumpTable trans = ChoGGi.ComFuncs.Translate MonitorFunc = ChoGGi.ComFuncs.MonitorFunctionResults so = ChoGGi.ComFuncs.SelObject -- used for console rules, so we can get around it spamming the log local OpenInImageViewerDlg = ChoGGi.ComFuncs.OpenInImageViewerDlg function OpenImageViewer(...) OpenInImageViewerDlg(...) end local OpenInMultiLineTextDlg = ChoGGi.ComFuncs.OpenInMultiLineTextDlg function OpenTextViewer(...) OpenInMultiLineTextDlg(...) end local OpenInExamineDlg = ChoGGi.ComFuncs.OpenInExamineDlg -- legacy (and used for console rules, so we can get around it spamming the log) function OpenExamine(...) OpenInExamineDlg(...) end function OpenExamineRet(...) return OpenInExamineDlg(...) end -- short n sweet ex = OpenExamine exr = OpenExamineRet function restart() quit("restart") end reboot = restart exit = quit mh = GetTerrainCursorObjSel -- returns selected obj under cursor mhc = GetTerrainCursorObj -- returns obj under cursor mc = GetPreciseCursorObj m = SelectionMouseObj c = GetTerrainCursor -- cursor position on map cs = terminal.GetMousePos -- cursor pos on screen s = false -- used to store SelectedObj function toboolean(str) if str == "true" then return true elseif str == "false" then return false end --~ return 0/0 end -- add some simple functions to the cheatmenu for moving it/getting pos function XShortcutsHost:SetPos(pt) -- doesn't "stick" self:SetBox(pt:x(), pt:y(), self.box:sizex(), self.box:sizey()) end function XShortcutsHost:GetPos() return ChoGGi_XWindow.GetPos(self, "idMenuBar") end function XShortcutsHost:GetSize() local GetSize = ChoGGi_XWindow.GetSize return GetSize(self, "idMenuBar") + GetSize(self, "idBottomContainer") end local function DiscoverTech(tech_id) UICity:SetTechDiscovered(tech_id) end DiscoverTech_Old = DiscoverTech -- for anyone still using it post-gagarin if not rawget(_G, "DiscoverTech") then _G.DiscoverTech = DiscoverTech end -- seems like a useful func to have if not rawget(Colonist, "HasTrait") then function Colonist:HasTrait(trait) if self.traits[trait] then return true end end end
--[[ /*===========================================================================* * Arch Engine - "Testers/graphicsConfig.lua" * * * * This is a tester script. It's purpose is to test some functionalities, * * thus should be removed from releases. * * Expect some hard coded, bizarre stuff. You've been warned ;) * * * * Marcelo de Matos Menezes - marcelodmmenezes@gmail.com * * Created: 26/05/2018 * * Last Modified: 26/05/2018 * *===========================================================================*/ ]] depth_test = true face_culling = true blending = true --clear_color = { 0.05, 0.08, 0.07, 1.0 } clear_color = { 1.0, 1.0, 1.0, 1.0 } --clear_color = { 0.0, 0.0, 0.0, 1.0 } view_port = { 0, 0, 800, 600 } --view_port = { 0, 0, 1920, 1080 } fov = 45.0 active_camera = -1
return function (connection, req, args) dofile('httpserver-header.lc')(connection, 200, 'html') --define robot dance steps --F=move forward, B=move backward, L=turn left, R=turn right, S=stop local steps = 'FFSSFFRSRFFSFFSSBBSSBBSSBBSSBBSSFFSSFFSSFFSSFFLSLBBS' --Tango local curStepIdx = 1 --1=GPIO5, 2=GPIO4, 3=GPIO0, 4=GPIO2, 5=GPIO14, 6=GPIO12, --7=GPIO13, 8=GPIO15, 9=GPIO3, 10=GPIO1, 11=GPIO9, 12=GPIO10 local leftpwm, leftduty, leftpin1, leftpin2 = 1, 818, 2, 4 --GPIO5, 80%, GPIO4, GPIO2 local rightpwm,rightduty, rightpin1, rightpin2 = 5, 717, 6, 7 --GPIO14, 70%, GPIO12, GPIO13 -- timer id(0-6), interval in ms local tmrId, tmrMs = 4, 800 -- init motors pwm.setup(leftpwm, 500, leftduty) pwm.start(leftpwm) gpio.mode(leftpin1, gpio.OUTPUT) gpio.mode(leftpin2, gpio.OUTPUT) pwm.setup(rightpwm, 500, rightduty) pwm.start(rightpwm) gpio.mode(rightpin1, gpio.OUTPUT) gpio.mode(rightpin2, gpio.OUTPUT) --run step every tmrMs tmr.alarm(tmrId, tmrMs, tmr.ALARM_SEMI, function() local curStep = string.sub(steps, curStepIdx, curStepIdx) if ((curStep ~= nil) and (curStep ~= '')) then if (curStep == 'F') then gpio.write(leftpin1, gpio.LOW) gpio.write(leftpin2, gpio.HIGH) gpio.write(rightpin1, gpio.LOW) gpio.write(rightpin2, gpio.HIGH) elseif (curStep == 'B') then gpio.write(leftpin1, gpio.HIGH) gpio.write(leftpin2, gpio.LOW) gpio.write(rightpin1, gpio.HIGH) gpio.write(rightpin2, gpio.LOW) elseif (curStep == 'L') then gpio.write(leftpin1, gpio.LOW) gpio.write(leftpin2, gpio.HIGH) gpio.write(rightpin1, gpio.HIGH) gpio.write(rightpin2, gpio.LOW) elseif (curStep == 'R') then gpio.write(leftpin1, gpio.HIGH) gpio.write(leftpin2, gpio.LOW) gpio.write(rightpin1, gpio.LOW) gpio.write(rightpin2, gpio.HIGH) elseif (curStep == 'S') then gpio.write(leftpin1, gpio.LOW) gpio.write(leftpin2, gpio.LOW) gpio.write(rightpin1, gpio.LOW) gpio.write(rightpin2, gpio.LOW) end curStepIdx = curStepIdx + 1 tmr.start(tmrId) else pwm.stop(leftpwm) gpio.write(leftpin1, gpio.LOW) gpio.write(leftpin2, gpio.LOW) pwm.stop(rightpwm) gpio.write(rightpin1, gpio.LOW) gpio.write(rightpin2, gpio.LOW) tmr.unregister(tmrId) end end) connection:send([===[<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>robot.lua</title> </head> <body> <h1>Running!</h1> </body> </html>]===]) end
-- Show off the template row layout return function(ui) if ui:windowBegin('Template Layout', 200, 100, 300, 200, 'title', 'border', 'movable', 'scalable') then x, y, width, height = ui:windowGetContentRegion() ui:layoutRow('dynamic', 40, 1) ui:label('Scale me!'); ui:layoutTemplateBegin(height - 40) ui:layoutTemplatePush('static', 75) ui:layoutTemplatePush('dynamic') ui:layoutTemplatePush('variable', 75) ui:layoutTemplateEnd() ui:button(nil, '#ff0000') ui:button(nil, '#00ff00') ui:button(nil, '#0000ff') end ui:windowEnd() end
--[[ Swaggy Jenkins Jenkins API clients generated from Swagger / Open API specification The version of the OpenAPI document: 1.1.2-pre.0 Contact: blah@cliffano.com Generated by: https://openapi-generator.tech ]] -- extension_class_container_impl1map class local extension_class_container_impl1map = {} local extension_class_container_impl1map_mt = { __name = "extension_class_container_impl1map"; __index = extension_class_container_impl1map; } local function cast_extension_class_container_impl1map(t) return setmetatable(t, extension_class_container_impl1map_mt) end local function new_extension_class_container_impl1map(io_jenkins_blueocean_service_embedded_rest_pipeline_impl, io_jenkins_blueocean_service_embedded_rest_multi_branch_pipeline_impl, _class) return cast_extension_class_container_impl1map({ ["io.jenkins.blueocean.service.embedded.rest.PipelineImpl"] = io_jenkins_blueocean_service_embedded_rest_pipeline_impl; ["io.jenkins.blueocean.service.embedded.rest.MultiBranchPipelineImpl"] = io_jenkins_blueocean_service_embedded_rest_multi_branch_pipeline_impl; ["_class"] = _class; }) end return { cast = cast_extension_class_container_impl1map; new = new_extension_class_container_impl1map; }
minetest.register_alias("lv_cable", "technic:lv_cable") minetest.register_craft({ output = 'technic:lv_cable 6', recipe = { {'default:paper', 'default:paper', 'default:paper'}, {'default:copper_ingot', 'default:copper_ingot', 'default:copper_ingot'}, {'default:paper', 'default:paper', 'default:paper'}, } }) technic.register_cable("LV", 2/16) if minetest.get_modpath("digilines") then local S = technic.getter if minetest.get_modpath("digistuff") then minetest.register_craft({ output = 'technic:lv_digi_cable 1', type = "shapeless", recipe = {'digistuff:digimese', 'technic:lv_cable'} }) else minetest.register_craft({ output = 'technic:lv_digi_cable 1', recipe = { {'digilines:wire_std_00000000', 'digilines:wire_std_00000000', 'digilines:wire_std_00000000'}, {'digilines:wire_std_00000000', 'technic:lv_cable', 'digilines:wire_std_00000000'}, {'digilines:wire_std_00000000', 'digilines:wire_std_00000000', 'digilines:wire_std_00000000'}, } }) end technic.register_cable("LV", 2/16, S("LV Cable (digiline)"), "_digi", { digiline = { wire = { rules = { {x = 1, y = 0, z = 0}, {x =-1, y = 0, z = 0}, {x = 0, y = 1, z = 0}, {x = 0, y =-1, z = 0}, {x = 0, y = 0, z = 1}, {x = 0, y = 0, z =-1} } } } }) end
local opts = { server = {}, tools = { autoSetHints = true, hover_actions = { border = { { "\226\149\173", "FloatBorder" }, { "\226\148\128", "FloatBorder" }, { "\226\149\174", "FloatBorder" }, { "\226\148\130", "FloatBorder" }, { "\226\149\175", "FloatBorder" }, { "\226\148\128", "FloatBorder" }, { "\226\149\176", "FloatBorder" }, { "\226\148\130", "FloatBorder" }, }, }, hover_with_actions = true, inlay_hints = { max_len_align = false, max_len_align_padding = 1, other_hints_prefix = "=>", parameter_hints_prefix = "<-", right_align = false, right_align_padding = 7, show_parameter_hints = true, }, runnables = { use_telescope = false }, }, } require("rust-tools").setup(opts)
--[[ BEGIN CONFIGURATION ]]-- SEARCH_STEP_FRAMES = 30 -- Each step forward lasts this many frames. SEARCH_FORWARD_FRAMES = 60 -- When you actually execute a move, play for this many frames. This should stay at 30 to keep -- the framerate of image capture constant. PLAY_FRAMES = 30 STEERING_BINS = 11 -- The steering is discretized into this many bins. SEARCH_DEPTH = 1 -- The depth to search. BENDING_ENERGY_WINDOW = 4 PROGRESS_WEIGHT = 1 VELOCITY_WEIGHT = 0.1 BENDING_ENERGY_WEIGHT = 0 USE_MAPPING = true --[[ END CONFIGURATION ]]-- local chunk_args = {...} local FRAMES_TO_SEARCH = chunk_args[1] local RECORDING_FOLDER, RECORDING_START_FRAME = chunk_args[2], chunk_args[3] if FRAMES_TO_SEARCH ~= nil then print("Searching for " .. FRAMES_TO_SEARCH .. " frames.") end local util = require("util") -- The save state will be temporarily stored in this file when performing a search. local STATE_FILE = util.getTMPDir() .. '\\root.state' local mode = util.readMode() local course = util.readCourse() if RECORDING_FOLDER == nil then -- Ensure that there is a recoridngs folder, as well as a subfolder for the current track-mode combination. os.execute('mkdir recordings\\' .. course .. '\\' .. mode) -- Generate a recording id. local RECORDING_ID = util.generateUUID() print("Recording ID:", RECORDING_ID) -- Create a folder for this recording. RECORDING_FOLDER = 'recordings\\' .. course .. '\\' .. mode .. '\\search-' .. RECORDING_ID os.execute('mkdir ' .. RECORDING_FOLDER) -- Create an empty steering file that will be appended to. os.execute('type nul > ' .. RECORDING_FOLDER .. '\\steering.txt') end client.unpause() client.speedmode(800) function onexit() if steering_file ~= nil then steering_file:close() end client.pause() savestate.load(STATE_FILE) client.speedmode(100) client.unpause_av() end local exit_guid = event.onexit(onexit) function eval_actions(actions, actions_history) -- Calculate bending energy, which is a measure of the smoothness of the trajectory. local bending_energy, window = 0, {} for _, action in ipairs(actions) do if #window < BENDING_ENERGY_WINDOW then table.insert(window, 1, action) end end for _, action in ipairs(actions_history) do if #window < BENDING_ENERGY_WINDOW then table.insert(window, 1, action) end end bending_energy = util.bendingEnergy(window) savestate.load(STATE_FILE) local start_progress = util.readProgress() for _, action in ipairs(actions) do for i=1, SEARCH_STEP_FRAMES do joypad.set({["P1 A"] = true}) joypad.setanalog({["P1 X Axis"] = util.convertSteerToJoystick(action, USE_MAPPING)}) emu.frameadvance() end end for i=1, SEARCH_FORWARD_FRAMES do joypad.set({["P1 A"] = true}) joypad.setanalog({["P1 X Axis"] = 0}) emu.frameadvance() end local end_progress = util.readProgress() if end_progress > start_progress then return PROGRESS_WEIGHT * util.readProgress() + VELOCITY_WEIGHT * util.readVelocity() - BENDING_ENERGY_WEIGHT * bending_energy else return PROGRESS_WEIGHT * (util.readProgress() - 3) end end function best_next_action(actions_so_far, actions_history) if #actions_so_far == SEARCH_DEPTH then return nil, eval_actions(actions_so_far, actions_history) end local best_action = 0 table.insert(actions_so_far, 0) local _, best_score = best_next_action(actions_so_far, actions_history) table.remove(actions_so_far) for action in util.linspace(-1, 1, STEERING_BINS) do if math.abs(action) > 1e-5 then table.insert(actions_so_far, action) local _, score = best_next_action(actions_so_far, actions_history) if score > best_score then best_score = score best_action = action end table.remove(actions_so_far) end end return best_action, best_score end local recording_frame = 1 if RECORDING_START_FRAME ~= nil then recording_frame = RECORDING_START_FRAME end local steering_file = io.open(RECORDING_FOLDER .. '\\steering.txt', 'a') local actions_history = {} while util.readProgress() < 3 do client.pause_av() start_time = os.time() savestate.save(STATE_FILE) action, score = best_next_action({}, actions_history) end_time = os.time() print("Action:", action, "Score:", score, "Time:", end_time - start_time) table.insert(actions_history, action) savestate.load(STATE_FILE) client.screenshot(RECORDING_FOLDER .. '\\' .. recording_frame .. '.png') steering_file:write(action .. '\n') steering_file:flush() recording_frame = recording_frame + 1 local start_progress = util.readProgress() client.unpause_av() for i=1, PLAY_FRAMES do joypad.set({["P1 A"] = true}) joypad.setanalog({["P1 X Axis"] = util.convertSteerToJoystick(action, USE_MAPPING)}) emu.frameadvance() if FRAMES_TO_SEARCH ~= nil then FRAMES_TO_SEARCH = FRAMES_TO_SEARCH - 1 end end local end_progress = util.readProgress() if end_progress < start_progress then print("Search AI is stuck!") break end -- If we've finished the amount of frames we were asked to search, then stop. if FRAMES_TO_SEARCH ~= nil and FRAMES_TO_SEARCH == 0 then break end end savestate.save(STATE_FILE) onexit() event.unregisterbyid(exit_guid) return recording_frame
local CollisionUtil = {} local self = CollisionUtil local sqrt = math.sqrt local min = math.min local max = math.max local pow = math.pow local dist = function(x1,y1, x2,y2) local dx, dy = x1-x2, y1-y2 return sqrt((dx*dx)+(dy*dy)) end local clamp = function(v, a, b) return max(a, min(b, v)) end -- Point function CollisionUtil.pointPoint(x1,y1, x2,y2) return x1 == x2 and y1 == y2 end function CollisionUtil.pointCircle(px,py, cx,cy,cr) return dist(px,py, cx,cy) <= cr end function CollisionUtil.pointRect(px,py, rx,ry,rw,rh) return px >= rx and px <= rx+rw and py >= ry and py <= ry+rh end function CollisionUtil.pointLine(px,py, x1,y1,x2,y2, precision) return self.linePoint(x1,y1,x2,y2, px,py, precision) end function CollisionUtil.pointPolygon(px,py, poly) return self.polygonPoint(poly, px,py) end -- Circle function CollisionUtil.circlePoint(cx,cy,cr, px,py) return self.pointCircle(px,py, cx,cy,cr) end function CollisionUtil.circleCircle(x1,y1,r1, x2,y2,r2) return dist(x1,y1, x2,y2) <= r1+r2 end function CollisionUtil.circleRect(cx,cy,cr, rx,ry,rw,rh) return self.rectCircle(rx,ry,rw,rh, cx,cy,cr) end function CollisionUtil.circleLine(cx,cy,cr, x1,y1,x2,y2) return self.lineCircle(x1,y1,x2,y2, cx,cy,cr) end function CollisionUtil.circlePolygon(cx,cy,cr, poly) return self.polygonCircle(poly, cx,cy,cr) end -- Rectangle function CollisionUtil.rectPoint(rx,ry,rw,rh, px,py) return self.pointRect(px,py, rx,ry,rw,rh) end function CollisionUtil.rectCircle(rx,ry,rw,rh, cx,cy,cr) local ex, ey = clamp(cx, rx, rx+rw), clamp(cy, ry, ry+rh) return dist(cx,cy, ex,ey) <= cr end function CollisionUtil.rectRect(x1,y1,w1,h1, x2,y2,w2,h2) return x1 + w1 >= x2 and x1 <= x2 + w2 and y1 + h1 >= y2 and y1 <= y2 + h2 end function CollisionUtil.rectLine(rx,ry,rw,rh, x1,y1,x2,y2) return self.lineRect(x1,y1,x2,y2, rx,ry,rw,rh) end function CollisionUtil.rectPolygon(rx,ry,rw,rh, poly) return self.polygonRect(poly, rx,ry,rw,rh) end -- Line function CollisionUtil.linePoint(x1,y1,x2,y2, px,py, precision) local d1 = dist(px,py, x1,y1) local d2 = dist(px,py, x2,y2) local len = dist(x1,y1, x2,y2) local buffer = precision or 0.01 return d1+d2 >= len-buffer and d1+d2 <= len+buffer end function CollisionUtil.lineCircle(x1,y1,x2,y2, cx,cy,cr) local inside1 = self.pointCircle(x1,y1, cx,cy,cr) local inside2 = self.pointCircle(x2,y2, cx,cy,cr) if inside1 or inside2 then return true end local len = dist(x1,y1, x2,y2) local dot = (((cx-x1)*(x2-x1)) + ((cy-y1)*(y2-y1))) / pow(len,2) local closest_x = x1 + (dot * (x2-x1)) local closest_y = y1 + (dot * (y2-y1)) if not self.linePoint(x1,y1,x2,y2, closest_x,closest_y) then return false end return dist(closest_x,closest_y, cx,cy) <= cr end function CollisionUtil.lineRect(x1,y1,x2,y2, rx,ry,rw,rh) return self.lineLine(x1,y1,x2,y2, rx,ry,rx,ry+rh) or self.lineLine(x1,y1,x2,y2, rx+rw,ry,rx+rw,ry+rh) or self.lineLine(x1,y1,x2,y2, rx,ry,rx+rw,ry) or self.lineLine(x1,y1,x2,y2, rx,ry+rh,rx+rw,ry+rh) or self.pointRect(x1,y1, rx,ry,rw,rh) end function CollisionUtil.lineLine(x1,y1,x2,y2, x3,y3,x4,y4) local ua = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)) local ub = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1)) return ua >= 0 and ua <= 1 and ub >= 0 and ub <= 1 end function CollisionUtil.linePolygon(x1,y1,x2,y2, poly) return self.polygonLine(poly, x1,y1,x2,y2) end -- Polygon function CollisionUtil.polygonPoint(poly, px,py) local collided = false for i = 1, #poly do local vc = poly[i] local vn = poly[(i % #poly) + 1] if ((vc[2] > py) ~= (vn[2] > py)) and (px < (vn[1]-vc[1]) * (py-vc[2]) / (vn[2]-vc[2]) + vc[1]) then collided = not collided end end return collided end function CollisionUtil.polygonCircle(poly, cx,cy,cr) local collided = false for i = 1, #poly do local vc = poly[i] local vn = poly[(i % #poly) + 1] if self.lineCircle(vc[1],vc[2],vn[1],vn[2], cx,cy,cr) then return true end if ((vc[2] > cy) ~= (vn[2] > cy)) and (cx < (vn[1]-vc[1]) * (cy-vc[2]) / (vn[2]-vc[2]) + vc[1]) then collided = not collided end end return collided end function CollisionUtil.polygonRect(poly, rx,ry,rw,rh) local collided = false for i = 1, #poly do local vc = poly[i] local vn = poly[(i % #poly) + 1] if self.lineRect(vc[1],vc[2],vn[1],vn[2], rx,ry,rw,rh) then return true end if ((vc[2] > ry) ~= (vn[2] > ry)) and (rx < (vn[1]-vc[1]) * (ry-vc[2]) / (vn[2]-vc[2]) + vc[1]) then collided = not collided end end return collided end function CollisionUtil.polygonLine(poly, x1,y1,x2,y2) local collided = false for i = 1, #poly do local vc = poly[i] local vn = poly[(i % #poly) + 1] if self.lineLine(vc[1],vc[2],vn[1],vn[2], x1,y1,x2,y2) then return true end if ((vc[2] > y1) ~= (vn[2] > y1)) and (x1 < (vn[1]-vc[1]) * (y1-vc[2]) / (vn[2]-vc[2]) + vc[1]) then collided = not collided end end return collided end function CollisionUtil.polygonPolygon(poly1, poly2) for i = 1, #poly1 do local vc = poly1[i] local vn = poly1[(i % #poly1) + 1] if self.polygonLine(poly2, vc[1],vc[2],vn[1],vn[2]) then return true end end return (#poly1>0 and self.polygonPoint(poly2, poly1[1][1],poly1[1][2])) or (#poly2>0 and self.polygonPoint(poly1, poly2[1][1],poly2[1][2])) end return CollisionUtil
client_script 'playertools_client.lua'
local gl = require("galaxyline") local gls = gl.section gl.short_line_list = {" "} -- keeping this table { } as empty will show inactive statuslines local colors = { bg = "#2e3440", fg = "#e5e9f0", green = "#A3BE8C", red = "#bf616a", lightbg = "#242831", blue = "#81a1c1", yellow = "#ebcb8b", cyan = "#8fbcbb", magenta = "#b48ead", grey = "#3b4252" } gls.left[1] = { icon_left = { provider = function() return "" end, highlight = {colors.blue, colors.bg} } } gls.left[2] = { statusIcon = { provider = function() return " ﮂ " end, highlight = {colors.bg, colors.blue}, separator = " ", separator_highlight = {colors.blue, colors.lightbg} } } gls.left[3] = { viMode_icon = { provider = function() return "" end, highlight = {colors.fg, colors.lightbg}, separator = " ", separator_highlight = {colors.cyan, colors.lightbg} } } gls.left[4] = { ViMode = { provider = function() local alias = { n = "Normal", i = "Insert", c = "Command", V = "Visual", [""] = "Visual", v = "Visual", R = "Replace" } local current_Mode = alias[vim.fn.mode()] if current_Mode == nil then return " Terminal " else return " " .. current_Mode .. " " end end, highlight = {colors.fg, colors.lightbg}, separator = " ", separator_highlight = {colors.lightbg, colors.bg} } } local checkwidth = function() local squeeze_width = vim.fn.winwidth(0) / 2 if squeeze_width > 30 then return true end return false end gls.left[5] = { DiffAdd = { provider = "DiffAdd", condition = checkwidth, icon = "  ", highlight = {colors.fg, colors.bg} } } gls.left[6] = { DiffModified = { provider = "DiffModified", condition = checkwidth, icon = "  ", highlight = {colors.magenta, colors.bg} } } gls.left[7] = { DiffRemove = { provider = "DiffRemove", condition = checkwidth, icon = "  ", highlight = {colors.magenta, colors.bg} } } gls.left[8] = { DiagnosticError = { provider = "DiagnosticError", icon = "  ", highlight = {colors.magenta, colors.bg} } } gls.left[9] = { DiagnosticWarn = { provider = "DiagnosticWarn", icon = "  ", highlight = {colors.yellow, colors.bg} } } gls.right[1] = { GitIcon = { provider = function() return " " end, condition = require("galaxyline.provider_vcs").check_git_workspace, highlight = {colors.magenta, colors.lightbg}, separator = "", separator_highlight = {colors.lightbg, colors.bg} } } gls.right[2] = { GitBranch = { provider = "GitBranch", condition = require("galaxyline.provider_vcs").check_git_workspace, highlight = {colors.magenta, colors.lightbg} } } gls.right[3] = { FileIcon = { provider = "FileIcon", condition = buffer_not_empty, highlight = {colors.bg, colors.cyan}, separator = " ", separator_highlight = {colors.cyan, colors.lightbg} } } gls.right[4] = { FileName = { provider = {"FileName"}, condition = buffer_not_empty, highlight = {colors.cyan, colors.lightbg}, separator = "", separator_highlight = {colors.lightbg, colors.bg} } } gls.right[5] = { time_icon = { provider = function() return " " end, separator = "", separator_highlight = {colors.green, colors.bg}, highlight = {colors.lightbg, colors.green} } } gls.right[6] = { time = { provider = function() return " " .. os.date("%H:%M") .. " " end, highlight = {colors.green, colors.lightbg} } } gls.right[7] = { icon_right = { provider = function() return " " end, highlight = {colors.lightbg, colors.bg} } }
-- _.find.lua -- -- Iterates over elements of collection, returning the first element -- predicate returns truthy for. The predicate is bound to selfArg and -- invoked with three arguments: (value, index|key, collection). -- @usage _.print(_.find({{a = 1}, {a = 2}, {a = 3}, {a = 2}, {a = 3}}, function(v) -- return v.a == 3 -- end)) -- --> {[a]=3} -- -- @param collection The collection to search. (table|string) -- @param predicate The function invoked per iteration -- @param selfArg The self binding of predicate. _.find = function (collection, predicate, selfArg) for k, v in _.iter(collection) do if callIteratee(predicate, selfArg, v, k, collection) then return v end end end
--------------------------------------------------------------------------------------------------- -- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/2379 --------------------------------------------------------------------------------------------------- -- Description: Check SDL is able to ignore notification from HMI after cut off of fake parameters -- and notification becomes invalid -- Scenario: notification that SDL should use internally -- -- Steps: -- 1. HMI sends notification with fake parameter -- SDL does: -- - cut off fake parameters -- - check whether notification is valid -- - ignore notification in case if it's invalid --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require("user_modules/sequences/actions") --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Functions ]] local function activateApp() local params = { appID = "123", --invalid data type fakeParam = "123" } common.getHMIConnection():SendNotification("BasicCommunication.OnAppActivated", params) common.getMobileSession():ExpectNotification("OnHMIStatus") :Times(0) common.getHMIConnection():ExpectRequest("BasicCommunication.ActivateApp") :Times(0) end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect regular mobile, start Session", common.start) runner.Step("Register App", common.registerAppWOPTU) runner.Title("Test") runner.Step("HMI sends OnAppActivated", activateApp) runner.Title("Postconditions") runner.Step("Stop SDL, restore SDL settings and PPT", common.postconditions)
--[[---------------------------------------------------------------------------- Implementation of the Gallery Remote Protocol. Copyright (C) 2007-2009 Arnaud Mouronval <arnaud.mouronval@yahoo.com> Copyright (C) 2007 Moritz Post <mail@moritzpost.de> Released under the GNU GPL. -----------------------------------------------------------------------------]]-- require 'TableUtils' require 'StringUtils' -- Lightroom SDK local LrView = import 'LrView' local LrFunctionContext = import 'LrFunctionContext' local LrDialogs = import 'LrDialogs' local LrLogger = import 'LrLogger' local LrHttp = import 'LrHttp' local LrTasks = import 'LrTasks' local LrStringUtils = import 'LrStringUtils' local LrPathUtils = import 'LrPathUtils' local prefs = import 'LrPrefs'.prefsForPlugin() local bind = LrView.bind local share = LrView.share -- Setup logger local log = LrLogger( 'LR2Gallery' ) GalleryRemoteProtocol = {} ---------------------------------------------------------------------------------- -- Parses the gallery responds by creating a table -- and mapping each gallery data set (key=value) to a table -- by inserting a { key=galleryKey, value=galleryValue } local function parseGalleryResponse( raw ) log:trace("Calling GalleryRemoteProtocol.parseGalleryResponse( Raw Message )") log:debug("Raw Message:\n"..raw) local flag = "#__GR2PROTO__" local result = {} local parsing = false local flagJustFound = false local lines = string.split( raw, "[^\n]+" ) -- loop over each line for i,v in ipairs(lines) do if string.sub( v, -13, -1 ) == flag then parsing = true flagJustFound = true end if parsing and not flagJustFound then -- create entry for result table local splitted = string.split( lines[i], "[^=]+" ) table.insert( result, { key = splitted[1], value = splitted[2] or "" } ) end flagJustFound = false end return result end -- Get a value from the parsed response table local function getResponse( responseTable, key ) log:trace("Calling GalleryRemoteProtocol.getResponse( Key: "..key.." )") for i,v in ipairs(responseTable) do if responseTable[i].key == key then return responseTable[i].value end end return nil end -- Returns the proper URL for Gallery function GalleryRemoteProtocol.getGalleryURL( server ) if server ~= nil then log:trace("Calling GalleryRemoteProtocol.getGalleryURL( "..server.." )") else log:trace("Calling GalleryRemoteProtocol.getGalleryURL( nil )") end -- the url to construct local url = "" server = LrStringUtils.trimWhitespace( server ) -- add the http:// if required if string.sub( server, 1, 7 ) ~= 'http://' then url = 'http://' end -- add the trailing / if required if string.sub( server, -1 ) ~= '/' then url = url..server..'/' else url = url..server end return url end -- Returns the proper URL for the Gallery Remote controller function GalleryRemoteProtocol.getGalleryRemoteURL( server ) if server ~= nil then log:trace("Calling GalleryRemoteProtocol.getGalleryRemoteURL( "..server.." )") else log:trace("Calling GalleryRemoteProtocol.getGalleryRemoteURL( nil )") end -- the url to construct local url = "" if GalleryRemoteProtocol.galleryVersion == '1' then -- Complete the URL url = url..GalleryRemoteProtocol.getGalleryURL( server ).."gallery_remote2.php" else -- Complete the URL url = url..GalleryRemoteProtocol.getGalleryURL( server ).."main.php?g2_controller=remote:GalleryRemote" end return url end -- Check the remote server by sending a no-op cmd to the remote Gallery function GalleryRemoteProtocol.isRemoteProtocolEnabled(serverId) log:trace("Calling GalleryRemoteProtocol.isRemoteProtocolEnabled( "..prefs.serverTable[serverId].label.." )") -- get server local server = prefs.serverTable[serverId].server -- check the current version of Gallery if prefs.serverTable[serverId].version ~= nil then GalleryRemoteProtocol.galleryVersion = prefs.serverTable[serverId].version else GalleryRemoteProtocol.galleryVersion = '2' end local serverStatus = '0' if GalleryRemoteProtocol.galleryVersion ~= '1' then -- construct operation local operation = { { name='g2_form[cmd]', value='no-op' } } -- send POST request to the gallery server local response, debug = LrHttp.postMultipart( GalleryRemoteProtocol.getGalleryRemoteURL(server), operation ) -- parse reponse into easy to digest table format responseTable = parseGalleryResponse( response ) -- get server response status serverStatus = getResponse( responseTable, 'status' ) -- show error when the connection could not be established if serverStatus ~= '0' then LrDialogs.message(LOC "$$$/GalleryUpload/Dialog/NoConnectionPossible/Message=Could not establish a connection to the remote Gallery.", LOC "$$$/GalleryUpload/Dialog/NoConnectionPossible/Info=Also make sure the remote module is enabled in the Gallery installation.", "critical") end end return serverStatus end -- Login to the remote Gallery function GalleryRemoteProtocol.login(serverId) log:trace("Calling GalleryRemoteProtocol.login( "..prefs.serverTable[serverId].label.." )") -- reset the authentication token GalleryRemoteProtocol.authToken = "" -- get server local server = prefs.serverTable[serverId].server local response, debug if GalleryRemoteProtocol.galleryVersion == '1' then -- send GET request to the gallery server response, debug = LrHttp.get( GalleryRemoteProtocol.getGalleryRemoteURL(server).."?cmd=login&protocol_version=2.0&uname="..prefs.serverTable[serverId].username.."&password="..prefs.serverTable[serverId].password ) else -- construct operation local operation = { { name='g2_form[cmd]', value='login' }, { name='g2_form[protocol_version]', value='2.0' }, { name='g2_form[uname]', value=prefs.serverTable[serverId].username }, { name='g2_form[password]', value=prefs.serverTable[serverId].password } } -- send POST request to the gallery server response, debug = LrHttp.postMultipart( GalleryRemoteProtocol.getGalleryRemoteURL(server), operation ) end -- parse reponse into easy to digest table format responseTable = parseGalleryResponse( response ) -- get server response status local serverStatus = getResponse( responseTable, 'status' ) log:debug("Request Status: "..serverStatus) -- show error when the connection could not be established if serverStatus ~= '0' then if serverStatus == '201' then LrDialogs.message(LOC ("$$$/GalleryUpload/Dialog/201Error/Message=Could not log in to the remote server '^1'", server), LOC "$$$/GalleryUpload/Dialog/201Error/Info=The login and/or password are incorrect.", "critical") elseif serverStatus == '202' then LrDialogs.message(LOC ("$$$/GalleryUpload/Dialog/202Error/Message=Could not log in to the remote server '^1'", server), LOC "$$$/GalleryUpload/Dialog/202Error/Info=The login and/or password are empty.", "critical") else gallery:error ("Authentication: Unmanaged error code "..serverStatus.." from the remote server") LrDialogs.message(LOC ("$$$/GalleryUpload/Dialog/LoginDetailsFaulty/Message=Could not log in to the remote server '^1'", server), LOC "$$$/GalleryUpload/Dialog/LoginDetailsFaulty/Info=Make sure the login details and the server url are valid.", "critical") end else if GalleryRemoteProtocol.galleryVersion ~= '1' then -- store current auth_token GalleryRemoteProtocol.authToken = getResponse( responseTable, 'auth_token' ) log:debug("Authentication Token: "..GalleryRemoteProtocol.authToken) end end return serverStatus end -- Get the list of albums from the server function GalleryRemoteProtocol.getAlbumList(serverId) log:trace("Calling GalleryRemoteProtocol.getAlbumList( "..prefs.serverTable[serverId].label.." )") -- get server local server = prefs.serverTable[serverId].server local response, debug if GalleryRemoteProtocol.galleryVersion == '1' then response, debug = LrHttp.get( GalleryRemoteProtocol.getGalleryRemoteURL(server).."?cmd=fetch-albums-prune&protocol_version=2.2&no_perms=yes" ) else -- construct operation local operation = { { name='g2_form[cmd]', value='fetch-albums-prune' }, { name='g2_form[protocol_version]', value='2.2' }, { name='g2_form[no_perms]', value='yes' }, { name='g2_authToken', value=GalleryRemoteProtocol.authToken }, } -- send POST request to the gallery server response, debug = LrHttp.postMultipart( GalleryRemoteProtocol.getGalleryRemoteURL(server), operation ) end -- parse reponse into easy to digest table format responseTable = parseGalleryResponse( response ) -- get server response status local serverStatus = getResponse( responseTable, 'status' ) log:debug("Gallery Command Status: "..serverStatus) -- build a list (table) of nodes from the data local albumList = {} -- show error when the connection could not be established if serverStatus ~= '0' then LrDialogs.message(LOC ( "$$$/GalleryUpload/Dialog/CouldNotFetchAlbums/Message=Could not fetch the list of albums from the server '^1'", server ), LOC "$$$/GalleryUpload/Dialog/CouldNotFetchAlbums/Info=Make sure you have sufficient rights on the server.", "critical") else local albumCount = getResponse( responseTable, 'album_count' ) log:debug("Album Count: "..albumCount) -- create nodes for i = 1, albumCount do log:debug("inserting album \""..getResponse(responseTable, "album.name."..i).."\" to albumList") table.insert(albumList, { name = getResponse(responseTable, "album.name."..i), title = getResponse(responseTable, "album.title."..i), summary = getResponse(responseTable, "album.summary."..i), parent = getResponse(responseTable, "album.parent."..i), children = {} } ) end -- set children nodes for k,album in pairs(albumList) do log:debug("Looking for the parent album of album #"..k) -- find parent node for l,pAlbum in pairs(albumList) do log:debug("Checking if album \""..pAlbum.name.. "\" is a match") if pAlbum.name == album.parent then -- add the current node id to the parent node as a child table.insert(albumList[l].children, k) log:debug("inserting album #"..k.." as child of album \""..albumList[l].name.."\"") end end end end if GalleryRemoteProtocol.galleryVersion ~= '1' then -- store current auth_token GalleryRemoteProtocol.authToken = getResponse(responseTable, 'auth_token') end return serverStatus, albumList end -- Add a new album to the server function GalleryRemoteProtocol.addAlbum(serverId, parentAlbum, albumName, albumTitle, albumDescription) log:trace("Calling GalleryRemoteProtocol.addAlbum( "..prefs.serverTable[serverId].label..", "..parentAlbum..", "..albumName..", "..albumTitle..", "..albumDescription.." )") -- get server local server = prefs.serverTable[serverId].server local response, debug if GalleryRemoteProtocol.galleryVersion == '1' then response, debug = LrHttp.get( GalleryRemoteProtocol.getGalleryRemoteURL(server).."?cmd=new-album&protocol_version=2.1&set_albumName="..parentAlbum.."&newAlbumName="..albumName.."&newAlbumTitle="..albumTitle.."&newAlbumDesc="..albumDescription ) else -- construct operation local operation = { { name='g2_form[cmd]', value='new-album' }, { name='g2_form[protocol_version]', value='2.1' }, { name='g2_form[set_albumName]', value=parentAlbum }, { name='g2_form[newAlbumName]', value=albumName }, { name='g2_form[newAlbumTitle]', value=albumTitle }, { name='g2_form[newAlbumDesc]', value=albumDescription }, { name='g2_authToken', value=GalleryRemoteProtocol.authToken }, } -- send POST request to the gallery server response, debug = LrHttp.postMultipart( GalleryRemoteProtocol.getGalleryRemoteURL(server), operation ) end -- parse reponse into easy to digest table format responseTable = parseGalleryResponse( response ) -- get server response status local serverStatus = getResponse( responseTable, 'status' ) return serverStatus, getResponse( responseTable, 'album_name' ) end -- Upload file to Gallery function GalleryRemoteProtocol.uploadImage(serverId, album, imagePath, caption) log:trace("Calling GalleryRemoteProtocol.uploadImage( "..prefs.serverTable[serverId].label..", "..album..", "..imagePath..", "..caption.." )") -- get server local server = prefs.serverTable[serverId].server local filename = LrPathUtils.leafName( imagePath ) local response, debug, content if GalleryRemoteProtocol.galleryVersion == '1' then -- construct operation content = { { name='cmd', value='add-item' }, { name='protocol_version', value='2.0' }, { name='set_albumName', value=album }, { name='caption', value=caption }, { name='userfile_name', value=filename }, { name = 'userfile', fileName = filename, filePath = imagePath, contentType = 'multipart/form-data' } } else -- construct operation content = { { name='g2_form[cmd]', value='add-item' }, { name='g2_form[protocol_version]', value='2.0' }, { name='g2_form[set_albumName]', value=album }, { name='g2_form[caption]', value=caption }, { name='g2_form[force_filename]', value=filename }, { name='g2_authToken', value=GalleryRemoteProtocol.authToken }, { name = 'g2_userfile', fileName = filename, filePath = imagePath, contentType = 'multipart/form-data' } } end -- send POST request to the gallery server response, debug = LrHttp.postMultipart( GalleryRemoteProtocol.getGalleryRemoteURL(server), content ) -- parse reponse into easy to digest table format responseTable = parseGalleryResponse( response ) -- get server response status local serverStatus = getResponse( responseTable, 'status' ) return serverStatus end
local images = nil -- don't reload the images each time -- Import all of the cards, give them attributes. function importCards(client) -- Okay, lots of stuff here. -- We're constructing a cards array with their image and value. -- We're also giving each card a "charVal", which is a one-character representation of the card being sent. if not images then importImages(client) end local cards = {} for i=1,12 do table.insert(cards,{}) for j=1,4 do table.insert(cards[i],{}) cards[i][j] = {image = images[i][j], value = 1, month = i, number = j, charVal = string.char(((i-1)*4)+j+64), x = 0, y = 0, size = 1, tweens = {}, canBeMatched = false} end end -- Special case, dammit November cards[11][3].value = 5 -- Most of the [2] cards are Ribbons. for i=1,12 do cards[i][2].value = 5 end -- Except for these three annoyances: cards[12][2].value = 1 cards[11][2].value = 10 cards[8][2].value = 10 -- Now, all of the cards are annoyances here! local bigcards = {1,3,8,11,12} for i=1,12 do cards[i][1].value = 10 end for i,j in pairs(bigcards) do cards[j][1].value = 20 end -- And finally, the Sake Cup, which is a world of its own. cards[9][1].value = 7 -- 7 is a good number. return cards end function importImage(client,i,j) local months = {"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"} if client then return love.graphics.newImage("assets/images/cards/"..months[i]..j..".png") else return "" end end function importImages(client) images = {} for i=1,12 do table.insert(images,{}) for j=1,4 do images[i][j] = importImage(client, i, j) end end end
--[[----------------------------------------------------------------------------------------------------------------------- Play a sound -----------------------------------------------------------------------------------------------------------------------]]-- local PLUGIN = {} PLUGIN.Title = "Play" PLUGIN.Description = "Play a sound or repeat the last one played." PLUGIN.Author = "Overv" PLUGIN.ChatCommand = "play" PLUGIN.Usage = "[path=lastusedone]" PLUGIN.Privileges = { "Play sound" } function PLUGIN:Call( ply, args ) if ( ply:EV_HasPrivilege( "Play sound" ) ) then local sound = args[1] or self.LastSound if ( sound ) then if ( string.match( sound, "^[a-zA-Z0-9/]+.wav$" ) ) then if ( not file.Exists( "sound/" .. sound, "GAME" ) ) then evolve:Notify( ply, evolve.colors.red, "Sound \"" .. sound .. "\" not found!" ) return end end for _, pl in ipairs( player.GetAll() ) do pl:ConCommand( "play " .. sound ) end self.LastSound = sound else evolve:Notify( ply, evolve.colors.red, "No sound was specified yet!" ) end else evolve:Notify( ply, evolve.colors.red, evolve.constants.notallowed ) end end evolve:RegisterPlugin( PLUGIN )
return { tag = 'modules', summary = 'Provides information about the current operating system and platform.', description = [[ The `lovr.system` provides information about the current operating system, and platform, and hardware. ]] }
object_tangible_quest_must_debris_door = object_tangible_quest_shared_must_debris_door:new { } ObjectTemplates:addTemplate(object_tangible_quest_must_debris_door, "object/tangible/quest/must_debris_door.iff")
-- vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab: use "roman/golden-ratio"
local Path = require('plenary.path') require('cmake').setup({ cmake_executable = 'cmake', -- CMake executable to run. parameters_file = 'neovim.json', -- JSON file to store information about selected target, run arguments and build type. build_dir = tostring(Path:new('{cwd}', 'build', '{os}-{build_type}')), -- Build directory. The expressions `{cwd}`, `{os}` and `{build_type}` will be expanded with the corresponding text values. -- samples_path = tostring(script_path:parent():parent():parent() / 'samples'), -- Folder with samples. `samples` folder from the plugin directory is used by default. default_projects_path = tostring(Path:new(vim.loop.os_homedir(), 'Projects')), -- Default folder for creating project. configure_args = {'-D', 'CMAKE_EXPORT_COMPILE_COMMANDS=1'}, -- Default arguments that will be always passed at cmake configure step. By default tells cmake to generate `compile_commands.json`. build_args = {'-j8'}, -- Default arguments that will be always passed at cmake build step. on_build_output = nil, -- Callback which will be called on every line that is printed during build process. Accepts printed line as argument. quickfix_height = 10, -- Height of the opened quickfix. quickfix_only_on_error = false, -- Open quickfix window only if target build failed. dap_open_command = require('dap').repl.open, -- Command to run after starting DAP session. You can set it to `false` if you don't want to open anything or `require('dapui').open` if you are using https://github.com/rcarriga/nvim-dap-ui dap_configuration = { name = "Launch", type = "lldb", request = "launch", program = function() return vim.fn.input("Path to executable: ", vim.fn.getcwd() .. "/", "file") end, cwd = "${workspaceFolder}", stopOnEntry = false, args = {}, runInTerminal = false } })
local function reql_error_formatter(err) if type(err) ~= 'table' then return end if err.ReQLError then return err.message() end end local version = require('semver')(string.match(_VERSION, '%d+%.%d+')) describe('control', function() local r setup(function() assert:add_formatter(reql_error_formatter) r = require('rethinkdb') function r.run(query, ...) assert.is_table(query, ...) return assert.is_table(query.run(query.r.c)) end local reql_db = 'control' local reql_table = 'func' r.reql_db = r.reql.db(reql_db) r.reql_table = r.reql.table(reql_table) r.c = assert.is_table(r.connect()) r.run(r.reql.db_create(reql_db)).to_array() r.c.use(reql_db) r.run(r.reql.table_create(reql_table)).to_array() end) teardown(function() if r.c then r.run(r.reql_table.delete()).to_array() end r = nil assert:remove_formatter(reql_error_formatter) end) it('branch db', function() local cur = r.run(r.reql_db.branch(1, 2)) assert.is_nil(cur.to_array()) end) it('branch error', function() local cur = r.run(r.reql.branch(r.reql.error'a', 1, 2)) assert.is_nil(cur.to_array()) end) it('branch false', function() local cur = r.run(r.reql.branch(false, 1, 2)) assert.same({2}, assert.is_table(cur.to_array())) end) it('branch nil', function() local cur = r.run(assert.is_table(r.reql().branch(1, 2))) assert.same({2}, assert.is_table(cur.to_array())) end) it('branch num', function() local cur = r.run(r.reql.branch(1, 'c', false)) assert.same({'c'}, assert.is_table(cur.to_array())) end) it('branch table', function() local cur = r.run(r.reql_table.branch(1, 2)) assert.is_nil(cur.to_array()) end) it('branch true', function() local cur = r.run(r.reql.branch(true, 1, 2)) assert.same({1}, assert.is_table(cur.to_array())) end) it('do append', function() local cur = r.run(r.reql{0, 1, 2}.call(function(v) return v.append(3) end)) assert.same({{0, 1, 2, 3}}, assert.is_table(cur.to_array())) end) if version.major >= 5 and version.minor > 1 then it('do', function() local cur = r.run(r.reql.call(function() return 1 end)) assert.same({1}, assert.is_table(cur.to_array())) end) it('do add', function() local cur = r.run(r.reql.call(1, 2, function(x, y) return x.add(y) end)) assert.same({3}, assert.is_table(cur.to_array())) end) it('do extra arg', function() local cur = r.run(r.reql.call(1, function(x, y) return x + y end)) assert.is_nil(cur.to_array()) end) it('do missing arg', function() local cur = r.run(r.reql.call(1, 2, function(x) return x end)) assert.is_nil(cur.to_array()) end) end it('do mul', function() local cur = r.run(r.reql(1).call(function(v) return v.mul(2) end)) assert.same({2}, assert.is_table(cur.to_array())) end) it('do no args', function() local cur = r.run(r.reql.call()) assert.is_nil(cur.to_array()) end) it('do no func', function() local cur = r.run(r.reql.call(1)) assert.same({1}, assert.is_table(cur.to_array())) end) it('do no return', function() local cur = r.run(r.reql.call(1, function() end)) assert.is_not_nil(cur) end) it('do return nil', function() local cur = r.run(r.reql.call(1, function() return nil end)) assert.is_not_nil(cur) end) it('do str add num', function() local cur = r.run(r.reql'abc'.call(function(v) return v.add(3) end)) assert.is_nil(cur.to_array()) end) it('do str add str add num', function() local cur = r.run(r.reql'abc'.call(function(v) return v.add'def' end).add(3)) assert.is_nil(cur.to_array()) end) it('do str append', function() local cur = r.run(r.reql'abc'.call(function(v) return v.append(3) end)) assert.is_nil(cur.to_array()) end) it('error', function() local cur = r.run(r.reql.error'Hello World') assert.is_nil(cur.to_array()) end) it('js', function() local cur = r.run(r.reql.js'1 + 1') assert.same({2}, assert.is_table(cur.to_array())) end) it('js add add', function() local cur = r.run(r.reql.js'1 + 1; 2 + 2') assert.same({4}, assert.is_table(cur.to_array())) end) it('do js function add', function() local cur = r.run(r.reql.call(1, 2, r.reql.js'(function(a, b) { return a + b; })')) assert.same({3}, assert.is_table(cur.to_array())) end) it('do js function', function() local cur = r.run(r.reql.call(1, r.reql.js'(function(x) { return x + 1; })')) assert.same({2}, assert.is_table(cur.to_array())) end) it('do js function add str', function() local cur = r.run(r.reql.call('foo', r.reql.js'(function(x) { return x + "bar"; })')) assert.same({'foobar'}, assert.is_table(cur.to_array())) end) it('do js no timeout', function() local cur = r.run(r.reql.js('1 + 2', {timeout = 1.2})) assert.same({3}, assert.is_table(cur.to_array())) end) it('js function result', function() local cur = r.run(r.reql.js'(function() { return 1; })') assert.is_nil(cur.to_array()) end) it('js function no wrap', function() local cur = r.run(r.reql.js'function() { return 1; }') assert.is_nil(cur.to_array()) end) it('do js function missing arg', function() local cur = r.run(r.reql.call(1, 2, r.reql.js'(function(a) { return a; })')) assert.same({1}, assert.is_table(cur.to_array())) end) it('do js function extra arg', function() local cur = r.run(r.reql.call(1, 2, r.reql.js'(function(a, b, c) { return a; })')) assert.same({1}, assert.is_table(cur.to_array())) end) it('do js function return undefined', function() local cur = r.run(r.reql.call(1, 2, r.reql.js'(function(a, b, c) { return c; })')) assert.is_nil(cur.to_array()) end) it('filter js', function() local cur = r.run(r.reql.filter({1, 2, 3}, r.reql.js'(function(a) { return a >= 2; })')) assert.same({{2, 3}}, assert.is_table(cur.to_array())) end) it('map js', function() local cur = r.run(r.reql.map({1, 2, 3}, r.reql.js'(function(a) { return a + 1; })')) assert.same({{2, 3, 4}}, assert.is_table(cur.to_array())) end) it('map js constant', function() local cur = r.run(r.reql.map({1, 2, 3}, r.reql.js'1')) assert.is_nil(cur.to_array()) end) it('filter js undefined', function() local cur = r.run(r.reql.filter({1, 2, 3}, r.reql.js'(function(a) {})')) assert.is_nil(cur.to_array()) end) it('map constant', function() local cur = r.run(r.reql.map({1, 2, 3}, 1)) assert.is_nil(cur.to_array()) end) it('filter constant str', function() local cur = r.run(r.reql.filter({1, 2, 3}, 'foo')) assert.same({{1, 2, 3}}, assert.is_table(cur.to_array())) end) it('filter constant obj', function() local cur = r.run(r.reql.filter({1, 2, 3}, {})) assert.same({{1, 2, 3}}, assert.is_table(cur.to_array())) end) it('filter nil', function() local cur = r.run(r.reql.filter({1, 2, 3}, r.reql())) assert.same({{}}, assert.is_table(cur.to_array())) end) it('filter false', function() local cur = r.run(r.reql.filter({1, 2, 3}, false)) assert.same({{}}, assert.is_table(cur.to_array())) end) it('for each insert', function() local cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.insert({id = row}) end)) assert.same({{deleted = 0, replaced = 0, unchanged = 0, errors = 0, skipped = 0, inserted = 3}}, assert.is_table(cur.to_array())) assert.is_table(r.run(r.reql_table.delete()).to_array()) end) it('count for each insert', function() local cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.insert({id = row}) end)) assert.is_table(cur.to_array()) cur = r.run(r.reql_table.count()) assert.same({3}, assert.is_table(cur.to_array())) assert.is_table(r.run(r.reql_table.delete()).to_array()) end) it('for each update', function() local cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.insert({id = row}) end)) assert.is_table(cur.to_array()) cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.update({foo = row}) end)) assert.same({{deleted = 0, replaced = 9, unchanged = 0, errors = 0, skipped = 0, inserted = 0}}, assert.is_table(cur.to_array())) assert.is_table(r.run(r.reql_table.delete()).to_array()) end) it('order_by limit variants', function() local cur = r.run( r.reql.for_each( {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, function(row) return r.reql_table.insert({id = row}) end ) ) assert.is_equal(10, assert.is_table(cur.to_array())[1].inserted) cur = r.run(r.reql_table.limit(5)'id') assert.same(5, #assert.is_table(cur.to_array())) cur = r.run(r.reql_table.order_by(r.reql.desc('id'))'id') assert.same({{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}}, assert.is_table(cur.to_array())) cur = r.run(r.reql_table.limit(5).order_by(r.reql.desc('id'))'id') assert.same(5, #(assert.is_table(cur.to_array())[1])) cur = r.run(r.reql_table.order_by(r.reql.desc('id')).limit(5)'id') assert.same({{10, 9, 8, 7, 6}}, assert.is_table(cur.to_array())) assert.same({10}, assert.is_table(r.run(r.reql_table.delete()'deleted').to_array())) end) it('for each insert with duplicates', function() local cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.insert({id = row}) end)) assert.is_table(cur.to_array()) cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.update({foo = row}) end)) assert.is_table(cur.to_array()) cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return {r.reql_table.insert({id = row}), r.reql_table.insert({id = row * 10})} end)) local res = assert.is_table(cur.to_array()) assert.is_equal(3, res[1].errors) assert.is_equal(3, res[1].inserted) assert.is_table(r.run(r.reql_table.delete()).to_array()) end) it('for each update many', function() local cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.insert({id = row}) end)) assert.is_table(cur.to_array()) cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.update({foo = row}) end)) assert.is_table(cur.to_array()) cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return {r.reql_table.insert({id = row}), r.reql_table.insert({id = row * 10})} end)) assert.is_table(cur.to_array()) cur = r.run(r.reql.for_each({1, 2, 3}, function(row) return r.reql_table.update({foo = row}) end)) assert.same({{deleted = 0, replaced = 18, unchanged = 0, errors = 0, skipped = 0, inserted = 0}}, assert.is_table(cur.to_array())) assert.is_table(r.run(r.reql_table.delete()).to_array()) end) end)
--====================================================================-- -- dmc_corona/dmc_netstream.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Corona Library : Net Stream --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.4.0" --====================================================================-- --== DMC Corona Library Config --====================================================================-- --====================================================================-- --== Support Functions local Utils = {} -- make copying from dmc_utils easier function Utils.extend( fromTable, toTable ) function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end --====================================================================-- --== Configuration local dmc_lib_data -- boot dmc_corona with boot script or -- setup basic defaults if it doesn't exist -- if false == pcall( function() require( 'dmc_corona_boot' ) end ) then _G.__dmc_corona = { dmc_corona={}, } end dmc_lib_data = _G.__dmc_corona --====================================================================-- --== DMC NetStream --====================================================================-- --====================================================================-- --== Configuration dmc_lib_data.dmc_netstream = dmc_lib_data.dmc_netstream or {} local DMC_NETSTREAM_DEFAULTS = { debug_active=false, } local dmc_netstream_data = Utils.extend( dmc_lib_data.dmc_netstream, DMC_NETSTREAM_DEFAULTS ) --====================================================================-- --== Imports local UrlLib = require 'socket.url' local Objects = require 'lib.dmc_lua.lua_objects' local Patch = require 'dmc_patch' local Sockets = require 'dmc_sockets' local StatesMixModule = require 'dmc_states_mix' local Utils = require 'lib.dmc_lua.lua_utils' --====================================================================-- --== Setup, Constants Patch.addPatch( 'string-format' ) local ObjectBase = Objects.ObjectBase local StatesMix = StatesMixModule.StatesMix local tconcat = table.concat local tinsert = table.insert local type = type local pairs = pairs local NetStream -- forward local netstream_table = {} local DEFAULT_PORT = 80 local DEFAULT_SPORT = 443 --====================================================================-- --== Support Functions -- make up a generic request for the web server -- local function createNetStream( params ) -- print( "createNetStream" ) params = params or {} --==-- local ns = NetStream:new{ url = params.url, method = params.method, listener = params.listener, http_params = params.params } netstream_table[ ns ] = ns return ns end local function removeNetStream( netstream, event ) -- print( "removeNetStream" ) local ns = netstream_table[ netstream ] if ns then netstream_table[ netstream ] = nil ns:removeSelf() end end function createHttpRequest( params ) -- print( "NetStream:createHttpRequest") params = params or {} --==-- local http_params = params.http_params local req_t = { "%s %s HTTP/1.1" % { params.method, params.path }, "Host: %s" % params.host, } if type( http_params.headers ) == 'table' then for k,v in pairs( http_params.headers ) do tinsert( req_t, #req_t+1, "%s: %s" % { k, v } ) end end if http_params.body ~= nil then tinsert( req_t, #req_t+1, "" ) tinsert( req_t, #req_t+1, http_params.body ) end tinsert( req_t, #req_t+1, "\r\n" ) -- print( tconcat( req_t, "\r\n" ) ) return tconcat( req_t, "\r\n" ) end --====================================================================-- --== Net Stream Class --====================================================================-- NetStream = newClass( { ObjectBase, StatesMix }, { name="DMC NetStream" } ) --== Class Constants NetStream.VERSION = VERSION --== State Constants NetStream.STATE_CREATE = 'state_create' NetStream.STATE_NOT_CONNECTED = 'state_not_connected' NetStream.STATE_CONNECTING = 'state_connecting' NetStream.STATE_CONNECTED = 'state_connected' --== Event Constants NetStream.EVENT = 'dmc_netstream_event' NetStream.CONNECTING = 'netstream_connecting_event' NetStream.CONNECTED = 'netstream_connected_event' NetStream.DATA = 'netstream_data_event' NetStream.DISCONNECTED = 'netstream_disconnected_event' NetStream.ERROR = 'netstream_error_event' --======================================================-- -- Start: Setup Lua Objects function NetStream:__init__( params ) -- print( "NetStream:__init__", params ) params = params or {} StatesMix.__init__( self, params ) ObjectBase.__init__( self, params ) --==-- --== Create Properties ==-- self._url = params.url self._method = params.method or 'GET' self._listener = params.listener self._http_params = params.http_params or {} self._auto_connect = params.auto_connect ~= nil and params.auto_connect or true self._header_wait = false -- event listeners self._onConnect_f = nil self._onData_f = nil -- from URL self._host = "" self._port = 0 self._path = "" end function NetStream:__initComplete__() -- print( "NetStream:__initComplete__" ) ObjectBase.__initComplete__( self ) --==-- local url_parts = UrlLib.parse( self._url ) self._host = url_parts.host self._port = url_parts.port self._path = url_parts.path if self._port == nil or self._port == 0 then self._port = url_parts.scheme == 'https' and DEFAULT_SPORT or DEFAULT_PORT end if self._path == nil then self._path = '/' end self._onConnect_f=self:createCallback( self._onConnect_handler ) self._onData_f=self:createCallback( self._onData_handler ) self._sock = Sockets:create( Sockets.ATCP ) -- SSL secure socket self._sock.secure = url_parts.scheme == 'https' and true or false -- set first state and transition self:setState( self.STATE_CREATE ) -- delay so that event listeners can be setup by user -- in time to get events timer.performWithDelay( 1, function() self:gotoState( self.STATE_NOT_CONNECTED ) end ) end function NetStream:__undoInitComplete__() -- print( "NetStream:__undoInitComplete__" ) local o o = self._sock if o.removeSelf then o:removeSelf() end self._sock = nil --==-- ObjectBase.__undoInitComplete__( self ) end -- END: Setup Lua Objects --======================================================-- --====================================================================-- --== Public Methods function NetStream:connect() -- print( "NetStream:connect" ) if self:getState() == self.NOT_CONNECTED then self:gotoState( self.STATE_CONNECTING ) end end --====================================================================-- --== State Machine --== CREATE ==-- function NetStream:state_create( next_state, params ) -- print( "NetStream:state_create: >> ", next_state ) if next_state == NetStream.STATE_NOT_CONNECTED then self:do_state_not_connected( params ) else print( "WARNING :: NetStream:state_create " .. tostring( next_state ) ) end end --== NOT CONNECTED ==-- function NetStream:do_state_not_connected( params ) -- print( "NetStream:do_state_not_connected" ) params = params or {} --==-- local event = params.event or nil -- might get event here -- set state first so we can go to another self:setState( self.STATE_NOT_CONNECTED ) if event then -- we're coming from being connected self:_send( nil, event.emsg ) self:dispatchEvent( self.DISCONNECTED, { emsg=event.emsg }, {merge=true} ) else -- haven't connected yet if self._auto_connect == true then self:gotoState( self.STATE_CONNECTING ) end end end function NetStream:state_not_connected( next_state, params ) -- print( "NetStream:state_not_connected: >> ", next_state ) if next_state == NetStream.STATE_CONNECTING then self:do_state_connecting( params ) else print( "WARNING :: NetStream:state_not_connected " .. tostring( next_state ) ) end end --== CONNECTING ==-- function NetStream:do_state_connecting( params ) -- print( "NetStream:do_state_connecting" ) params = params or {} --==-- params.onConnect = self._onConnect_f params.onData = self._onData_f self._header_wait = false -- set state first so we can go to another self:setState( self.STATE_CONNECTING ) self:dispatchEvent( self.CONNECTING ) self._sock:connect( self._host, self._port, params ) end function NetStream:state_connecting( next_state, params ) -- print( "NetStream:state_connecting: >> ", next_state ) if next_state == NetStream.STATE_CONNECTED then self:do_state_connected( params ) elseif next_state == NetStream.STATE_NOT_CONNECTED then self:do_state_not_connected( params ) else print( "WARNING :: NetStream:state_connecting " .. tostring( next_state ) ) end end --== CONNECTED ==-- function NetStream:do_state_connected( params ) -- print( "NetStream:do_state_connected" ) params = params or {} --==-- -- set state first so we can go to another self:setState( self.STATE_CONNECTED ) self:dispatchEvent( self.CONNECTED ) end function NetStream:state_connected( next_state, params ) -- print( "NetStream:state_connected: >> ", next_state ) if next_state == NetStream.STATE_NOT_CONNECTED then self:do_state_not_connected( params ) else print( "WARNING :: NetStream:state_connected " .. tostring( next_state ) ) end end --====================================================================-- --== Private Methods --[[ Chunk contains the current chunk of data. When the transmission is over, the function is called with an empty string (i.e. "") as the chunk. If an error occurs, the function receives 'nil' as chunk and an error message as 'err' --]] function NetStream:_send( data, emsg ) -- print("NetStream:_send", #data ) if self._listener then self._listener( { data=data, emsg=emsg } ) end end function NetStream:_handleErrorEvent( event ) -- print("NetStream:_handleErrorEvent", event ) self:_send( nil, event.emsg ) self:dispatchEvent( self.ERROR, { emsg=event.emsg }, {merge=true} ) self:gotoState( self.STATE_NOT_CONNECTED ) end --====================================================================-- --== Event Handlers function NetStream:_onConnect_handler( event ) -- print("NetStream:_onConnect_handler", event.status ) local sock = self._sock local user_agent = 'dmc-netstream %s' % tostring( NetStream.VERSION ) if event.status == sock.CONNECTED then -- print("=== Connection Established ===") local http_params, http_header http_params = self._http_params or {} http_header = http_params.headers or {} http_header = Utils.normalizeHeaders( http_header, {case='lower'} ) http_header['user-agent'] = http_header['user-agent'] or user_agent http_params.headers = http_header -- put back local p = { host=self._host, method=self._method, path=self._path, http_params = http_params } local bytes, err = sock:send( createHttpRequest( p ) ) elseif event.status == sock.CLOSED then -- print("=== Connection Closed ===\n\n") -- print( event.emsg ) self:gotoState( self.STATE_NOT_CONNECTED, { event=event } ) removeNetStream( self ) else -- print("=== Connection Error ===") self:_handleErrorEvent( event ) removeNetStream( self, event ) end end function NetStream:_onData_handler( event ) -- print("NetStream:_onData_handler", event.status ) event = event or {} -- print( '>>', event.type, event.status, event.bytes ) --==-- local curr_state = self:getState() local connecting_handler = function( e ) -- print("== Newline Handler ==") if not e.data then -- print( 'err>>', event.emsg ) self:_handleErrorEvent( event ) removeNetStream( self ) else -- print("Received Data:\n") -- for i,v in ipairs( e.data ) do print(i,v) end -- print("\n") self._header_wait = false self:gotoState( self.STATE_CONNECTED ) end end local connected_handler = function( e ) -- print("=== Data Event ===\n\n") -- print( 'data re>> ', e.data, e.emsg ) -- Utils.hexDump( e.data ) if e.data ~= nil then self:_send( e.data, e.emsg ) self:dispatchEvent( self.DATA, { data=e.data, emsg=event.emsg }, {merge=true} ) end end if curr_state == self.STATE_CONNECTING and not self._header_wait then self._sock:receiveUntilNewline( connecting_handler ) self._header_wait = true elseif curr_state == self.STATE_CONNECTED then self._sock:receive( '*a', connected_handler ) end end --====================================================================-- --== NetStream Facade --====================================================================-- return { newStream = createNetStream, }