content
stringlengths
5
1.05M
local class = require 'EasyLD.lib.middleclass' local WorldSlice = class('WorldSlice') function WorldSlice:initialize(map, offset) self.map = map self.offset = offset self:load() end function WorldSlice:load() self.mapHeight = self.map.h * self.map.tileset.tileSizeY self.entities = {} self.entitiesOrder = {} for i = 0, self.mapHeight - 1 do self.entitiesOrder[i + self.offset.y] = {} end end function WorldSlice:update(dt) for _,entity in ipairs(self.entities) do local oldY = math.floor(entity.pos.y) entity:update(dt) entity:tryMove(dt, self.map, self.entities) local newY = math.floor(entity.pos.y) if oldY ~= newY then self.entitiesOrder[oldY][entity] = nil self.entitiesOrder[newY][entity] = entity end end local deadEntities = {} for id,entity in ipairs(self.entities) do if entity.isDead then entity:onDeath() self.entitiesOrder[math.floor(entity.pos.y)][entity] = nil table.insert(deadEntities, id) end end for _,id in ipairs(deadEntities) do table.remove(self.entities, id) for i = entity.id, #self.entities do self.entities[i].id = i end end end function WorldSlice:draw() self.map:draw(self.offset.x, self.offset.y, self.map.w, self.map.h, 0, 0) for i = self.offset.y, self.offset.y + self.mapHeight - 1 do for _,entity in pairs(self.entitiesOrder[i]) do entity:draw() end end end function WorldSlice:addEntity(entity) table.insert(self.entities, entity) entity.id = #self.entities self.entitiesOrder[math.floor(entity.pos.y)][entity] = entity end function WorldSlice:removeEntity(entity) table.remove(self.entities, entity.id) for i = entity.id, #self.entities do self.entities[i].id = i end self.entitiesOrder[math.floor(entity.pos.y)][entity] = nil end return WorldSlice
---------------------- -------------------- -- Math Functions ---------------- -------------- ------------ ---------- -------- ------ ---- -- ------------------ -- Public Functions -------- ------ ---- -- -- _:abs(num) -- Returns absolute value of `num`. -- -- @param number(num) -- @return number function _:abs(num) num = _:assertArgument('num', num, 'number') -- return _.__abs(num) end -- _:add(...) -- Adds all `...` numbers and returns sum. -- -- @param number(...) -- @return number function _:add(...) return _:sum(...) end -- _:bin2Dec(bin) -- Converts `bin` representation into -- it's base-10 numeric counterpart. -- -- @param string(bin) -- @return number function _:bin2Dec(bin) bin = _:assertArgument('bin', bin, 'string') -- local dec = 0 local exp = _.__len(bin) - 1 for v in _.__gmatch(bin, '.') do dec = dec + tonumber(v) * 2 ^ exp exp = exp - 1 end return dec end -- _:bin2Hex(bin) -- Converts `bin` representation into -- it's hexadecimal string counterpart. -- -- @param string(bin) -- @return string function _:bin2Hex(bin) bin = _:assertArgument('bin', bin, 'string') -- return _:dec2Hex(_:bin2Dec(bin)) end -- _:bitwiseAND(x, y) -- Perform bitwise AND operation on `x` and -- returns the result. -- -- @param number(x) -- @param number(y) -- @return number function _:bitwiseAND(x, y) x = _:assertArgument('x', x, 'number') y = _:assertArgument('y', y, 'number') -- local bx = _:padStart(_:dec2Bin(x), 32, '0') local by = _:padStart(_:dec2Bin(y), 32, '0') local cx = _:words(bx, '.') local cy = _:words(by, '.') local out = '' for i = 1, #cx do if cx[i] == cy[i] then out = out .. cx[i] else out = out .. '0' end end return _:bin2Dec(out) end -- _:bitwiseNOT(x) -- Perform bitwise NOT operation on `x` and -- returns the result. -- -- @param number(x) -- @return number function _:bitwiseNOT(x) x = _:assertArgument('x', x, 'number') -- return -x - 1 end -- _:bitwiseOR(x, y) -- Perform bitwise OR operation on `x` and -- returns the result. -- -- @param number(x) -- @param number(y) -- @return number function _:bitwiseOR(x, y) x = _:assertArgument('x', x, 'number') y = _:assertArgument('y', y, 'number') -- local bx = _:padStart(_:dec2Bin(x), 32, '0') local by = _:padStart(_:dec2Bin(y), 32, '0') local cx = _:words(bx, '.') local cy = _:words(by, '.') local out = '' for i = 1, #cx do if cx[i] == '1' or cy[i] == '1' then out = out .. '1' else out = out .. '0' end end return _:bin2Dec(out) end -- _:bitwiseXOR(x, y) -- Perform bitwise XOR operation on `x` and -- returns the result. -- -- @param number(x) -- @param number(y) -- @return number function _:bitwiseXOR(x, y) x = _:assertArgument('x', x, 'number') y = _:assertArgument('y', y, 'number') -- local bx = _:padStart(_:dec2Bin(x), 32, '0') local by = _:padStart(_:dec2Bin(y), 32, '0') local cx = _:words(bx, '.') local cy = _:words(by, '.') local out = '' for i = 1, #cx do if cx[i] == '1' then out = out .. (cy[i] == '0' and '1' or '0') elseif cy[i] == '1' then out = out .. (cx[i] == '0' and '1' or '0') else out = out .. '0' end end return _:bin2Dec(out) end -- _:ceil(num, [precision=0]) -- Rounds up `num` to desired `precision`. -- -- @param number(num) -- @param number(precision) -- @return number function _:ceil(num, precision) num = _:assertArgument('num', num, 'number') precision = _:assertArgument('precision', precision, 'number', 0) -- local factor = 10 ^ precision return _.__ceil(num * factor) / factor end -- _:dec2Bin(dec) -- Converts `dec` representation into it's -- binary string counterpart. -- -- @param number(dec) -- @return string function _:dec2Bin(dec) dec = _:assertArgument('dec', dec, 'number') -- -- local hex = _.__format('%x', dec) -- local bin = _:hex2Bin(hex) local num = _.__abs(dec) local bin = '' local mod = 0 while num > 0 do bin = bin .. tostring(num % 2) num = _.__floor(num / 2) end bin = _.__reverse(bin) if dec < 0 then -- 2's complement complement = _:padStart(_:dec2Bin(_:bitwiseNOT(dec)), 32, '1') mask = _:rep('1', 32) print(_:bitwiseOR(complement, mask)) end return bin end -- _:dec2Hex(dec) -- Converts `dec` representation into it's -- hexadecimal string counterpart. -- -- @param number(dec) -- @return string function _:dec2Hex(dec) dec = _:assertArgument('dec', dec, 'number') -- return _.__upper(_.__format('%x', dec)) end -- _:divide(...) -- Divides series of numbers and returns result. -- -- @param number(...) -- @return number function _:divide(...) local out for k, v in pairs({...}) do if _:isNumber(v) then if not out then out = v else _:assertNotZero('v', v) out = out / v end end end return out end -- _:floor(num, [precision=0]) -- Rounds down `num` to desired `precision`. -- -- @param number(num) -- @param number(precision) -- @return number function _:floor(num, precision) num = _:assertArgument('num', num, 'number') precision = _:assertArgument('precision', precision, 'number', 0) -- local factor = 10 ^ precision return _.__floor(num * factor) / factor end -- _:hex2Bin(hex) -- Converts `hex` representation into it's -- binary string counterpart. -- -- @param string(bin) -- @return string function _:hex2Bin(hex) hex = _:assertArgument('hex', hex, 'string') -- local bin = '' for v in _.__gmatch(hex, '.') do bin = bin .. _.HB[_.__lower(v)] end return bin end -- _:hex2Dec(hex) -- Converts `hex` representation into it's -- base-10 numeric counterpart. -- -- @param string(bin) -- @return number function _:hex2Dec(hex) hex = _:assertArgument('hex', hex, 'string') -- return _:bin2Dec(_:hex2Bin(hex)) end -- _:max(...) -- Finds max value in sequence of numbers. -- -- @param number(...) -- @return number function _:max(...) return _:maxBy({...}) end -- _:maxBy(tabl, [iteratee]) -- Finds max in sequence of numbers, with -- every element invoked by `iteratree`. -- -- note: -- every element of `tabl` will invoke -- `iteratree`, if provided -- -- @param table(tabl) -- @param function(iteratee) - func to ivoke per element -- @return number function _:maxBy(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function', _.D['iteratee']) -- local max for k, v in pairs(tabl) do local value = iteratee(v) if _:isNumber(value) then if not max then max = value else max = _.__max(max, value) end end end return max end -- _:mean(...) -- Computes mean of sequence of numbers. -- -- @param number(...) -- @return number function _:mean(...) return _:meanBy({...}) end -- _:mean(tabl, [iteratee]) -- computes mean of numbers in `tabl` -- -- note: -- every element of `tabl` will invoke -- `iteratree`, if provided -- -- @param table(tabl) -- @param function(iteratee) - func to ivoke per element -- @return number function _:meanBy(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function', _.D['iteratee']) -- local size = _:size(tabl) if size > 0 then return (_:sumBy(tabl, iteratee) / size) end return 0 end -- _:min(...) -- Computes minimum of sequence of numbers. -- -- @param number(...) -- @return number function _:min(...) return _:minBy({...}) end -- _:minBy(tabl, [iteratee]) -- Computes minimum of `tabl` of numbers, -- with every element invoked by `iteratree`. -- -- note: -- every element of `tabl` will invoke -- `iteratree`, if provided -- -- @param table(tabl) -- @param function(iteratee) - func to ivoke per element -- @return number function _:minBy(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function', _.D['iteratee']) -- local min for k, v in pairs(tabl) do local value = iteratee(v) if _:isNumber(value) then if not min then min = value else min = _.__min(min, value) end end end return min end -- _:multiply(...) -- Multiplies sequence of numbers. -- -- @param number(...) -- @return number function _:multiply(...) return _:multiplyBy({...}) end -- _:multiply(...) -- Multiplies series of numbers, with every -- element invoked by `iteratree`. -- -- Note: Every element of `tabl` will invoke -- `iteratree`, if provided. -- -- @param mixed(...) -- @return number function _:multiplyBy(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function', _.D['iteratee']) -- local mul for k, v in pairs(tabl) do local value = iteratee(v) if _:isNumber(value) then if not mul then mul = value else mul = mul * value end end end return mul end -- _:round(num, [precision=0]) -- Computes `value` rounded to `precision`. -- -- @param number(num) -- @param number(precision) -- @return number function _:round(num, precision) num = _:assertArgument('num', num, 'number') precision = _:assertArgument('precision', precision, 'number', 0) -- local factor = 10 ^ precision return _.__floor(num * factor + 0.5) / factor end -- _:subtract(...) -- Subtracts sequence of numbers -- -- @param number(...) -- @return number function _:subtract(...) return _:subtractBy({...}) end -- _:subtractBy(tabl, iteratee) -- Subtracts `tabl` of numbers, with every -- element invoked by `iteratree`. -- -- note: -- every element of `tabl` will invoke -- `iteratree`, if provided -- -- @param table(tabl) -- @param function(iteratee) - func to ivoke per element -- @return number function _:subtractBy(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function', _.D['iteratee']) -- local sub for k, v in pairs(tabl) do local value = iteratee(v) if _:isNumber(value) then if not sub then sub = value else sub = sub - value end end end return sub end -- _:sum(...) -- Sums sequence of numbers. -- -- @param number(...) -- @return number function _:sum(...) return _:sumBy({...}) end -- _:sumBy(tabl, [iteratee]) -- computes sum of all values in `tabl` -- -- note: -- every element of `tabl` will invoke -- `iteratree`, if provided -- -- @param table(tabl) -- @param function(iteratee) - func to ivoke per element -- @return number function _:sumBy(tabl, iteratee) tabl = _:assertArgument('tabl', tabl, 'table') iteratee = _:assertArgument('iteratee', iteratee, 'function', _.D['iteratee']) -- local sum = 0 for k, v in pairs(tabl) do local value = iteratee(v) if _:isNumber(value) then sum = sum + value end end return sum end -- _:toDeg(rad) -- Converts `rad` to degrees. -- -- @param number(rad) - radians -- @return number function _:toDeg(rad) return _.__deg(rad) end -- _:toRad(deg) -- Converts `deg` to radians. -- -- @param number(deg) - degrees -- @return number function _:toRad(deg) return _.__rad(deg) end
--[[--------------------------------------------------------------------------- DarkRP custom jobs --------------------------------------------------------------------------- This file contains your custom jobs. This file should also contain jobs from DarkRP that you edited. Note: If you want to edit a default DarkRP job, first disable it in darkrp_config/disabled_defaults.lua Once you've done that, copy and paste the job to this file and edit it. The default jobs can be found here: https://github.com/FPtje/DarkRP/blob/master/gamemode/config/jobrelated.lua For examples and explanation please visit this wiki page: http://wiki.darkrp.com/index.php/DarkRP:CustomJobFields Add your custom jobs under the following line: ---------------------------------------------------------------------------]] TEAM_POLICE = DarkRP.createJob("Police Officer", { color = Color(25, 25, 170, 255), model = { "models/kerry/player/police_chicago_01.mdl", "models/kerry/player/police_chicago_02.mdl", "models/kerry/player/police_chicago_03.mdl", "models/kerry/player/police_chicago_04.mdl", "models/kerry/player/police_chicago_05.mdl", "models/kerry/player/police_chicago_06.mdl", "models/kerry/player/police_chicago_07.mdl", "models/kerry/player/police_chicago_08.mdl", "models/kerry/player/police_chicago_09.mdl" }, description = [[The protector of every citizen that lives in the city. You have the power to arrest criminals and protect innocents. Hit a player with your arrest baton to put them in jail. Bash a player with a stunstick and they may learn to obey the law. The Battering Ram can break down the door of a criminal, with a warrant for their arrest. The Battering Ram can also unfreeze frozen props (if enabled). Type /wanted <name> to alert the public to the presence of a criminal.]], weapons = {"unarrest_stick", "fas2_p226", "weapon_r_handcuffs", "stunstick", "door_ram", "weaponchecker", "bala_pocketsearch"}, command = "police", max = 10, salary = GAMEMODE.Config.normalsalary * 1.45, admin = 0, vote = false, hasLicense = true, ammo = { ["fas2_ammo_357sig"] = 30, }, category = "Civil Protection", }) TEAM_CHIEF = DarkRP.createJob("Chief of Police", { color = Color(20, 20, 255, 255), model = { "models/kerry/player/police_chicago_01.mdl", "models/kerry/player/police_chicago_02.mdl", "models/kerry/player/police_chicago_03.mdl", "models/kerry/player/police_chicago_04.mdl", "models/kerry/player/police_chicago_05.mdl", "models/kerry/player/police_chicago_06.mdl", "models/kerry/player/police_chicago_07.mdl", "models/kerry/player/police_chicago_08.mdl", "models/kerry/player/police_chicago_09.mdl" }, description = [[The Chief is the leader of the Civil Protection unit. Coordinate the police force to enforce law in the city. Hit a player with arrest baton to put them in jail. Bash a player with a stunstick and they may learn to obey the law. The Battering Ram can break down the door of a criminal, with a warrant for his/her arrest. Type /wanted <name> to alert the public to the presence of a criminal. Type /jailpos to set the Jail Position]], weapons = {"unarrest_stick", "fas2_ragingbull", "weapon_r_handcuffs", "stunstick", "door_ram", "weaponchecker", "bala_pocketsearch"}, command = "chief", max = 1, salary = GAMEMODE.Config.normalsalary * 1.67, admin = 0, vote = false, hasLicense = true, chief = true, NeedToChangeFrom = TEAM_POLICE, ammo = { ["fas2_ammo_454casull"] = 30, }, category = "Civil Protection", }) TEAM_SWAT = DarkRP.createJob("S.W.A.T", { color = Color(25, 25, 170, 255), model = { "models/player/pmc_4/pmc__02.mdl", "models/player/pmc_4/pmc__03.mdl", "models/player/pmc_4/pmc__04.mdl", "models/player/pmc_4/pmc__05.mdl", "models/player/pmc_4/pmc__06.mdl", "models/player/pmc_4/pmc__07.mdl", "models/player/pmc_4/pmc__08.mdl", "models/player/pmc_4/pmc__09.mdl", "models/player/pmc_4/pmc__10.mdl", "models/player/pmc_4/pmc__11.mdl", "models/player/pmc_4/pmc__12.mdl", "models/player/pmc_4/pmc__13.mdl", "models/player/pmc_4/pmc__14.mdl", }, description = [[Task force for when y'all fucked up]], weapons = {"unarrest_stick", "fas2_p226", "fas2_mp5a5", "weapon_r_handcuffs", "stunstick", "door_ram", "weaponchecker", "bala_pocketsearch", "fas2_att_compm4", "fas2_att_suppressor", "fas2_att_foregrip"}, command = "swat", max = 10, salary = GAMEMODE.Config.normalsalary * 1.45, admin = 0, vote = false, hasLicense = true, ammo = { ["fas2_ammo_357sig"] = 30, ["fas2_ammo_9x19"] = 60 }, category = "Civil Protection", }) TEAM_CITIZEN = DarkRP.createJob("Citizen", { color = Color(20, 150, 20, 255), model = { "models/player/Group01/Female_01.mdl", "models/player/Group01/Female_02.mdl", "models/player/Group01/Female_03.mdl", "models/player/Group01/Female_04.mdl", "models/player/Group01/Female_06.mdl", "models/player/group01/male_01.mdl", "models/player/Group01/Male_02.mdl", "models/player/Group01/male_03.mdl", "models/player/Group01/Male_04.mdl", "models/player/Group01/Male_05.mdl", "models/player/Group01/Male_06.mdl", "models/player/Group01/Male_07.mdl", "models/player/Group01/Male_08.mdl", "models/player/Group01/Male_09.mdl" }, description = [[The Citizen is the most basic level of society you can hold besides being a hobo. You have no specific role in city life.]], weapons = {}, command = "citizen", max = 0, salary = GAMEMODE.Config.normalsalary, admin = 0, vote = false, hasLicense = false, candemote = false, category = "Citizens", useCharacterAppearance = true -- IMPORTANT IF YOU WANT TO PRESERVE THE PLAYERS PURCHASED CLOTHES }) TEAM_MEDIC = DarkRP.createJob("Paramedic", { color = Color(47, 79, 79, 255), model = { "models/player/gems_paramedic1/female_01.mdl", "models/player/gems_paramedic1/female_02.mdl", "models/player/gems_paramedic1/female_03.mdl", "models/player/gems_paramedic1/female_04.mdl", "models/player/gems_paramedic1/female_06.mdl", "models/player/gems_paramedic1/female_07.mdl", "models/player/gems_paramedic1/male_01.mdl", "models/player/gems_paramedic1/male_02.mdl", "models/player/gems_paramedic1/male_03.mdl", "models/player/gems_paramedic1/male_04.mdl", "models/player/gems_paramedic1/male_05.mdl", "models/player/gems_paramedic1/male_06.mdl", "models/player/gems_paramedic1/male_07.mdl", "models/player/gems_paramedic1/male_08.mdl", "models/player/gems_paramedic1/male_09.mdl" }, description = [[With your medical knowledge you work to restore players to full health. Without a medic, people cannot be healed. Left click with the Medical Kit to heal other players. Right click with the Medical Kit to heal yourself.]], weapons = {"fas2_ifak"}, ammo = { ["fas2_ammo_medical"] = 1 }, command = "medic", max = 3, salary = GAMEMODE.Config.normalsalary, admin = 0, vote = false, hasLicense = false, medic = true, category = "Citizens", }) --[[--------------------------------------------------------------------------- Define which team joining players spawn into and what team you change to if demoted ---------------------------------------------------------------------------]] GAMEMODE.DefaultTeam = TEAM_CITIZEN --[[--------------------------------------------------------------------------- Define which teams belong to civil protection Civil protection can set warrants, make people wanted and do some other police related things ---------------------------------------------------------------------------]] GAMEMODE.CivilProtection = { [TEAM_POLICE] = true, [TEAM_CHIEF] = true, [TEAM_MAYOR] = true, } --[[--------------------------------------------------------------------------- Jobs that are hitmen (enables the hitman menu) ---------------------------------------------------------------------------]] DarkRP.addHitmanTeam(TEAM_MOB) -- Give everyone the ARCBank card regardless of job hook.Add("PlayerLoadout", "GiveARCBankCard", function(ply) if ply:isArrested() then return end ply:Give("weapon_arc_atmcard") end)
local awful = require("awful") local client_placement_f = awful.placement.no_overlap + awful.placement.no_offscreen local mon_width = awful.screen.focused().geometry.width local mon_height = awful.screen.focused().geometry.height awful.rules.rules = { { id = "global", rule = { }, properties = { floating = false, size_hints_honor = false, honor_workare = true, honor_padding = true, focus = awful.client.focus.filter, raise = true, screen = awful.screen.focused, }, }, { id = "floating", rule_any = { instance = { "copyq", "pinentry" }, class = { "Arandr", "Blueman-manager", "Gpick", "Kruler", "Sxiv", "Tor Browser", "Wpa_gui", "veromix", "xtightvncviewer", "Wine" }, name = { "Event Tester", -- xev. }, role = { "AlarmWindow", -- Thunderbird's calendar. "ConfigManager", -- Thunderbird's about:config. "pop-up", -- e.g. Google Chrome's (detached) Developer Tools. } }, properties = { floating = true } }, -- Add titlebars to normal clients and dialogs { id = "titlebars", rule_any = { type = { "normal", "dialog" } }, properties = { titlebars_enabled = true } }, -- Discord & Messengers { rule = { class = "discord" }, properties = { screen = 1, tag = awful.screen.focused().tags[3], titlebars_enabled = true } }, -- Steam { rule = { class = "Steam", name = "Steam" }, properties = { screen = 1, tag = awful.screen.focused().tags[4], titlebars_enabled = false, floating = true, x = 100, y = 100 } }, { rule = { class = "Steam", name = "Friends List" }, properties = { screen = 1, tag = awful.screen.focused().tags[4], titlebars_enabled = false, floating = true, x = mon_width-500, y = 100 } }, -- Streaming { rule = { class = "obs" }, properties = { screen = 1, tag = awful.screen.focused().tags[6], titlebars_enabled = false, floating = true } }, -- Games { rule_any = { class = { "Terraria.bin.x86", "yuzu" } }, properties = { screen = 1, tag = awful.screen.focused().tags[4], titlebars_enabled = false, floating = true, switch_to_tags = true } }, { rule_any = { class = { "terraria.exe", "Terraria.exe", "steam_app_105600" } }, properties = { screen = 1, tag = awful.screen.focused().tags[4], titlebars_enabled = false, floating = false, switch_to_tags = true } }, -- Deluge & Others { rule = { class = "Deluge" }, properties = { screen = 1, tag = awful.screen.focused().tags[5] } }, { rule = { class = "Sxiv" }, properties = { screen = 1, width = mon_width/1.5, height = mon_height/1.5, x = mon_width/2 - (mon_width/1.5)/2, y = mon_height/2 - (mon_height/1.5)/2 } }, -- Remove from my view { rule = { class = "bluetoothst" }, properties = { screen = 1, tag = awful.screen.focused().tags[5] } }, -- Browsers { rule = { class = "Firefox" }, properties = { screen = 1, tag = awful.screen.focused().tags[2], switch_to_tags = true, titlebars_enabled = true } }, -- Dialogues { rule_any = { type = { "dialog", }, role = { "GtkFileChooserDialog", "conversation", } }, properties = { screen = 1, titlebars_enabled = false, floating = true }, callback = function (c) awful.placement.centered(c, { honor_padding = true, honor_workarea = true }) end } }
local PistolRun = class("PistolRun", PlayerActState) local dirStateEnum = { Forward = 1, Back = 2, Right = 3, Left = 4 } local curDirState = 0 local function Turn(_dir) if _dir ~= curDirState then curDirState = _dir if _dir == dirStateEnum.Forward then localPlayer.Avatar:PlayAnimation("RunFront", 9, 1, 0.1, true, true, 1) elseif _dir == dirStateEnum.Right then localPlayer.Avatar:PlayAnimation("RunRight", 9, 1, 0.1, true, true, 1) elseif _dir == dirStateEnum.Left then localPlayer.Avatar:PlayAnimation("RunLeft", 9, 1, 0.1, true, true, 1) elseif _dir == dirStateEnum.Back then localPlayer.Avatar:PlayAnimation("RunBack", 9, 1, 0.1, true, true, 1) end end end function PistolRun:OnEnter() PlayerActState.OnEnter(self) localPlayer.Avatar:SetBlendSubtree(Enum.BodyPart.LowerBody, 9) local dir = PlayerCtrl.finalDir curDirState = 0 if Vector3.Angle(dir, localPlayer.Forward) < 30 then Turn(dirStateEnum.Forward) elseif Vector3.Angle(dir, localPlayer.Right) < 75 then Turn(dirStateEnum.Right) elseif Vector3.Angle(dir, localPlayer.Left) < 75 then Turn(dirStateEnum.Left) else Turn(dirStateEnum.Back) end end function PistolRun:OnUpdate(dt) PlayerActState.OnUpdate(self, dt) FsmMgr.playerActFsm:TriggerMonitor( { "Idle", "SwimIdle", "PistolHit", "PistolAttack", "Vertigo", "TakeOutItem" } ) self:IdleMonitor() self:WalkMonitor("Pistol") self:JumpMonitor("Pistol") end function PistolRun:OnLeave() PlayerActState.OnLeave(self) localPlayer.Avatar:StopAnimation("RunFront", 9) localPlayer.Avatar:StopAnimation("RunRight", 9) localPlayer.Avatar:StopAnimation("RunLeft", 9) localPlayer.Avatar:StopAnimation("RunBack", 9) end ---็›‘ๅฌ้™ๆญข function PistolRun:IdleMonitor() local dir = PlayerCtrl.finalDir dir.y = 0 if dir.Magnitude > 0 then if localPlayer.LinearVelocity.Magnitude > 0 then if Vector3.Angle(dir, localPlayer.Forward) < 30 then Turn(dirStateEnum.Forward) elseif Vector3.Angle(dir, localPlayer.Right) < 75 then Turn(dirStateEnum.Right) elseif Vector3.Angle(dir, localPlayer.Left) < 75 then Turn(dirStateEnum.Left) else Turn(dirStateEnum.Back) end end localPlayer:MoveTowards(Vector2(dir.x, dir.z)) else FsmMgr.playerActFsm:Switch("PistolIdle") end end return PistolRun
object_tangible_furniture_jedi_frn_all_table_light_01_hue = object_tangible_furniture_jedi_shared_frn_all_table_light_01_hue:new { } ObjectTemplates:addTemplate(object_tangible_furniture_jedi_frn_all_table_light_01_hue, "object/tangible/furniture/jedi/frn_all_table_light_01_hue.iff")
-- General Hammerspoon configurations hs.window.animationDuration = 0.1 hs.application.enableSpotlightForNameSearches(true) hs.hints.hintChars = { "J", "K", "L", ";", "A", "S", "D", "F", "H", "G" } -- Window size and position history local windowHistory = {} function windowHistory:save() local window = hs.window.focusedWindow() if not self[window:id()] then self[window:id()] = {} end table.insert(self[window:id()], window:frame()) end function windowHistory:restore() local window = hs.window.focusedWindow() if not self[window:id()] then return end if #self[window:id()] > 0 then window:setFrame(table.remove(self[window:id()])) end end -- Remove window history of no longer existing windows function windowHistory:clean() for id in pairs(self) do if type(id) == "number" and hs.window.get(id) == nil then self[id] = nil end end end -- Clean the window history every 5 minutes to avoid memory leaks hs.timer.doEvery(hs.timer.minutes(5), function() windowHistory:clean() end) -- setFocusedWindow set the current window frame according to the return value of -- `layoutfn`, which should be a function that takes three arguments: -- `screen`: The screen's frame -- `window`: The current window's frame -- `isExternal`: Whether it's not on the built in display or not function setFocusedWindow(layoutfn) -- Return a function so we could use it easily with `bind()` return function() local window = hs.window.focusedWindow() local screen = window:screen() local isExternal = false if screen:name() == "Thunderbolt Display" then isExternal = true end windowHistory:save() window:setFrame(hs.geometry(layoutfn(screen:frame(), window:frame(), isExternal))) end end -- Focus an application, toggling between its windows function focus(appName) -- Return a function so we could use it easily with `bind()` return function() local app = hs.application.get(appName) if app then if not app:isFrontmost() then app:mainWindow():focus() else -- Filter windows without title (workaround a Chrome issue) local windows = hs.fnutils.filter(app:allWindows(), function(w) return w:title() ~= "" end) if #windows > 1 and app:mainWindow() == windows[1] then windows[2]:focus() else windows[1]:focus() end end end end end -- Bind a key to the hyper key function bind(key, fn) hs.hotkey.bind({"ctrl", "alt", "cmd", "shift"}, key, fn) end -- Hammersppon hints bind("h", hs.hints.windowHints) -- Focus specific applications bind("j", focus("Google Chrome")) bind("k", focus("Emacs")) bind("l", focus("Terminal")) bind("u", focus("Dash")) -- Focus a bindable application local bindableFocus = nil -- Set the application to focus bind("8", function() bindableFocus = hs.window.focusedWindow() end) -- Focus the application bind("i", function() if bindableFocus then bindableFocus:focus() end end) -- Start screensave hs.hotkey.bind({}, "f20", hs.caffeinate.startScreensaver) -- Sending windows to different monitors bind("1", function() hs.window:focusedWindow():centerOnScreen(hs.screen.allScreens()[1], true) end) bind("2", function() hs.window:focusedWindow():centerOnScreen(hs.screen.allScreens()[2], true) end) -- Laptop layout ratios local rightRatio = 0.4443 local leftRatio = 0.5556 -- Restore layout history bind("z", function() windowHistory:restore() end) -- Left window bind("a", setFocusedWindow(function(screen, window, isExternal) if isExternal then return { x = screen.x + 20, y = screen.y + 20, w = 1100, h = screen.h - 40, } else return { x = screen.x, y = screen.y, w = screen.w * leftRatio, h = screen.h, } end end)) -- Middle window bind("s", setFocusedWindow(function(screen, window, isExternal) if isExternal then return { x = screen.x + 20, y = screen.y + 20, w = screen.w - 40, h = screen.h - 40, } else return { x = screen.x + 20, y = screen.y, w = screen.w - 40, h = screen.h, } end end)) -- Right window bind("d", setFocusedWindow(function(screen, window, isExternal) if isExternal then return { x = screen.x + screen.w - 1420, y = screen.y + 20, w = 1400, h = screen.h - 40, } else return { x = screen.x + screen.w * leftRatio, y = screen.y, w = screen.w * rightRatio, h = screen.h, } end end)) -- Center window bind("c", setFocusedWindow(function(screen, window) return { x = screen.x + (screen.w - window.w) / 2, y = screen.y + (screen.h - window.h) / 2, w = window.w, h = window.h, } end)) -- Upper center window bind("v", setFocusedWindow(function(screen, window) return { x = screen.x + (screen.w - window.w) / 2, y = screen.y + 40, w = window.w, h = window.h, } end)) -- Finder sized window bind("f", setFocusedWindow(function(screen, window) return { x = window.x, y = window.y, h = 640, w = 600, } end)) -- Right middle window, suitable for DevTools bind("r", setFocusedWindow(function(screen) return { x = screen.x + screen.w - 1320, y = screen.y + 120, w = 1200, h = screen.h - 240, } end)) -- Tall window bind("w", setFocusedWindow(function(screen, window) return { x = window.x, y = screen.y + 20, w = window.w, h = screen.h - 40, } end)) -- Application specific configuration -- A helper function that converts an event to key code: { modifiers.., characters... } function toKey(event) local key = {} for modifier, _ in pairs(event:getFlags()) do table.insert(key, modifier) end table.insert(key, hs.keycodes.map[event:getKeyCode()]) return key end -- Swap meta and alt keys in Terminal.app local swapMeta = hs.eventtap.new({ hs.eventtap.event.types.keyDown }, function(event) -- Ignore those keys when swaping the meta local ignoredKeys = hs.fnutils.map({ { "cmd", "tab" }, { "cmd", "space" }, { "alt", "space" }, { "cmd", "q" }, { "cmd", "c" }, { "cmd", "alt", "c" }, { "cmd", "shift", "c" }, { "cmd", "," }, { "cmd", "shift", "4" }, { "cmd", "shift", "3" }, { "cmd", "ctrl", "\\" }, }, table.concat) local modifiers = event:getFlags() -- Ignore hyper key presses if modifiers.cmd and modifiers.alt and modifiers.ctrl and modifiers.shift then return false, {} end -- Ignore keys that are in ignoredKeys if hs.fnutils.contains(ignoredKeys, table.concat(toKey(event))) then return false, {} end if modifiers.alt then return true, { event:setFlags({ cmd = true, alt = nil }) } end if modifiers.cmd then return true, { event:setFlags({ cmd = nil, alt = true }) } end end) -- Attach the eventtap to the Terminal app only when it's focused hs.window.filter.new("Terminal") :subscribe(hs.window.filter.windowFocused, function() swapMeta:start() end) :subscribe(hs.window.filter.windowUnfocused, function() swapMeta:stop() end)
if kode == nil then return end local modules_init_ = { "role", nil, } -- moduleName = {skippedModel, skippedService} local skip_ = { test = {true} } local facade_ = kode.facade facade_:skip(skip_) facade_:registerModules(modules_init_) -- Event.checkEvents() --[[ Usage: local roleModel = app.model("role") -- "app.modules.role.role_m" local talentModel = app.model("role", "talent") -- "app.modules.role.talent_m" --]] function app.model(module, model) return facade_:loadModel(module, model) end --[[ Usage: local roleService = app.service("role") -- "app.modules.role.role_s" local talentService = app.service("role", "talent") -- "app.modules.role.talent_s" --]] function app.service(module, service) return facade_:loadService(module, service) end --[[ Usage: local rolePane = app.view("role") -- "app.modules.role.view.rolepane" local talentPane = app.view("role", "talent") -- "app.modules.role.view.talentpane" --]] function app.view(module, view) return facade_:loadView(module,view) end --[[ Usage: local roleVo = app.vo("role") -- "app.modules.role.role_vo" local talentVo = app.vo("role", "talent") -- "app.modules.role.talent_vo" --]] function app.vo(module, vo) return facade_:loadvo(module, vo) end --[[ ๅปบ่ฎฎไฝฟ็”จๆ–ฐ็š„ๆŽฅๅฃ by Andy Usage: local roleModel = ns.model.role -- "app.modules.role.role_m" local talentModel = ns.model.role_talent -- "app.modules.role.talent_m" local roleService = ns.service.role -- "app.modules.role.role_s" local talentService = ns.service.role_talent -- "app.modules.role.talent_s" local rolePane = ns.view.role -- "app.modules.role.view.rolepane" local talentPane = ns.view.role_talent -- "app.modules.role.view.talentpane" local roleVo = ns.vo.role -- "app.modules.role.role_vo" local talentVo = ns.vo.role_talent -- "app.modules.role.talent_vo" --]] _G.BaseController = facade_:loadController("base") _G.BaseModel = facade_:loadModel("base") _G.BaseService = facade_:loadService("base")
DriftPoints = {} local screenSize = Vector2(guiGetScreenSize()) local isActive = false local FONT_SIZE = 36 local font local listFont local totalScore = 0 local drawScore = 0 local borderOffset = 15 local playersScoreList = {} local scoreListUpdateTimer local themeColor = tocolor(255, 150, 0) addEvent("dpDriftPoints.earnedPoints") local function dxDrawTextShadow(text, x1, y1, x2, y2, color, scale, font, alignX, alignY, textRotation, alpha) if not alpha then alpha = 255 end dxDrawText(text, x1 - 1, y1, x2 - 1, y2, tocolor(0, 0, 0, alpha), scale, font, alignX, alignY, false, false, false, false, false, textRotation) dxDrawText(text, x1 + 1, y1, x2 + 1, y2, tocolor(0, 0, 0, alpha), scale, font, alignX, alignY, false, false, false, false, false, textRotation) dxDrawText(text, x1, y1 - 1, x2, y2 - 1, tocolor(0, 0, 0, alpha), scale, font, alignX, alignY, false, false, false, false, false, textRotation) dxDrawText(text, x1, y1 + 1, x2, y2 + 1, tocolor(0, 0, 0, alpha), scale, font, alignX, alignY, false, false, false, false, false, textRotation) dxDrawText(text, x1, y1, x2, y2, color, scale, font, alignX, alignY, false, false, false, false, false, textRotation) end local function getScoreText(score) score = tostring(score) local len = #score score = "#FFFFFF" .. score while len < 6 do score = "0" .. score len = len + 1 end return score end local function draw() drawScore = drawScore + math.ceil((totalScore - drawScore) * 0.2) dxDrawTextShadow(exports.dpLang:getString("race_drift_score") .. ": " .. tostring(drawScore), 0, 0, screenSize.x - borderOffset, screenSize.y, tocolor(255, 255, 255), 1, font, "right", "top", 0) local y = 60 for i, p in ipairs(playersScoreList) do local color = tocolor(255, 255, 255) if p[4] then color = themeColor end dxDrawText(p[1] .. ". " .. p[2] .. " - #AAAAAA" .. getScoreText(p[3]), 0, y, screenSize.x - borderOffset, y, color, 1, listFont, "right", "top", false, false, false, true) y = y + 25 end end local function updateScoreList() local players = RaceClient.getPlayers() if not players then return end table.sort(players, function (player1, player2) local score1 = player1:getData("raceDriftScore") or 0 local score2 = player2:getData("raceDriftScore") or 0 return score1 > score2 end) playersScoreList = {} local isFirst = true for i, player in ipairs(players) do if players[i + 1] and players[i + 1] == localPlayer then isFirst = false table.insert(playersScoreList, {i, exports.dpUtils:removeHexFromString(player.name), player:getData("raceDriftScore")}) elseif players[i] == localPlayer then table.insert(playersScoreList, {i, exports.dpUtils:removeHexFromString(player.name), player:getData("raceDriftScore"), true}) elseif players[i - 1] and players[i - 1] == localPlayer then table.insert(playersScoreList, {i, exports.dpUtils:removeHexFromString(player.name), player:getData("raceDriftScore")}) elseif isFirst and players[i - 2] and players[i - 2] == localPlayer then table.insert(playersScoreList, {i, exports.dpUtils:removeHexFromString(player.name), player:getData("raceDriftScore")}) end end end local function earnedPoints(points) DriftPoints.addScore(points) end function DriftPoints.start() if isActive then return false end font = exports.dpAssets:createFont("Roboto-Regular.ttf", FONT_SIZE, true) listFont = exports.dpAssets:createFont("Roboto-Regular.ttf", 16, true) isActive = true addEventHandler("onClientRender", root, draw) totalScore = 0 drawScore = 0 localPlayer:setData("raceDriftScore", 0) addEventHandler("dpDriftPoints.earnedPoints", root, earnedPoints) scoreListUpdateTimer = setTimer(updateScoreList, 1000, 0) themeColor = tocolor(exports.dpUI:getThemeColor()) end function DriftPoints.stop() if not isActive then return false end isActive = false removeEventHandler("onClientRender", root, draw) removeEventHandler("dpDriftPoints.earnedPoints", root, earnedPoints) localPlayer:setData("raceDriftScore", false) if isTimer(scoreListUpdateTimer) then killTimer(scoreListUpdateTimer) end if isElement(font) then destroyElement(font) end if isElement(listFont) then destroyElement(listFont) end end function DriftPoints.addScore(points) if type(points) ~= "number" then return false end totalScore = totalScore + points localPlayer:setData("raceDriftScore", totalScore) end function DriftPoints.getScore() return totalScore end
--[[ file:fishSystem.lua ]] local class = require("class") local gameSystem = require("game.system") ---@class fishSystem:gameSystem local system = class(gameSystem) ---ๆž„้€  function system:ctor() end return system
local Movement = Component:extend("Movement") function Movement:initialize(speed) assert(self.physics_type ~= "static", "tried to add a Movement component to a static physical entity") self.speed = speed or 200 self.movement = {} self.movement.x = 0 self.movement.y = 0 self.movable = true end function Movement:move(x, y) self.movement.x = x or self.movement.x self.movement.y = y or self.movement.y return self end function Movement:update(dt) if not self.movable then return end if self.parent then self.movement.x, self.movement.y = 0 return end local mx, my = MathUtils.normalize(self.movement.x, self.movement.y) self.physics_body:applyForce(mx * self.speed, my * self.speed) end function Movement:isMoveable() return self.movable end function Movement:setMovable(value) self.movable = value return self end function Movement:getMaxSpeed() return self.speed end
--[[---------------------------------------------------------------------------- Application Name: LocateAndMeasure Summary: Measuring part dimensions, independent on rotation and translation Description: Teaching the shape of a โ€golden partโ€, measuring edge-to-edge distance, circle radius etc. Matching new, identical objects with full rotation in the image and measuring the same dimensions. How to Run: Starting this sample is possible either by running the app (F5) or debugging (F7+F10). Setting breakpoint on the first row inside the 'main' function allows debugging step-by-step after 'Engine.OnStarted' event. Results can be seen in the image viewer on the DevicePage. Restarting the Sample may be necessary to show images after loading the webpage. To run this Sample a device with SICK Algorithm API and AppEngine >= V2.5.0 is required. For example SIM4000 with latest firmware. Alternatively the Emulator in AppStudio 2.3 or higher can be used. More Information: Tutorial "Algorithms - Fitting and Measurement". ------------------------------------------------------------------------------]] --Start of Global Scope--------------------------------------------------------- print('AppEngine Version: ' .. Engine.getVersion()) local DELAY = 2000 -- ms between visualization steps for demonstration purpose -- Creating global v local v = View.create() -- Loading necessary Scripts require('GraphicsSetup') -- Setup of graphical overlay attributes local matching = require('Matching') -- Functions for teaching and matching object shape local featuresFunc = require('Fitting') -- Functions for feature fitting local measure = require('Measurement') -- Functions for measuring local fixture = require('Fixture') -- Functions for pose-adjustment of regions in live images local passFailGraphics = require('PassFail') -- Functions for pass fail result handling, e.g. graphics --End of Global Scope----------------------------------------------------------- --Start of Function and Event Scope--------------------------------------------- local function main() -- Teaching local refImage = Image.load('resources/Teach.bmp') v:clear() local imageID = v:addImage(refImage) v:present() local teachPose = matching.teach(refImage, imageID, v) local features = featuresFunc.defineFeatures(imageID, v) local fitted = featuresFunc.fitFeatures(refImage, imageID, v, features) local positions = measure(imageID, v, fitted, features) fixture.setFixture(teachPose, features, positions) Script.sleep(DELAY) -- for demonstration purpose only -- Live for i = 1, 3 do local liveImage = Image.load('resources/' .. i .. '.bmp') v:clear() imageID = v:addImage(liveImage) v:present() local matchPose = matching.match(liveImage, imageID, v, teachPose) local fixt = fixture.getFixture(matchPose) fitted = featuresFunc.fitFeatures(liveImage, imageID, v, fixt) local measuredValues = measure(imageID, v, fitted, features) passFailGraphics(imageID, v, measuredValues) Script.sleep(DELAY) -- for demonstration purpose only end print('App finished.') end --The following registration is part of the global scope which runs once after startup --Registration of the 'main' function to the 'Engine.OnStarted' event Script.register('Engine.OnStarted', main) --End of Function and Event Scope-----------------
--[[---------------------------------------------------------------------------- 12345678901234567890123456789012345678901234567890123456789012345678901234567890 Debug Copyright 2010-2012, John R. Ellis -- You may use this script for any purpose, as long as you include this notice in any versions derived in whole or part from this file. This module provides an interactive debugger, a prepackaged LrLogger with some simple utility functions, and a rudimentary elapsed-time functin profiler. For an introductory overview, see the accompanying "Debugging Toolkit.htm". Overview of the public interface; for details, see the particular function: namespace init ([boolean enable]) Initializes the interactive debugger. boolean enabled True if the interactive debugging is enabled. function showErrors (function) Wraps a function with an error handler that invokes the debugger. string pp (value, int indent, int maxChars, int maxLines) Pretty prints an arbitrary Lua value. LrLogger log A log file that outputs to "debug.log" in the plugin directory. void setLogFilename (string) Changes the filename of "log". void logn (...) Writes the arguments to "log", converted to strings and space-separated. void lognpp (...) Pretty prints the arguments to "log", separated by spaces or newlines. void stackTrace () Writes a stack trace to "log". ------------------------------------------------------------------------------]] local Debug = {} local LrApplication = import 'LrApplication' local LrDate = import 'LrDate' local LrDialogs = import 'LrDialogs' local LrFunctionContext = import 'LrFunctionContext' local LrLogger = import 'LrLogger' local LrPathUtils = import 'LrPathUtils' local LrTasks = import 'LrTasks' -- Forward references local lineCount, logFilename, logPush, parseParams, showErrors, showWindow, sourceLines, upPush local Newline = WIN_ENV and "\r\n" or "\n" --[[ A platform-indepent newline. Unfortunately, some controls (e.g. edit_field) need to have the old-fashioned \r\n supplied in strings to display newlines properly on Windows. ]] --[[---------------------------------------------------------------------------- public namespace init ([boolean enable]) Re-initializes the interactive debugger, discarding breaks and cached source lines. If "enable" is true or if it is nil and the plugin directory ends with ".lrdevplugin", then debugging is enabled. Otherwise, debugging is disabled, and calls to Debug.pause, Debug.pauseIf, Debug.breakFunc, and Debug.unbreakFunc will be ignored. This lets you leave calls to the debugging functions in your code and just enable or disable the debugger via the call to Debug.init. Further, calling Debug.init() with no parameters automatically enables debugging only when running from a ".lrdevplugin" directory; in released code (".lrplugin"), debugging will be disabled. When Debug is loaded, it does an implicit Debug.init(). That is, debugging will be enabled if the plugin directory ends with ".lrdevplugin", disabled otherwise. Returns the Debug module. ------------------------------------------------------------------------------]] function Debug.init (enable) if enable == nil then enable = _PLUGIN.path:sub (-12) == ".lrdevplugin" end Debug.enabled = enable return Debug end --[[---------------------------------------------------------------------------- public boolean enabled True if debugging has been enabled by Debug.init, false otherwise. ------------------------------------------------------------------------------]] Debug.enabled = false --[[---------------------------------------------------------------------------- public function showErrors (function) Returns a function wrapped around "func" such that if any errors occur from calling "func", the debugger window is displayed. If debugging was disabled by Debug.init, then instead of displaying the debugger window, the standard Lightroom error dialog is displayed. ------------------------------------------------------------------------------]] function Debug.showErrors (func) if type (func) ~= "function" then error ("Debug.showErrors argument must be a function", 2) end if not Debug.enabled then return showErrors (func) end -- local fi = getFuncInfo (func) local fi if not fi then return showErrors (func) end return function (...) local args = {...} args.n = select("#", ...) local function onReturn (success, ...) if not success then local err = select (1, ...) if err ~= Debug.DebugTerminatedError then showWindow ("failed", fi.parameters, args, nil, err, getStackInfo (4, fi.funcName, fi.filename, fi.lineNumber, err)) end error (err, 0) else return ... end end if LrTasks.canYield () then return onReturn (LrTasks.pcall (func, ...)) else return onReturn (pcall (func, ...)) end end end --[[---------------------------------------------------------------------------- private func showErrors (func) Returns a function wrapped around "func" such that if any errors occur from calling "func", the standard Lightroom error dialog is displayed. By default, Lightroom doesn't show an error dialog for callbacks from LrView controls or for tasks created by LrTasks. ------------------------------------------------------------------------------]] function showErrors (func) return function (...) return LrFunctionContext.callWithContext("wrapped", function (context) LrDialogs.attachErrorDialogToFunctionContext (context) return func (unpack (arg)) end) end end --[[---------------------------------------------------------------------------- private boolean isSDKObject (x) Returns true if "x" is an object implemented by the LR SDK. In LR 3, those objects are tables with a string for a metatable, but in LR 4 beta, getmetatable() raises an error for such objects. NOTE: This is also in Util.lua. ------------------------------------------------------------------------------]] local majorVersion = LrApplication.versionTable ().major local function isSDKObject (x) if type (x) ~= "table" then return false elseif majorVersion < 4 then return type (getmetatable (x)) == "string" else local success, value = pcall (getmetatable, x) return not success or type (value) == "string" end end --[[---------------------------------------------------------------------------- public string pp (value, int indent, int maxChars, int maxLines) Returns "value" pretty printed into a string. The string is guaranteed not to end in a newline. indent (default 4): If "indent" is greater than zero, then it is the number of characters to use for indenting each level. If "indent" is 0, then the value is pretty-printed all on one line with no newlines. maxChars (default maxLines * 100): The output is guaranteed to be no longer than this number of characters. If it exceeds maxChars - 3, then the last three characters will be "..." to indicate truncation. maxLines (default 5000): The output is guaranteed to have no more than this many lines. If it is truncated, the last line will end with "..." ------------------------------------------------------------------------------]] function Debug.pp (value, indent, maxChars, maxLines) if not indent then indent = 4 end if not maxLines then maxLines = 5000 end if not maxChars then maxChars = maxLines * 100 end local s = "" local lines = 1 local tableLabel = {} local nTables = 0 local function addNewline (i) if #s >= maxChars or lines >= maxLines then return true end if indent > 0 then s = s .. "\n" .. string.rep (" ", i) lines = lines + 1 end return false end local function pp1 (x, i) if type (x) == "string" then s = s .. string.format ("%q", x):gsub ("\n", "n") elseif type (x) ~= "table" then s = s .. tostring (x) elseif isSDKObject (x) then s = s .. tostring (x) else if tableLabel [x] then s = s .. tableLabel [x] return false end local isEmpty = true for _, _ in pairs (x) do isEmpty = false; break end if isEmpty then s = s .. "{}" return false end nTables = nTables + 1 local label = "table: " .. nTables tableLabel [x] = label s = s .. "{" if indent > 0 then s = s .. "--" .. label end local first = true for k, v in pairs (x) do if first then first = false else s = s .. ", " end if addNewline (i + indent) then return true end if type (k) == "string" and k:match ("^[_%a][_%w]*$") then s = s .. k else s = s .. "[" if pp1 (k, i + indent) then return true end s = s .. "]" end s = s .. " = " if pp1 (v, i + indent) then return true end end s = s .. "}" end return false end local truncated = pp1 (value, 0) if truncated or #s > maxChars then s = s:sub (1, math.max (0, maxChars - 3)) .. "..." end return s end --[[---------------------------------------------------------------------------- public LrLogger log The "log" is an LrLogger log file that by default writes to the file "debug.log" in the current plugin directory. ------------------------------------------------------------------------------]] Debug.log = LrLogger ("com.daveburnsphoto.log") --[[ This apparently must be unique across all of Lightroom and plugins.]] logFilename = LrPathUtils.child (_PLUGIN.path, "debug.log") Debug.log:enable (function (msg) local f = io.open (logFilename, "a") if f == nil then return end f:write ( LrDate.timeToUserFormat (LrDate.currentTime (), "%y/%m/%d %H:%M:%S"), msg, Newline) f:close () end) --[[---------------------------------------------------------------------------- public void setLogFilename (string) Sets the filename of the log to be something other than the default (_PLUGIN.path/debug.log). ------------------------------------------------------------------------------]] function Debug.setLogFilename (filename) logFilename = filename end --[[---------------------------------------------------------------------------- public void logn (...) Writes all of the arguments to the log, separated by spaces on a single line, using tostring() to convert to a string. Useful for low-level debugging. ------------------------------------------------------------------------------]] function Debug.logn (...) local s = "" for i = 1, select ("#", ...) do local v = select (i, ...) s = s .. (i > 1 and " " or "") .. tostring (v) end Debug.log:trace (s) end --[[---------------------------------------------------------------------------- public void lognpp (...) Pretty prints all of the arguments to the log, separated by spaces or newlines. Useful ------------------------------------------------------------------------------]] function Debug.lognpp (...) local s = "" local sep = " " for i = 1, select ("#", ...) do local v = select (i, ...) local pp = Debug.pp (v) s = s .. (i > 1 and sep or "") .. pp if lineCount (pp) > 1 then sep = "\n" end end Debug.log:trace (s) end --[[---------------------------------------------------------------------------- private int lineCount (string s) Counts the number of lines in "s". The last line may or may not end with a newline, but it counts as a line. ------------------------------------------------------------------------------]] function lineCount (s) local l = 0 for i = 1, #s do if s:sub (i, i) == "\n" then l = l + 1 end end if #s > 0 and s:sub (-1, -1) ~= "\n" then l = l + 1 end return l end --[[---------------------------------------------------------------------------- public void stackTrace () Write a raw stack trace to the log. ------------------------------------------------------------------------------]] function Debug.stackTrace () local s = "\nStack trace:" local i = 2 while true do local info = debug.getinfo (i) if not info then break end s = string.format ("%s\n%s [%s %s]", s, info.name, info.source, info.currentline) i = i + 1 end Debug.log:trace (s) end return Debug
--[[ Justify Module ]]-- local _, BCM = ... BCM.modules[#BCM.modules+1] = function() if bcmDB.BCM_Justify then bcmDB.justify = nil return end if bcmDB.justify then local noDel for k, v in pairs(bcmDB.justify) do _G[k]:SetJustifyH(v) noDel = true end if not noDel then bcmDB.justify = nil end --Cleanup db end end
local mg = require "moongen" local memory = require "memory" local device = require "device" local stats = require "stats" local log = require "log" function configure(parser) parser:description("Generates TCP SYN flood from varying source IPs, supports both IPv4 and IPv6") parser:argument("dev", "Devices to transmit from."):args("*"):convert(tonumber) parser:option("-r --rate", "Transmit rate in Mbit/s."):default(10000):convert(tonumber) parser:option("-i --ip", "Source IP (IPv4 or IPv6)."):default("10.0.0.1") parser:option("-d --destination", "Destination IP (IPv4 or IPv6).") parser:option("-f --flows", "Number of different IPs to use."):default(100):convert(tonumber) end function master(args) for i, dev in ipairs(args.dev) do local dev = device.config{port = dev} dev:wait() dev:getTxQueue(0):setRate(args.rate) mg.startTask("loadSlave", dev:getTxQueue(0), args.ip, args.flows, args.destination) end mg.waitForTasks() end function loadSlave(queue, minA, numIPs, dest) --- parse and check ip addresses local minIP, ipv4 = parseIPAddress(minA) if minIP then log:info("Detected an %s address.", minIP and "IPv4" or "IPv6") else log:fatal("Invalid minIP: %s", minA) end -- min TCP packet size for IPv6 is 74 bytes (+ CRC) local packetLen = ipv4 and 60 or 74 -- continue normally local mem = memory.createMemPool(function(buf) buf:getTcpPacket(ipv4):fill{ ethSrc = queue, ethDst = "12:34:56:78:90", ip4Dst = dest, ip6Dst = dest, tcpSyn = 1, tcpSeqNumber = 1, tcpWindow = 10, pktLength = packetLen } end) local bufs = mem:bufArray(128) local counter = 0 local c = 0 local txStats = stats:newDevTxCounter(queue, "plain") while mg.running() do -- fill packets and set their size bufs:alloc(packetLen) for i, buf in ipairs(bufs) do local pkt = buf:getTcpPacket(ipv4) --increment IP if ipv4 then pkt.ip4.src:set(minIP) pkt.ip4.src:add(counter) else pkt.ip6.src:set(minIP) pkt.ip6.src:add(counter) end counter = incAndWrap(counter, numIPs) -- dump first 3 packets if c < 3 then buf:dump() c = c + 1 end end --offload checksums to NIC bufs:offloadTcpChecksums(ipv4) queue:send(bufs) txStats:update() end txStats:finalize() end
local CemeteryModule = require "module.CemeteryModule" local MapConfig = require "config.MapConfig" local SmallTeamDungeonConf = require "config.SmallTeamDungeonConf" local View = {} function View:Start(data) self.view = CS.SGK.UIReference.Setup(self.gameObject) self.IsShow = false self.descArr = {} self.view.bg.desc.open[CS.UGUIClickEventListener].onClick = function ( ... ) self.IsShow = not self.IsShow self.view.bg.desc.open.transform.localEulerAngles = self.IsShow and Vector3(0,0,180) or Vector3.zero self:ShowDesc(self.descArr) end self:RefUI() end function View:RefUI() local descArr = {} local activityid = CemeteryModule.Getactivityid() for k,v in pairs(SmallTeamDungeonConf.GetTeam_pve_fight(activityid).idx) do for i = 1,#v do if CemeteryModule.GetTEAMRecord(v[i].gid) > 0 then local conf = SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid) if not descArr[conf.sequence] then descArr[conf.sequence] = {} end descArr[conf.sequence][#descArr[conf.sequence]+1] = SmallTeamDungeonConf.GetTeam_pve_fight_gid(v[i].gid) end end end self:ShowDesc(descArr) self.descArr = descArr end function View:ShowDesc(descArr) local desc = "" local Count = 0 for i = 1,#descArr do for j = 1,#descArr[i] do if Count == 2 and self.IsShow == false then break end if desc == "" then desc = descArr[i][j].win_des else desc = desc.."\n"..descArr[i][j].win_des end Count = Count + 1 end end self.view.bg:SetActive(desc ~= "") self.view.bg.desc[UnityEngine.UI.Text].text = desc end function View:onEvent(event, data) if event == "update_monster_schedule" then self:RefUI() end end function View:OnDestroy( ... ) DialogStack.Destroy("PveSchedule") end function View:listEvent() return{ "update_monster_schedule", } end return View
-- -- Author: [email protected] -- Date: 2015-12-02 15:35:49 -- BehaviorTree3 init && require lua file b3 = {} b3.Com = require('cocos.framework.BehaviorTree3.Com') --core b3.BaseNode = require('cocos.framework.BehaviorTree3.Core.BaseNode') b3.Action = require('cocos.framework.BehaviorTree3.Core.Action') b3.Decorator = require('cocos.framework.BehaviorTree3.Core.Decorator') b3.Condition = require('cocos.framework.BehaviorTree3.Core.Condition') b3.Composite = require('cocos.framework.BehaviorTree3.Core.Composite') b3.BehaviorTree = require('cocos.framework.BehaviorTree3.Core.BehaviorTree') b3.Blackborad = require('cocos.framework.BehaviorTree3.Core.Blackborad') b3.Tick = require('cocos.framework.BehaviorTree3.Core.Tick') --Action b3.Error = require('cocos.framework.BehaviorTree3.Actions.Error') b3.Failer = require('cocos.framework.BehaviorTree3.Actions.Failer') b3.Runner = require('cocos.framework.BehaviorTree3.Actions.Runner') b3.Succeeder = require('cocos.framework.BehaviorTree3.Actions.Succeeder') b3.Wait = require('cocos.framework.BehaviorTree3.Actions.Wait') --Composites b3.Sequence = require('cocos.framework.BehaviorTree3.Composites.Sequence') b3.Priority = require('cocos.framework.BehaviorTree3.Composites.Priority') b3.MemSequence = require('cocos.framework.BehaviorTree3.Composites.MemSequence') b3.MemPriority = require('cocos.framework.BehaviorTree3.Composites.MemPriority') b3.WeightSelector = require('cocos.framework.BehaviorTree3.Composites.WeightSelector') --Decorators b3.Inverter = require('cocos.framework.BehaviorTree3.Decorators.Inverter') b3.Limiter = require('cocos.framework.BehaviorTree3.Decorators.Limiter') b3.MaxTime = require('cocos.framework.BehaviorTree3.Decorators.MaxTime') b3.Repeater = require('cocos.framework.BehaviorTree3.Decorators.Repeater') b3.RepeatUntilFailure = require('cocos.framework.BehaviorTree3.Decorators.RepeatUntilFailure') b3.RepeatUntilSuccess = require('cocos.framework.BehaviorTree3.Decorators.RepeatUntilSuccess')
local module = {} module.__index = module local signal = require(game:GetService('ReplicatedStorage').Common.Signal) function module:Make(key, new) local info = { value = new, changed = signal.new() } self.data[key] = info return info end function module:GetInfo(key) local info = self.data[key] return info or self:Make(key) end function module:GetChangedSignal(key) local info = self:GetInfo(key) return info.changed end function module:Set(key, value) local info = self:GetInfo(key) if value == nil then self.data[key] = nil return end info.value = value info.changed:Fire(value) end function module:Get(key) local info = self.data[key] return info and info.value end function module.new(current) if not current then return end local meta = setmetatable({ data = {} }, module) for key, value in pairs(current) do meta:Make(key, value) end return meta end function module:Destroy() for key in pairs(self.data) do self[key] = nil end end return module
local input = require('core/input') input:right(101638) input:down(101639) input:down(101641) input:down(101643) input:down(101645) input:cross(101646) input:cross(101904) return input:all()
local ffi = require"ffi" local cdecl = require"imgui.cdefs" local ffi_cdef = function(code) local ret,err = pcall(ffi.cdef,code) if not ret then local lineN = 1 for line in code:gmatch("([^\n\r]*)\r?\n") do print(lineN, line) lineN = lineN + 1 end print(err) error"bad cdef" end end assert(cdecl, "imgui.lua not properly build") ffi.cdef(cdecl) --load dll local lib = ffi.load(cimguimodule) -----------ImStr definition local ImStrv if pcall(function() local a = ffi.new("ImStrv")end) then ImStrv= {} function ImStrv.__new(ctype,a,b) b = b or ffi.new("const char*",a) + (a and #a or 0) return ffi.new(ctype,a,b) end function ImStrv.__tostring(is) return is.Begin~=nil and ffi.string(is.Begin,is.End~=nil and is.End-is.Begin or nil) or nil end ImStrv.__index = ImStrv ImStrv = ffi.metatype("ImStrv",ImStrv) end -----------ImVec2 definition local ImVec2 ImVec2 = { __add = function(a,b) return ImVec2(a.x + b.x, a.y + b.y) end, __sub = function(a,b) return ImVec2(a.x - b.x, a.y - b.y) end, __unm = function(a) return ImVec2(-a.x,-a.y) end, __mul = function(a, b) --scalar mult if not ffi.istype(ImVec2, b) then return ImVec2(a.x * b, a.y * b) end return ImVec2(a * b.x, a * b.y) end, norm = function(a) return math.sqrt(a.x*a.x+a.y*a.y) end, __tostring = function(v) return 'ImVec2<'..v.x..','..v.y..'>' end } ImVec2.__index = ImVec2 ImVec2 = ffi.metatype("ImVec2",ImVec2) local ImVec4= {} ImVec4.__index = ImVec4 ImVec4 = ffi.metatype("ImVec4",ImVec4) --the module local M = {ImVec2 = ImVec2, ImVec4 = ImVec4 , ImStrv = ImStrv, lib = lib} if jit.os == "Windows" then function M.ToUTF(unc_str) local buf_len = lib.igImTextCountUtf8BytesFromStr(unc_str, nil) + 1; local buf_local = ffi.new("char[?]",buf_len) lib.igImTextStrToUtf8(buf_local, buf_len, unc_str, nil); return buf_local end function M.FromUTF(utf_str) local wbuf_length = lib.igImTextCountCharsFromUtf8(utf_str, nil) + 1; local buf_local = ffi.new("ImWchar[?]",wbuf_length) lib.igImTextStrFromUtf8(buf_local, wbuf_length, utf_str, nil,nil); return buf_local end end M.FLT_MAX = lib.igGET_FLT_MAX() M.FLT_MIN = lib.igGET_FLT_MIN() -----------ImGui_ImplGlfwGL3 local ImGui_ImplGlfwGL3 = {} ImGui_ImplGlfwGL3.__index = ImGui_ImplGlfwGL3 local gl3w_inited = false function ImGui_ImplGlfwGL3.__new() if gl3w_inited == false then lib.Do_gl3wInit() gl3w_inited = true end local ptr = lib.ImGui_ImplGlfwGL3_new() ffi.gc(ptr,lib.ImGui_ImplGlfwGL3_delete) return ptr end function ImGui_ImplGlfwGL3:destroy() ffi.gc(self,nil) --prevent gc twice lib.ImGui_ImplGlfwGL3_delete(self) end function ImGui_ImplGlfwGL3:NewFrame() return lib.ImGui_ImplGlfwGL3_NewFrame(self) end function ImGui_ImplGlfwGL3:Render() return lib.ImGui_ImplGlfwGL3_Render(self) end function ImGui_ImplGlfwGL3:Init(window, install_callbacks) return lib.ImGui_ImplGlfwGL3_Init(self, window,install_callbacks); end function ImGui_ImplGlfwGL3.KeyCallback(window, key,scancode, action, mods) return lib.ImGui_ImplGlfwGL3_KeyCallback(window, key,scancode, action, mods); end function ImGui_ImplGlfwGL3.MouseButtonCallback(win, button, action, mods) return lib.ImGui_ImplGlfwGL3_MouseButtonCallback(win, button, action, mods) end function ImGui_ImplGlfwGL3.ScrollCallback(window,xoffset,yoffset) return lib.ImGui_ImplGlfwGL3_MouseButtonCallback(window,xoffset,yoffset) end function ImGui_ImplGlfwGL3.CharCallback(window,c) return lib.ImGui_ImplGlfwGL3_CharCallback(window, c); end M.ImplGlfwGL3 = ffi.metatype("ImGui_ImplGlfwGL3",ImGui_ImplGlfwGL3) -----------------------Imgui_Impl_SDL_opengl3 local Imgui_Impl_SDL_opengl3 = {} Imgui_Impl_SDL_opengl3.__index = Imgui_Impl_SDL_opengl3 function Imgui_Impl_SDL_opengl3.__call() if gl3w_inited == false then lib.Do_gl3wInit() gl3w_inited = true end return setmetatable({ctx = lib.igCreateContext(nil)},Imgui_Impl_SDL_opengl3) end function Imgui_Impl_SDL_opengl3:Init(window, gl_context, glsl_version) self.window = window glsl_version = glsl_version or "#version 130" lib.ImGui_ImplSDL2_InitForOpenGL(window, gl_context); lib.ImGui_ImplOpenGL3_Init(glsl_version); end function Imgui_Impl_SDL_opengl3:destroy() lib.ImGui_ImplOpenGL3_Shutdown(); lib.ImGui_ImplSDL2_Shutdown(); lib.igDestroyContext(self.ctx); end function Imgui_Impl_SDL_opengl3:NewFrame() lib.ImGui_ImplOpenGL3_NewFrame(); lib.ImGui_ImplSDL2_NewFrame(); lib.igNewFrame(); end function Imgui_Impl_SDL_opengl3:Render() lib.igRender() lib.ImGui_ImplOpenGL3_RenderDrawData(lib.igGetDrawData()); end M.Imgui_Impl_SDL_opengl3 = setmetatable({},Imgui_Impl_SDL_opengl3) -----------------------Imgui_Impl_SDL_opengl2 local Imgui_Impl_SDL_opengl2 = {} Imgui_Impl_SDL_opengl2.__index = Imgui_Impl_SDL_opengl2 function Imgui_Impl_SDL_opengl2.__call() return setmetatable({ctx = lib.igCreateContext(nil)},Imgui_Impl_SDL_opengl2) end function Imgui_Impl_SDL_opengl2:Init(window, gl_context) self.window = window lib.ImGui_ImplSDL2_InitForOpenGL(window, gl_context); lib.ImGui_ImplOpenGL2_Init(); end function Imgui_Impl_SDL_opengl2:destroy() lib.ImGui_ImplOpenGL2_Shutdown(); lib.ImGui_ImplSDL2_Shutdown(); lib.igDestroyContext(self.ctx); end function Imgui_Impl_SDL_opengl2:NewFrame() lib.ImGui_ImplOpenGL2_NewFrame(); lib.ImGui_ImplSDL2_NewFrame(); lib.igNewFrame(); end function Imgui_Impl_SDL_opengl2:Render() lib.igRender() lib.ImGui_ImplOpenGL2_RenderDrawData(lib.igGetDrawData()); end M.Imgui_Impl_SDL_opengl2 = setmetatable({},Imgui_Impl_SDL_opengl2) -----------------------Imgui_Impl_glfw_opengl3 local Imgui_Impl_glfw_opengl3 = {} Imgui_Impl_glfw_opengl3.__index = Imgui_Impl_glfw_opengl3 function Imgui_Impl_glfw_opengl3.__call() if gl3w_inited == false then lib.Do_gl3wInit() gl3w_inited = true end return setmetatable({ctx = lib.igCreateContext(nil)},Imgui_Impl_glfw_opengl3) end function Imgui_Impl_glfw_opengl3:Init(window, install_callbacks,glsl_version) glsl_version = glsl_version or "#version 130" lib.ImGui_ImplGlfw_InitForOpenGL(window, install_callbacks); lib.ImGui_ImplOpenGL3_Init(glsl_version); end function Imgui_Impl_glfw_opengl3:destroy() lib.ImGui_ImplOpenGL3_Shutdown(); lib.ImGui_ImplGlfw_Shutdown(); lib.igDestroyContext(self.ctx); end function Imgui_Impl_glfw_opengl3:NewFrame() lib.ImGui_ImplOpenGL3_NewFrame(); lib.ImGui_ImplGlfw_NewFrame(); lib.igNewFrame(); end function Imgui_Impl_glfw_opengl3:Render() lib.igRender() lib.ImGui_ImplOpenGL3_RenderDrawData(lib.igGetDrawData()); end function Imgui_Impl_glfw_opengl3.KeyCallback(window, key,scancode, action, mods) return lib.ImGui_ImplGlfw_KeyCallback(window, key,scancode, action, mods); end function Imgui_Impl_glfw_opengl3.MouseButtonCallback(win, button, action, mods) return lib.ImGui_ImplGlfw_MouseButtonCallback(win, button, action, mods) end function Imgui_Impl_glfw_opengl3.ScrollCallback(window,xoffset,yoffset) return lib.ImGui_ImplGlfw_ScrollCallback(window,xoffset,yoffset) end function Imgui_Impl_glfw_opengl3.CharCallback(window,c) return lib.ImGui_ImplGlfw_CharCallback(window, c); end M.Imgui_Impl_glfw_opengl3 = setmetatable({},Imgui_Impl_glfw_opengl3) -----------------------Imgui_Impl_glfw_opengl2 local Imgui_Impl_glfw_opengl2 = {} Imgui_Impl_glfw_opengl2.__index = Imgui_Impl_glfw_opengl2 function Imgui_Impl_glfw_opengl2.__call() return setmetatable({ctx = lib.igCreateContext(nil)},Imgui_Impl_glfw_opengl2) end function Imgui_Impl_glfw_opengl2:Init(window, install_callbacks) lib.ImGui_ImplGlfw_InitForOpenGL(window, install_callbacks); lib.ImGui_ImplOpenGL2_Init(); end function Imgui_Impl_glfw_opengl2:destroy() lib.ImGui_ImplOpenGL2_Shutdown(); lib.ImGui_ImplGlfw_Shutdown(); lib.igDestroyContext(self.ctx); end function Imgui_Impl_glfw_opengl2:NewFrame() lib.ImGui_ImplOpenGL2_NewFrame(); lib.ImGui_ImplGlfw_NewFrame(); lib.igNewFrame(); end function Imgui_Impl_glfw_opengl2:Render() lib.igRender() lib.ImGui_ImplOpenGL2_RenderDrawData(lib.igGetDrawData()); end function Imgui_Impl_glfw_opengl2.KeyCallback(window, key,scancode, action, mods) return lib.ImGui_ImplGlfw_KeyCallback(window, key,scancode, action, mods); end function Imgui_Impl_glfw_opengl2.MouseButtonCallback(win, button, action, mods) return lib.ImGui_ImplGlfw_MouseButtonCallback(win, button, action, mods) end function Imgui_Impl_glfw_opengl2.ScrollCallback(window,xoffset,yoffset) return lib.ImGui_ImplGlfw_ScrollCallback(window,xoffset,yoffset) end function Imgui_Impl_glfw_opengl2.CharCallback(window,c) return lib.ImGui_ImplGlfw_CharCallback(window, c); end M.Imgui_Impl_glfw_opengl2 = setmetatable({},Imgui_Impl_glfw_opengl2) -----------------------another Log local Log = {} Log.__index = Log function Log.__new() local ptr = lib.Log_new() ffi.gc(ptr,lib.Log_delete) return ptr end function Log:Add(fmt,...) lib.Log_Add(self,fmt,...) end function Log:Draw(title) title = title or "Log" lib.Log_Draw(self,title) end M.Log = ffi.metatype("Log",Log) ------------convenience function function M.U32(a,b,c,d) return lib.igGetColorU32_Vec4(ImVec4(a,b,c,d or 1)) end -------------ImGuiZMO.quat function M.mat4_cast(q) local nonUDT_out = ffi.new("Mat4") lib.mat4_cast(q,nonUDT_out) return nonUDT_out end function M.mat4_pos_cast(q,pos) local nonUDT_out = ffi.new("Mat4") lib.mat4_pos_cast(q,pos,nonUDT_out) return nonUDT_out end function M.quat_cast(f) local nonUDT_out = ffi.new("quat") lib.quat_cast(f,nonUDT_out) return nonUDT_out end function M.quat_pos_cast(f) local nonUDT_out = ffi.new("quat") local nonUDT_pos = ffi.new("G3Dvec3") lib.quat_pos_cast(f,nonUDT_out,nonUDT_pos) return nonUDT_out,nonUDT_pos end --------------- several widgets------------ local sin, cos, atan2, pi, max, min,acos,sqrt = math.sin, math.cos, math.atan2, math.pi, math.max, math.min,math.acos,math.sqrt function M.dial(label,value_p,sz, fac) fac = fac or 1 sz = sz or 20 local style = M.GetStyle() local p = M.GetCursorScreenPos(); local radio = sz*0.5 local center = M.ImVec2(p.x + radio, p.y + radio) local x2 = cos(value_p[0]/fac)*radio + center.x local y2 = sin(value_p[0]/fac)*radio + center.y M.InvisibleButton(label.."t",M.ImVec2(sz, sz)) local is_active = M.IsItemActive() local is_hovered = M.IsItemHovered() local touched = false if is_active then touched = true local m = M.GetIO().MousePos local md = M.GetIO().MouseDelta if md.x == 0 and md.y == 0 then touched=false end local mp = M.ImVec2(m.x - md.x, m.y - md.y) local ax = mp.x - center.x local ay = mp.y - center.y local bx = m.x - center.x local by = m.y - center.y local ma = sqrt(ax*ax + ay*ay) local mb = sqrt(bx*bx + by*by) local ab = ax * bx + ay * by; local vet = ax * by - bx * ay; ab = ab / (ma * mb); if not (ma == 0 or mb == 0 or ab < -1 or ab > 1) then if (vet>0) then value_p[0] = value_p[0] + acos(ab)*fac; else value_p[0] = value_p[0] - acos(ab)*fac; end end end local col32idx = is_active and lib.ImGuiCol_FrameBgActive or (is_hovered and lib.ImGuiCol_FrameBgHovered or lib.ImGuiCol_FrameBg) local col32 = M.GetColorU32(col32idx, 1) local col32line = M.GetColorU32(lib.ImGuiCol_SliderGrabActive, 1) local draw_list = M.GetWindowDrawList(); draw_list:AddCircleFilled( center, radio, col32, 16); draw_list:AddLine( center, M.ImVec2(x2, y2), col32line, 1); M.SameLine() M.PushItemWidth(50) if M.InputFloat(label, value_p, 0.0, 0.1) then touched = true end M.PopItemWidth() return touched end function M.Curve(name,numpoints,LUTsize,pressed_on_modified) if pressed_on_modified == nil then pressed_on_modified=true end numpoints = numpoints or 10 LUTsize = LUTsize or 720 local CU = {name = name,numpoints=numpoints,LUTsize=LUTsize} CU.LUT = ffi.new("float[?]",LUTsize) CU.LUT[0] = -1 CU.points = ffi.new("ImVec2[?]",numpoints) CU.points[0].x = -1 function CU:getpoints() local pts = {} for i=0,numpoints-1 do pts[i+1] = {x=CU.points[i].x,y=CU.points[i].y} end return pts end function CU:setpoints(pts) assert(#pts<=numpoints) for i=1,#pts do CU.points[i-1].x = pts[i].x CU.points[i-1].y = pts[i].y end CU.LUT[0] = -1 lib.CurveGetData(CU.points, numpoints,CU.LUT, LUTsize ) end function CU:get_data() CU.LUT[0] = -1 lib.CurveGetData(CU.points, numpoints,CU.LUT, LUTsize ) end function CU:draw(sz) sz = sz or M.ImVec2(200,200) return lib.Curve(name, sz,CU.points, CU.numpoints,CU.LUT, CU.LUTsize,pressed_on_modified) end return CU end function M.pad(label,value,sz) local function clip(val,mini,maxi) return math.min(maxi,math.max(mini,val)) end sz = sz or 200 local canvas_pos = M.GetCursorScreenPos(); M.InvisibleButton(label.."t",M.ImVec2(sz, sz)) -- + style.ItemInnerSpacing.y)) local is_active = M.IsItemActive() local is_hovered = M.IsItemHovered() local touched = false if is_active then touched = true local m = M.GetIO().MousePos local md = M.GetIO().MouseDelta if md.x == 0 and md.y == 0 and not M.IsMouseClicked(0,false) then touched=false end value[0] = ((m.x - canvas_pos.x)/sz)*2 - 1 value[1] = (1.0 - (m.y - canvas_pos.y)/sz)*2 - 1 value[0] = clip(value[0], -1,1) value[1] = clip(value[1], -1,1) end local draw_list = M.GetWindowDrawList(); draw_list:AddRect(canvas_pos,canvas_pos+M.ImVec2(sz,sz),M.U32(1,0,0,1)) draw_list:AddLine(canvas_pos + M.ImVec2(0,sz/2),canvas_pos + M.ImVec2(sz,sz/2) ,M.U32(1,0,0,1)) draw_list:AddLine(canvas_pos + M.ImVec2(sz/2,0),canvas_pos + M.ImVec2(sz/2,sz) ,M.U32(1,0,0,1)) draw_list:AddCircleFilled(canvas_pos + M.ImVec2((1+value[0])*sz,((1-value[1])*sz)+1)*0.5,5,M.U32(1,0,0,1)) return touched end function M.Plotter(xmin,xmax,nvals) local Graph = {xmin=xmin or 0,xmax=xmax or 1,nvals=nvals or 400} function Graph:init() self.values = ffi.new("float[?]",self.nvals) end function Graph:itox(i) return self.xmin + i/(self.nvals-1)*(self.xmax-self.xmin) end function Graph:calc(func,ymin1,ymax1) local vmin = math.huge local vmax = -math.huge for i=0,self.nvals-1 do self.values[i] = func(self:itox(i)) vmin = (vmin < self.values[i]) and vmin or self.values[i] vmax = (vmax > self.values[i]) and vmax or self.values[i] end self.ymin = ymin1 or vmin self.ymax = ymax1 or vmax end function Graph:draw() local regionsize = M.GetContentRegionAvail() local desiredY = regionsize.y - M.GetFrameHeightWithSpacing() M.PushItemWidth(-1) M.PlotLines("##grafica",self.values,self.nvals,nil,nil,self.ymin,self.ymax,M.ImVec2(0,desiredY)) local p = M.GetCursorScreenPos() p.y = p.y - M.GetStyle().FramePadding.y local w = M.CalcItemWidth() self.origin = p self.size = M.ImVec2(w,desiredY) local draw_list = M.GetWindowDrawList() for i=0,4 do local ylab = i*desiredY/4 --+ M.GetStyle().FramePadding.y draw_list:AddLine(M.ImVec2(p.x, p.y - ylab), M.ImVec2(p.x + w,p.y - ylab), M.U32(1,0,0,1)) local valy = self.ymin + (self.ymax - self.ymin)*i/4 local labelY = string.format("%0.3f",valy) -- - M.CalcTextSize(labelY).x draw_list:AddText(M.ImVec2(p.x , p.y -ylab), M.U32(0,1,0,1),labelY) end for i=0,10 do local xlab = i*w/10 draw_list:AddLine(M.ImVec2(p.x + xlab,p.y), M.ImVec2(p.x + xlab,p.y - desiredY), M.U32(1,0,0,1)) local valx = self:itox(i/10*(self.nvals -1)) draw_list:AddText(M.ImVec2(p.x + xlab,p.y + 2), M.U32(0,1,0,1),string.format("%0.3f",valx)) end M.PopItemWidth() return w,desiredY end Graph:init() return Graph end
--lune/base/Import.lns local _moduleObj = {} local __mod__ = '@lune.@base.@Import' local _lune = {} if _lune6 then _lune = _lune6 end function _lune._Set_or( setObj, otherSet ) for val in pairs( otherSet ) do setObj[ val ] = true end return setObj end function _lune._Set_and( setObj, otherSet ) local delValList = {} for val in pairs( setObj ) do if not otherSet[ val ] then table.insert( delValList, val ) end end for index, val in ipairs( delValList ) do setObj[ val ] = nil end return setObj end function _lune._Set_has( setObj, val ) return setObj[ val ] ~= nil end function _lune._Set_sub( setObj, otherSet ) local delValList = {} for val in pairs( setObj ) do if otherSet[ val ] then table.insert( delValList, val ) end end for index, val in ipairs( delValList ) do setObj[ val ] = nil end return setObj end function _lune._Set_len( setObj ) local total = 0 for val in pairs( setObj ) do total = total + 1 end return total end function _lune._Set_clone( setObj ) local obj = {} for val in pairs( setObj ) do obj[ val ] = true end return obj end function _lune._toSet( val, toKeyInfo ) if type( val ) == "table" then local tbl = {} for key, mem in pairs( val ) do local mapKey, keySub = toKeyInfo.func( key, toKeyInfo.child ) local mapVal = _lune._toBool( mem ) if mapKey == nil or mapVal == nil then if mapKey == nil then return nil end if keySub == nil then return nil, mapKey end return nil, string.format( "%s.%s", mapKey, keySub) end tbl[ mapKey ] = mapVal end return tbl end return nil end function _lune.nilacc( val, fieldName, access, ... ) if not val then return nil end if fieldName then local field = val[ fieldName ] if not field then return nil end if access == "item" then local typeId = type( field ) if typeId == "table" then return field[ ... ] elseif typeId == "string" then return string.byte( field, ... ) end elseif access == "call" then return field( ... ) elseif access == "callmtd" then return field( val, ... ) end return field end if access == "item" then local typeId = type( val ) if typeId == "table" then return val[ ... ] elseif typeId == "string" then return string.byte( val, ... ) end elseif access == "call" then return val( ... ) elseif access == "list" then local list, arg = ... if not list then return nil end return val( list, arg ) end error( string.format( "illegal access -- %s", access ) ) end function _lune.unwrap( val ) if val == nil then __luneScript:error( 'unwrap val is nil' ) end return val end function _lune.unwrapDefault( val, defval ) if val == nil then return defval end return val end function _lune._toStem( val ) return val end function _lune._toInt( val ) if type( val ) == "number" then return math.floor( val ) end return nil end function _lune._toReal( val ) if type( val ) == "number" then return val end return nil end function _lune._toBool( val ) if type( val ) == "boolean" then return val end return nil end function _lune._toStr( val ) if type( val ) == "string" then return val end return nil end function _lune._toList( val, toValInfoList ) if type( val ) == "table" then local tbl = {} local toValInfo = toValInfoList[ 1 ] for index, mem in ipairs( val ) do local memval, mess = toValInfo.func( mem, toValInfo.child ) if memval == nil and not toValInfo.nilable then if mess then return nil, string.format( "%d.%s", index, mess ) end return nil, index end tbl[ index ] = memval end return tbl end return nil end function _lune._toMap( val, toValInfoList ) if type( val ) == "table" then local tbl = {} local toKeyInfo = toValInfoList[ 1 ] local toValInfo = toValInfoList[ 2 ] for key, mem in pairs( val ) do local mapKey, keySub = toKeyInfo.func( key, toKeyInfo.child ) local mapVal, valSub = toValInfo.func( mem, toValInfo.child ) if mapKey == nil or mapVal == nil then if mapKey == nil then return nil end if keySub == nil then return nil, mapKey end return nil, string.format( "%s.%s", mapKey, keySub) end tbl[ mapKey ] = mapVal end return tbl end return nil end function _lune._fromMap( obj, map, memInfoList ) if type( map ) ~= "table" then return false end for index, memInfo in ipairs( memInfoList ) do local val, key = memInfo.func( map[ memInfo.name ], memInfo.child ) if val == nil and not memInfo.nilable then return false, key and string.format( "%s.%s", memInfo.name, key) or memInfo.name end obj[ memInfo.name ] = val end return true end function _lune.loadModule( mod ) if __luneScript then return __luneScript:loadModule( mod ) end return require( mod ) end function _lune.__isInstanceOf( obj, class ) while obj do local meta = getmetatable( obj ) if not meta then return false end local indexTbl = meta.__index if indexTbl == class then return true end if meta.ifList then for index, ifType in ipairs( meta.ifList ) do if ifType == class then return true end if _lune.__isInstanceOf( ifType, class ) then return true end end end obj = indexTbl end return false end function _lune.__Cast( obj, kind, class ) if kind == 0 then -- int if type( obj ) ~= "number" then return nil end if math.floor( obj ) ~= obj then return nil end return obj elseif kind == 1 then -- real if type( obj ) ~= "number" then return nil end return obj elseif kind == 2 then -- str if type( obj ) ~= "string" then return nil end return obj elseif kind == 3 then -- class return _lune.__isInstanceOf( obj, class ) and obj or nil end return nil end if not _lune6 then _lune6 = _lune end local Types = _lune.loadModule( 'lune.base.Types' ) local Meta = _lune.loadModule( 'lune.base.Meta' ) local Parser = _lune.loadModule( 'lune.base.Parser' ) local Util = _lune.loadModule( 'lune.base.Util' ) local Ast = _lune.loadModule( 'lune.base.Ast' ) local Macro = _lune.loadModule( 'lune.base.Macro' ) local Nodes = _lune.loadModule( 'lune.base.Nodes' ) local frontInterface = _lune.loadModule( 'lune.base.frontInterface' ) local Log = _lune.loadModule( 'lune.base.Log' ) local Runner = _lune.loadModule( 'lune.base.Runner' ) local TransUnitIF = _lune.loadModule( 'lune.base.TransUnitIF' ) local ModuleLoader = {} local _TypeInfo = {} local ImportParam = {} function ImportParam.setmeta( obj ) setmetatable( obj, { __index = ImportParam } ) end function ImportParam.new( pos, modifier, processInfo, typeId2Scope, typeId2TypeInfo, typeId2TypeDataAccessor, importedAliasMap, lazyModuleSet, metaInfo, scope, moduleTypeInfo, scopeAccess, typeId2AtomMap, dependLibId2DependInfo ) local obj = {} ImportParam.setmeta( obj ) if obj.__init then obj:__init( pos, modifier, processInfo, typeId2Scope, typeId2TypeInfo, typeId2TypeDataAccessor, importedAliasMap, lazyModuleSet, metaInfo, scope, moduleTypeInfo, scopeAccess, typeId2AtomMap, dependLibId2DependInfo ) end return obj end function ImportParam:__init( pos, modifier, processInfo, typeId2Scope, typeId2TypeInfo, typeId2TypeDataAccessor, importedAliasMap, lazyModuleSet, metaInfo, scope, moduleTypeInfo, scopeAccess, typeId2AtomMap, dependLibId2DependInfo ) self.pos = pos self.modifier = modifier self.processInfo = processInfo self.typeId2Scope = typeId2Scope self.typeId2TypeInfo = typeId2TypeInfo self.typeId2TypeDataAccessor = typeId2TypeDataAccessor self.importedAliasMap = importedAliasMap self.lazyModuleSet = lazyModuleSet self.metaInfo = metaInfo self.scope = scope self.moduleTypeInfo = moduleTypeInfo self.scopeAccess = scopeAccess self.typeId2AtomMap = typeId2AtomMap self.dependLibId2DependInfo = dependLibId2DependInfo end setmetatable( _TypeInfo, { ifList = {Mapping,} } ) function _TypeInfo.new( ) local obj = {} _TypeInfo.setmeta( obj ) if obj.__init then obj:__init( ); end return obj end function _TypeInfo:__init() self.typeId = Ast.userRootId self.skind = Ast.SerializeKind.Normal end function _TypeInfo:createTypeInfoCache( param ) do local typeInfo = param.typeId2TypeInfo[self.typeId] if typeInfo ~= nil then return typeInfo, nil end end local typeInfo, mess = self:createTypeInfo( param ) if typeInfo ~= nil then param.typeId2TypeInfo[self.typeId] = typeInfo typeInfo:get_typeId():set_orgId( self.typeId ) end return typeInfo, mess end function _TypeInfo.setmeta( obj ) setmetatable( obj, { __index = _TypeInfo } ) end function _TypeInfo:_toMap() return self end function _TypeInfo._fromMap( val ) local obj, mes = _TypeInfo._fromMapSub( {}, val ) if obj then _TypeInfo.setmeta( obj ) end return obj, mes end function _TypeInfo._fromStem( val ) return _TypeInfo._fromMap( val ) end function _TypeInfo._fromMapSub( obj, val ) local memInfo = {} table.insert( memInfo, { name = "skind", func = Ast.SerializeKind._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "typeId", func = _lune._toInt, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end function ImportParam:getTypeInfo( typeId ) do local typeInfo = self.typeId2TypeInfo[typeId] if typeInfo ~= nil then return typeInfo, nil end end do local atom = self.typeId2AtomMap[typeId] if atom ~= nil then local typeInfo, mess = atom:createTypeInfoCache( self ) if typeInfo ~= nil then self.typeId2TypeInfo[typeId] = typeInfo end return typeInfo, mess end end return nil, nil end function ImportParam:getTypeDataAccessor( typeId ) local typeInfo, mess = self:getTypeInfo( typeId ) if typeInfo ~= nil then local typeDataAccessor = self.typeId2TypeDataAccessor[typeId] if nil == typeDataAccessor then local _typeDataAccessor = typeDataAccessor Util.err( string.format( "not found TypeDataAccessor for %d: %s", typeId, typeInfo:getTxt( )) ) end return typeDataAccessor, typeInfo end Util.err( string.format( "not found TypeDataAccessor for %d: %s", typeId, mess or "") ) end local _IdInfo = {} setmetatable( _IdInfo, { ifList = {Mapping,} } ) function _IdInfo.setmeta( obj ) setmetatable( obj, { __index = _IdInfo } ) end function _IdInfo.new( id, mod ) local obj = {} _IdInfo.setmeta( obj ) if obj.__init then obj:__init( id, mod ) end return obj end function _IdInfo:__init( id, mod ) self.id = id self.mod = mod end function _IdInfo:_toMap() return self end function _IdInfo._fromMap( val ) local obj, mes = _IdInfo._fromMapSub( {}, val ) if obj then _IdInfo.setmeta( obj ) end return obj, mes end function _IdInfo._fromStem( val ) return _IdInfo._fromMap( val ) end function _IdInfo._fromMapSub( obj, val ) local memInfo = {} table.insert( memInfo, { name = "id", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "mod", func = _lune._toInt, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end function ImportParam:getTypeInfoFrom( typeId ) if typeId.mod == 0 then return self:getTypeInfo( typeId.id ) end if typeId.mod == frontInterface.getRootDependModId( ) then return Ast.getRootProcessInfoRo( ):getTypeInfo( typeId.id ), nil end local exportInfo = self.dependLibId2DependInfo[typeId.mod] if nil == exportInfo then local _exportInfo = exportInfo Util.err( string.format( "%s, %d, %d", self.moduleTypeInfo:getTxt( ), typeId.mod, typeId.id) ) end do local typeInfo = exportInfo:get_importId2localTypeInfoMap()[typeId.id] if typeInfo ~= nil then return typeInfo, nil end end do local typeInfo = exportInfo:get_processInfo():getTypeInfo( typeId.id ) if typeInfo ~= nil then return typeInfo, nil end end return nil, string.format( "not found type -- %s, %d, %d", self.moduleTypeInfo:getTxt( ), typeId.mod, typeId.id) end local _TypeInfoNilable = {} setmetatable( _TypeInfoNilable, { __index = _TypeInfo } ) function _TypeInfoNilable:createTypeInfo( param ) local orgTypeInfo = param:getTypeInfoFrom( self.orgTypeId ) if nil == orgTypeInfo then local _orgTypeInfo = orgTypeInfo Util.err( string.format( "failed to createTypeInfo -- self.orgTypeId = (%d,%d)", self.orgTypeId.mod, self.orgTypeId.id) ) end local newTypeInfo = orgTypeInfo:get_nilableTypeInfo( ) param.typeId2TypeInfo[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) return newTypeInfo, nil end function _TypeInfoNilable.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoNilable } ) end function _TypeInfoNilable.new( orgTypeId ) local obj = {} _TypeInfoNilable.setmeta( obj ) if obj.__init then obj:__init( orgTypeId ) end return obj end function _TypeInfoNilable:__init( orgTypeId ) _TypeInfo.__init( self) self.orgTypeId = orgTypeId end function _TypeInfoNilable:_toMap() return self end function _TypeInfoNilable._fromMap( val ) local obj, mes = _TypeInfoNilable._fromMapSub( {}, val ) if obj then _TypeInfoNilable.setmeta( obj ) end return obj, mes end function _TypeInfoNilable._fromStem( val ) return _TypeInfoNilable._fromMap( val ) end function _TypeInfoNilable._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "orgTypeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoAlias = {} setmetatable( _TypeInfoAlias, { __index = _TypeInfo } ) function _TypeInfoAlias:createTypeInfo( param ) local __func__ = '@lune.@base.@Import._TypeInfoAlias.createTypeInfo' local _ local srcTypeInfo = _lune.unwrap( param:getTypeInfoFrom( self.srcTypeId )) local newTypeInfo = param.processInfo:createAlias( param.processInfo, self.rawTxt, true, Ast.AccessMode.Pub, param.moduleTypeInfo, srcTypeInfo ) param.typeId2TypeInfo[self.typeId] = newTypeInfo param.typeId2TypeDataAccessor[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) local _1 = param:getTypeInfo( self.parentId ) if nil == _1 then local __1 = _1 return nil, string.format( "%s: not found parentInfo %d %s", __func__, self.parentId, self.rawTxt) end local parentScope = param.typeId2Scope[self.parentId] if nil == parentScope then local _parentScope = parentScope return nil, string.format( "%s: not found parentScope %s %s", __func__, self.parentId, self.rawTxt) end parentScope:addAliasForType( param.processInfo, self.rawTxt, nil, newTypeInfo ) param.importedAliasMap[srcTypeInfo] = newTypeInfo return newTypeInfo, nil end function _TypeInfoAlias.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoAlias } ) end function _TypeInfoAlias.new( parentId, rawTxt, srcTypeId ) local obj = {} _TypeInfoAlias.setmeta( obj ) if obj.__init then obj:__init( parentId, rawTxt, srcTypeId ) end return obj end function _TypeInfoAlias:__init( parentId, rawTxt, srcTypeId ) _TypeInfo.__init( self) self.parentId = parentId self.rawTxt = rawTxt self.srcTypeId = srcTypeId end function _TypeInfoAlias:_toMap() return self end function _TypeInfoAlias._fromMap( val ) local obj, mes = _TypeInfoAlias._fromMapSub( {}, val ) if obj then _TypeInfoAlias.setmeta( obj ) end return obj, mes end function _TypeInfoAlias._fromStem( val ) return _TypeInfoAlias._fromMap( val ) end function _TypeInfoAlias._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "rawTxt", func = _lune._toStr, nilable = false, child = {} } ) table.insert( memInfo, { name = "srcTypeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoDDD = {} setmetatable( _TypeInfoDDD, { __index = _TypeInfo } ) function _TypeInfoDDD:createTypeInfo( param ) local itemTypeInfo = _lune.unwrap( param:getTypeInfoFrom( self.itemTypeId )) local newTypeInfo = param.processInfo:createDDD( itemTypeInfo, true, self.extTypeFlag ) param.typeId2TypeInfo[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) return newTypeInfo, nil end function _TypeInfoDDD.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoDDD } ) end function _TypeInfoDDD.new( parentId, itemTypeId, extTypeFlag ) local obj = {} _TypeInfoDDD.setmeta( obj ) if obj.__init then obj:__init( parentId, itemTypeId, extTypeFlag ) end return obj end function _TypeInfoDDD:__init( parentId, itemTypeId, extTypeFlag ) _TypeInfo.__init( self) self.parentId = parentId self.itemTypeId = itemTypeId self.extTypeFlag = extTypeFlag end function _TypeInfoDDD:_toMap() return self end function _TypeInfoDDD._fromMap( val ) local obj, mes = _TypeInfoDDD._fromMapSub( {}, val ) if obj then _TypeInfoDDD.setmeta( obj ) end return obj, mes end function _TypeInfoDDD._fromStem( val ) return _TypeInfoDDD._fromMap( val ) end function _TypeInfoDDD._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "itemTypeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) table.insert( memInfo, { name = "extTypeFlag", func = _lune._toBool, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoAlternate = {} setmetatable( _TypeInfoAlternate, { __index = _TypeInfo } ) function _TypeInfoAlternate:createTypeInfo( param ) local baseInfo = _lune.unwrap( param:getTypeInfoFrom( self.baseId )) local interfaceList = {} for __index, ifTypeId in ipairs( self.ifList ) do table.insert( interfaceList, _lune.unwrap( param:getTypeInfoFrom( ifTypeId )) ) end local newTypeInfo = param.processInfo:createAlternate( self.belongClassFlag, self.altIndex, self.txt, self.accessMode, param.moduleTypeInfo, baseInfo, interfaceList ) param.typeId2TypeInfo[self.typeId] = newTypeInfo param.typeId2TypeDataAccessor[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) return newTypeInfo, nil end function _TypeInfoAlternate.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoAlternate } ) end function _TypeInfoAlternate.new( parentId, txt, accessMode, baseId, ifList, belongClassFlag, altIndex ) local obj = {} _TypeInfoAlternate.setmeta( obj ) if obj.__init then obj:__init( parentId, txt, accessMode, baseId, ifList, belongClassFlag, altIndex ) end return obj end function _TypeInfoAlternate:__init( parentId, txt, accessMode, baseId, ifList, belongClassFlag, altIndex ) _TypeInfo.__init( self) self.parentId = parentId self.txt = txt self.accessMode = accessMode self.baseId = baseId self.ifList = ifList self.belongClassFlag = belongClassFlag self.altIndex = altIndex end function _TypeInfoAlternate:_toMap() return self end function _TypeInfoAlternate._fromMap( val ) local obj, mes = _TypeInfoAlternate._fromMapSub( {}, val ) if obj then _TypeInfoAlternate.setmeta( obj ) end return obj, mes end function _TypeInfoAlternate._fromStem( val ) return _TypeInfoAlternate._fromMap( val ) end function _TypeInfoAlternate._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "txt", func = _lune._toStr, nilable = false, child = {} } ) table.insert( memInfo, { name = "accessMode", func = Ast.AccessMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "baseId", func = _IdInfo._fromMap, nilable = false, child = {} } ) table.insert( memInfo, { name = "ifList", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) table.insert( memInfo, { name = "belongClassFlag", func = _lune._toBool, nilable = false, child = {} } ) table.insert( memInfo, { name = "altIndex", func = _lune._toInt, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoGeneric = {} setmetatable( _TypeInfoGeneric, { __index = _TypeInfo } ) function _TypeInfoGeneric:createTypeInfo( param ) local genSrcTypeInfo = _lune.unwrap( param:getTypeInfoFrom( self.genSrcTypeId )) local genTypeList = {} for __index, typeId in ipairs( self.genTypeList ) do table.insert( genTypeList, _lune.unwrap( param:getTypeInfoFrom( typeId )) ) end local newTypeInfo, scope = param.processInfo:createGeneric( genSrcTypeInfo, genTypeList, param.moduleTypeInfo ) param.typeId2TypeInfo[self.typeId] = newTypeInfo param.typeId2TypeDataAccessor[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) param.typeId2Scope[self.typeId] = scope return newTypeInfo, nil end function _TypeInfoGeneric.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoGeneric } ) end function _TypeInfoGeneric.new( genSrcTypeId, genTypeList ) local obj = {} _TypeInfoGeneric.setmeta( obj ) if obj.__init then obj:__init( genSrcTypeId, genTypeList ) end return obj end function _TypeInfoGeneric:__init( genSrcTypeId, genTypeList ) _TypeInfo.__init( self) self.genSrcTypeId = genSrcTypeId self.genTypeList = genTypeList end function _TypeInfoGeneric:_toMap() return self end function _TypeInfoGeneric._fromMap( val ) local obj, mes = _TypeInfoGeneric._fromMapSub( {}, val ) if obj then _TypeInfoGeneric.setmeta( obj ) end return obj, mes end function _TypeInfoGeneric._fromStem( val ) return _TypeInfoGeneric._fromMap( val ) end function _TypeInfoGeneric._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "genSrcTypeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) table.insert( memInfo, { name = "genTypeList", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoBox = {} setmetatable( _TypeInfoBox, { __index = _TypeInfo } ) function _TypeInfoBox:createTypeInfo( param ) local boxingType = _lune.unwrap( param:getTypeInfo( self.boxingType )) local newTypeInfo = param.processInfo:createBox( self.accessMode, boxingType ) param.typeId2TypeInfo[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) return newTypeInfo, nil end function _TypeInfoBox.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoBox } ) end function _TypeInfoBox.new( accessMode, boxingType ) local obj = {} _TypeInfoBox.setmeta( obj ) if obj.__init then obj:__init( accessMode, boxingType ) end return obj end function _TypeInfoBox:__init( accessMode, boxingType ) _TypeInfo.__init( self) self.accessMode = accessMode self.boxingType = boxingType end function _TypeInfoBox:_toMap() return self end function _TypeInfoBox._fromMap( val ) local obj, mes = _TypeInfoBox._fromMapSub( {}, val ) if obj then _TypeInfoBox.setmeta( obj ) end return obj, mes end function _TypeInfoBox._fromStem( val ) return _TypeInfoBox._fromMap( val ) end function _TypeInfoBox._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "accessMode", func = Ast.AccessMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "boxingType", func = _lune._toInt, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoExt = {} setmetatable( _TypeInfoExt, { __index = _TypeInfo } ) function _TypeInfoExt:createTypeInfo( param ) local extedType = _lune.unwrap( param:getTypeInfoFrom( self.extedTypeId )) local newTypeInfo do local _matchExp = param.processInfo:createLuaval( extedType, true ) if _matchExp[1] == Ast.LuavalResult.OK[1] then local extType = _matchExp[2][1] local _ = _matchExp[2][2] newTypeInfo = extType elseif _matchExp[1] == Ast.LuavalResult.Err[1] then local mess = _matchExp[2][1] Util.err( mess ) end end param.typeId2TypeInfo[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) return newTypeInfo, nil end function _TypeInfoExt.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoExt } ) end function _TypeInfoExt.new( extedTypeId ) local obj = {} _TypeInfoExt.setmeta( obj ) if obj.__init then obj:__init( extedTypeId ) end return obj end function _TypeInfoExt:__init( extedTypeId ) _TypeInfo.__init( self) self.extedTypeId = extedTypeId end function _TypeInfoExt:_toMap() return self end function _TypeInfoExt._fromMap( val ) local obj, mes = _TypeInfoExt._fromMapSub( {}, val ) if obj then _TypeInfoExt.setmeta( obj ) end return obj, mes end function _TypeInfoExt._fromStem( val ) return _TypeInfoExt._fromMap( val ) end function _TypeInfoExt._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "extedTypeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoModifier = {} setmetatable( _TypeInfoModifier, { __index = _TypeInfo } ) function _TypeInfoModifier:createTypeInfo( param ) local srcTypeInfo = param:getTypeInfoFrom( self.srcTypeId ) if nil == srcTypeInfo then local _srcTypeInfo = srcTypeInfo return nil, string.format( "not found srcType -- %d", self.srcTypeId.id) end local newTypeInfo = param.modifier:createModifier( srcTypeInfo, self.mutMode ) param.typeId2TypeInfo[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) return newTypeInfo, nil end function _TypeInfoModifier.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoModifier } ) end function _TypeInfoModifier.new( srcTypeId, mutMode ) local obj = {} _TypeInfoModifier.setmeta( obj ) if obj.__init then obj:__init( srcTypeId, mutMode ) end return obj end function _TypeInfoModifier:__init( srcTypeId, mutMode ) _TypeInfo.__init( self) self.srcTypeId = srcTypeId self.mutMode = mutMode end function _TypeInfoModifier:_toMap() return self end function _TypeInfoModifier._fromMap( val ) local obj, mes = _TypeInfoModifier._fromMapSub( {}, val ) if obj then _TypeInfoModifier.setmeta( obj ) end return obj, mes end function _TypeInfoModifier._fromStem( val ) return _TypeInfoModifier._fromMap( val ) end function _TypeInfoModifier._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "srcTypeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) table.insert( memInfo, { name = "mutMode", func = Ast.MutMode._from, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoModule = {} setmetatable( _TypeInfoModule, { __index = _TypeInfo } ) function _TypeInfoModule:createTypeInfo( param ) local __func__ = '@lune.@base.@Import._TypeInfoModule.createTypeInfo' local parentInfo = Ast.headTypeInfo if self.parentId ~= Ast.userRootId then local workTypeInfo = param:getTypeInfo( self.parentId ) if nil == workTypeInfo then local _workTypeInfo = workTypeInfo Util.err( string.format( "not found parentInfo %d %s", self.parentId, self.txt) ) end parentInfo = workTypeInfo end local parentScope = param.typeId2Scope[self.parentId] if nil == parentScope then local _parentScope = parentScope return nil, string.format( "%s: not found parentScope %s %s", __func__, self.parentId, self.txt) end local newTypeInfo = parentScope:getTypeInfoChild( self.txt ) do local _exp = newTypeInfo if _exp ~= nil then error( "internal error" ) else local scope = Ast.Scope.new(param.processInfo, parentScope, Ast.ScopeKind.Module, nil) local mutable = false do if self.typeId == param.metaInfo.__moduleTypeId then mutable = param.metaInfo.__moduleMutable end end local parentTypeDataAccessor = param:getTypeDataAccessor( parentInfo:get_typeId().id ) local workTypeInfo = param.processInfo:createModule( scope, parentInfo, parentTypeDataAccessor, true, self.txt, mutable ) newTypeInfo = workTypeInfo param.typeId2Scope[self.typeId] = scope param.typeId2TypeInfo[self.typeId] = workTypeInfo workTypeInfo:get_typeId():set_orgId( self.typeId ) parentScope:addClass( param.processInfo, self.txt, nil, workTypeInfo ) Log.log( Log.Level.Info, __func__, 376, function ( ) return string.format( "new module -- %s, %s, %d, %d, %d", self.txt, workTypeInfo:getFullName( Ast.defaultTypeNameCtrl, parentScope, false ), self.typeId, workTypeInfo:get_typeId().id, parentScope:get_scopeId()) end ) end end return newTypeInfo, nil end function _TypeInfoModule.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoModule } ) end function _TypeInfoModule.new( parentId, txt ) local obj = {} _TypeInfoModule.setmeta( obj ) if obj.__init then obj:__init( parentId, txt ) end return obj end function _TypeInfoModule:__init( parentId, txt ) _TypeInfo.__init( self) self.parentId = parentId self.txt = txt end function _TypeInfoModule:_toMap() return self end function _TypeInfoModule._fromMap( val ) local obj, mes = _TypeInfoModule._fromMapSub( {}, val ) if obj then _TypeInfoModule.setmeta( obj ) end return obj, mes end function _TypeInfoModule._fromStem( val ) return _TypeInfoModule._fromMap( val ) end function _TypeInfoModule._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "txt", func = _lune._toStr, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoNormal = {} setmetatable( _TypeInfoNormal, { __index = _TypeInfo } ) function _TypeInfoNormal:createTypeInfo( param ) local __func__ = '@lune.@base.@Import._TypeInfoNormal.createTypeInfo' local newTypeInfo = nil if self.parentId ~= Ast.userRootId or not Ast.getBuiltInTypeIdMap( )[self.typeId] or self.kind == Ast.TypeInfoKind.List or self.kind == Ast.TypeInfoKind.Array or self.kind == Ast.TypeInfoKind.Map or self.kind == Ast.TypeInfoKind.Set then local parentInfo = Ast.headTypeInfo if self.parentId ~= Ast.userRootId then local workTypeInfo = param:getTypeInfo( self.parentId ) if nil == workTypeInfo then local _workTypeInfo = workTypeInfo return nil, string.format( "not found parentInfo %d %s", self.parentId, self.txt) end parentInfo = workTypeInfo end local itemTypeInfo = {} for __index, typeId in ipairs( self.itemTypeId ) do table.insert( itemTypeInfo, _lune.unwrap( param:getTypeInfoFrom( typeId )) ) end local argTypeInfo = {} for index, typeId in ipairs( self.argTypeId ) do local argType, mess = param:getTypeInfoFrom( typeId ) if argType ~= nil then table.insert( argTypeInfo, argType ) else local errmess = string.format( "not found arg (index:%d) -- %s.%s, %d, %d. %s", index, parentInfo:getTxt( ), self.txt, typeId.id, #self.argTypeId, mess) return nil, errmess end end local retTypeInfo = {} for __index, typeId in ipairs( self.retTypeId ) do table.insert( retTypeInfo, _lune.unwrap( param:getTypeInfoFrom( typeId )) ) end local baseInfo = _lune.unwrap( param:getTypeInfoFrom( self.baseId )) local interfaceList = {} for __index, ifTypeId in ipairs( self.ifList ) do table.insert( interfaceList, _lune.unwrap( param:getTypeInfoFrom( ifTypeId )) ) end local parentScope = param.typeId2Scope[self.parentId] if nil == parentScope then local _parentScope = parentScope return nil, string.format( "%s: not found parentScope %s %s", __func__, self.parentId, self.txt) end if self.txt ~= "" then newTypeInfo = parentScope:getTypeInfoChild( self.txt ) end if newTypeInfo and (self.kind == Ast.TypeInfoKind.Class or self.kind == Ast.TypeInfoKind.ExtModule or self.kind == Ast.TypeInfoKind.IF ) then error( "internal error" ) else local function postProcess( workTypeInfo, scope ) newTypeInfo = workTypeInfo if scope ~= nil then param.typeId2Scope[self.typeId] = scope end param.typeId2TypeInfo[self.typeId] = workTypeInfo workTypeInfo:get_typeId():set_orgId( self.typeId ) end do local _switchExp = self.kind if _switchExp == Ast.TypeInfoKind.Class or _switchExp == Ast.TypeInfoKind.IF then Log.log( Log.Level.Debug, __func__, 486, function ( ) return string.format( "new type -- %d, %s -- %s, %d", self.parentId, self.txt, _lune.nilacc( parentScope:get_ownerTypeInfo(), 'getFullName', 'callmtd' , Ast.defaultTypeNameCtrl, parentScope, false ) or "nil", _lune.nilacc( _lune.nilacc( parentScope:get_ownerTypeInfo(), 'get_typeId', 'callmtd' ), "id" ) or -1) end ) local baseScope = _lune.unwrap( baseInfo:get_scope()) local ifScopeList = {} for __index, ifType in ipairs( interfaceList ) do table.insert( ifScopeList, _lune.unwrap( ifType:get_scope()) ) end local scope = Ast.Scope.new(param.processInfo, parentScope, Ast.ScopeKind.Class, baseScope, ifScopeList) local altTypeList = {} for __index, itemType in ipairs( itemTypeInfo ) do table.insert( altTypeList, _lune.unwrap( (_lune.__Cast( itemType, 3, Ast.AlternateTypeInfo ) )) ) end local parentTypeDataAccessor = param:getTypeDataAccessor( self.parentId ) local workTypeInfo = param.processInfo:createClassAsync( self.kind == Ast.TypeInfoKind.Class, self.abstractFlag, scope, baseInfo, interfaceList, altTypeList, parentInfo, parentTypeDataAccessor, true, Ast.AccessMode.Pub, self.txt ) parentScope:addClassLazy( param.processInfo, self.txt, nil, workTypeInfo, _lune._Set_has(param.lazyModuleSet, self.typeId ) ) postProcess( workTypeInfo, scope ) param.typeId2TypeDataAccessor[self.typeId] = workTypeInfo elseif _switchExp == Ast.TypeInfoKind.ExtModule then Log.log( Log.Level.Debug, __func__, 525, function ( ) return string.format( "new type -- %d, %s -- %s, %d", self.parentId, self.txt, _lune.nilacc( parentScope:get_ownerTypeInfo(), 'getFullName', 'callmtd' , Ast.defaultTypeNameCtrl, parentScope, false ) or "nil", _lune.nilacc( _lune.nilacc( parentScope:get_ownerTypeInfo(), 'get_typeId', 'callmtd' ), "id" ) or -1) end ) local scope = Ast.Scope.new(param.processInfo, parentScope, Ast.ScopeKind.Module, nil, {}) local parentTypeDataAccessor = param:getTypeDataAccessor( self.parentId ) local workTypeInfo = param.processInfo:createExtModule( scope, parentInfo, parentTypeDataAccessor, true, Ast.AccessMode.Pub, self.txt, _lune.unwrap( self.moduleLang), _lune.unwrap( self.requirePath) ) parentScope:addExtModule( param.processInfo, self.txt, nil, workTypeInfo, _lune._Set_has(param.lazyModuleSet, self.typeId ), _lune.unwrap( self.moduleLang) ) postProcess( workTypeInfo, scope ) param.typeId2TypeDataAccessor[self.typeId] = workTypeInfo elseif _switchExp == Ast.TypeInfoKind.Func or _switchExp == Ast.TypeInfoKind.Method or _switchExp == Ast.TypeInfoKind.FormFunc or _switchExp == Ast.TypeInfoKind.Macro then local typeInfoKind = self.kind local accessMode = self.accessMode local workTypeInfo local scope = nil if self.kind ~= Ast.TypeInfoKind.FormFunc then scope = Ast.Scope.new(param.processInfo, parentScope, Ast.ScopeKind.Other, nil) end local parentTypeDataAccessor = param:getTypeDataAccessor( self.parentId ) local workTypeInfoMut = param.processInfo:createFuncAsync( self.abstractFlag, false, scope, typeInfoKind, parentInfo, parentTypeDataAccessor, false, true, self.staticFlag, accessMode, self.txt, self.asyncMode, itemTypeInfo, argTypeInfo, retTypeInfo, self.mutMode ) param.typeId2TypeDataAccessor[self.typeId] = workTypeInfoMut postProcess( workTypeInfoMut, scope ) do local _switchExp = self.kind if _switchExp == Ast.TypeInfoKind.Func or _switchExp == Ast.TypeInfoKind.Method or _switchExp == Ast.TypeInfoKind.Macro or _switchExp == Ast.TypeInfoKind.FormFunc then local symbolKind = Ast.SymbolKind.Fun do local _switchExp = self.kind if _switchExp == Ast.TypeInfoKind.Method then symbolKind = Ast.SymbolKind.Mtd elseif _switchExp == Ast.TypeInfoKind.Macro then symbolKind = Ast.SymbolKind.Mac elseif _switchExp == Ast.TypeInfoKind.FormFunc then symbolKind = Ast.SymbolKind.Typ end end local workParentScope = _lune.unwrap( param.typeId2Scope[self.parentId]) workParentScope:add( param.processInfo, symbolKind, false, self.kind == Ast.TypeInfoKind.Func, self.txt, nil, workTypeInfoMut, accessMode, self.staticFlag, Ast.MutMode.IMut, true, false ) end end elseif _switchExp == Ast.TypeInfoKind.Set then local workTypeInfo = param.processInfo:createSet( self.accessMode, parentInfo, itemTypeInfo, self.mutMode ) postProcess( workTypeInfo, nil ) elseif _switchExp == Ast.TypeInfoKind.List then local workTypeInfo = param.processInfo:createList( self.accessMode, parentInfo, itemTypeInfo, self.mutMode ) postProcess( workTypeInfo, nil ) elseif _switchExp == Ast.TypeInfoKind.Array then local workTypeInfo = param.processInfo:createArray( self.accessMode, parentInfo, itemTypeInfo, self.mutMode ) postProcess( workTypeInfo, nil ) elseif _switchExp == Ast.TypeInfoKind.Map then local workTypeInfo = param.processInfo:createMap( self.accessMode, parentInfo, itemTypeInfo[1], itemTypeInfo[2], self.mutMode ) postProcess( workTypeInfo, nil ) else Util.err( string.format( "illegal kind -- %s", Ast.TypeInfoKind:_getTxt( self.kind) ) ) end end end else newTypeInfo = param.scope:getTypeInfo( self.txt, param.scope, false, param.scopeAccess ) if newTypeInfo ~= nil then param.typeId2TypeInfo[self.typeId] = newTypeInfo newTypeInfo:get_typeId():set_orgId( self.typeId ) else for key, val in pairs( self:_toMap( ) ) do Util.errorLog( string.format( "error: illegal self %s:%s", key, val) ) end end end return newTypeInfo, nil end function _TypeInfoNormal.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoNormal } ) end function _TypeInfoNormal.new( parentId, abstractFlag, baseId, txt, staticFlag, accessMode, kind, mutMode, asyncMode, ifList, itemTypeId, argTypeId, retTypeId, children, moduleLang, requirePath ) local obj = {} _TypeInfoNormal.setmeta( obj ) if obj.__init then obj:__init( parentId, abstractFlag, baseId, txt, staticFlag, accessMode, kind, mutMode, asyncMode, ifList, itemTypeId, argTypeId, retTypeId, children, moduleLang, requirePath ) end return obj end function _TypeInfoNormal:__init( parentId, abstractFlag, baseId, txt, staticFlag, accessMode, kind, mutMode, asyncMode, ifList, itemTypeId, argTypeId, retTypeId, children, moduleLang, requirePath ) _TypeInfo.__init( self) self.parentId = parentId self.abstractFlag = abstractFlag self.baseId = baseId self.txt = txt self.staticFlag = staticFlag self.accessMode = accessMode self.kind = kind self.mutMode = mutMode self.asyncMode = asyncMode self.ifList = ifList self.itemTypeId = itemTypeId self.argTypeId = argTypeId self.retTypeId = retTypeId self.children = children self.moduleLang = moduleLang self.requirePath = requirePath end function _TypeInfoNormal:_toMap() return self end function _TypeInfoNormal._fromMap( val ) local obj, mes = _TypeInfoNormal._fromMapSub( {}, val ) if obj then _TypeInfoNormal.setmeta( obj ) end return obj, mes end function _TypeInfoNormal._fromStem( val ) return _TypeInfoNormal._fromMap( val ) end function _TypeInfoNormal._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "abstractFlag", func = _lune._toBool, nilable = false, child = {} } ) table.insert( memInfo, { name = "baseId", func = _IdInfo._fromMap, nilable = false, child = {} } ) table.insert( memInfo, { name = "txt", func = _lune._toStr, nilable = false, child = {} } ) table.insert( memInfo, { name = "staticFlag", func = _lune._toBool, nilable = false, child = {} } ) table.insert( memInfo, { name = "accessMode", func = Ast.AccessMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "kind", func = Ast.TypeInfoKind._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "mutMode", func = Ast.MutMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "asyncMode", func = Ast.Async._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "ifList", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) table.insert( memInfo, { name = "itemTypeId", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) table.insert( memInfo, { name = "argTypeId", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) table.insert( memInfo, { name = "retTypeId", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) table.insert( memInfo, { name = "children", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) table.insert( memInfo, { name = "moduleLang", func = Types.Lang._from, nilable = true, child = {} } ) table.insert( memInfo, { name = "requirePath", func = _lune._toStr, nilable = true, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoEnum = {} setmetatable( _TypeInfoEnum, { __index = _TypeInfo } ) function _TypeInfoEnum:createTypeInfo( param ) local accessMode = _lune.unwrap( Ast.AccessMode._from( self.accessMode )) local parentTypeDataAccessor, parentInfo = param:getTypeDataAccessor( self.parentId ) local parentScope = _lune.unwrap( param.typeId2Scope[self.parentId]) local scope = Ast.Scope.new(param.processInfo, parentScope, Ast.ScopeKind.Class, nil) param.typeId2Scope[self.typeId] = scope local valTypeInfo = _lune.unwrap( param:getTypeInfo( self.valTypeId )) local enumTypeInfo = param.processInfo:createEnum( scope, parentInfo, parentTypeDataAccessor, true, accessMode, self.txt, valTypeInfo ) local newTypeInfo = enumTypeInfo param.typeId2TypeInfo[self.typeId] = enumTypeInfo param.typeId2TypeDataAccessor[self.typeId] = enumTypeInfo enumTypeInfo:get_typeId():set_orgId( self.typeId ) local function getEnumLiteral( val ) do local _switchExp = valTypeInfo if _switchExp == Ast.builtinTypeInt then return _lune.newAlge( Ast.EnumLiteral.Int, {math.floor(val)}) elseif _switchExp == Ast.builtinTypeReal then return _lune.newAlge( Ast.EnumLiteral.Real, {val * 1.0}) elseif _switchExp == Ast.builtinTypeString then return _lune.newAlge( Ast.EnumLiteral.Str, {val}) end end return nil end for valName, valData in pairs( self.enumValList ) do local val = getEnumLiteral( valData ) if nil == val then local _val = val return nil, string.format( "unknown enum val type -- %s", valTypeInfo:getTxt( )) end local evalValSym = _lune.unwrap( scope:addEnumVal( param.processInfo, valName, nil, enumTypeInfo )) enumTypeInfo:addEnumValInfo( Ast.EnumValInfo.new(valName, val, evalValSym) ) end parentScope:addEnum( param.processInfo, accessMode, self.txt, nil, enumTypeInfo ) return newTypeInfo, nil end function _TypeInfoEnum.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoEnum } ) end function _TypeInfoEnum.new( parentId, txt, accessMode, valTypeId, enumValList ) local obj = {} _TypeInfoEnum.setmeta( obj ) if obj.__init then obj:__init( parentId, txt, accessMode, valTypeId, enumValList ) end return obj end function _TypeInfoEnum:__init( parentId, txt, accessMode, valTypeId, enumValList ) _TypeInfo.__init( self) self.parentId = parentId self.txt = txt self.accessMode = accessMode self.valTypeId = valTypeId self.enumValList = enumValList end function _TypeInfoEnum:_toMap() return self end function _TypeInfoEnum._fromMap( val ) local obj, mes = _TypeInfoEnum._fromMapSub( {}, val ) if obj then _TypeInfoEnum.setmeta( obj ) end return obj, mes end function _TypeInfoEnum._fromStem( val ) return _TypeInfoEnum._fromMap( val ) end function _TypeInfoEnum._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "txt", func = _lune._toStr, nilable = false, child = {} } ) table.insert( memInfo, { name = "accessMode", func = Ast.AccessMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "valTypeId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "enumValList", func = _lune._toMap, nilable = false, child = { { func = _lune._toStr, nilable = false, child = {} }, { func = _lune._toStem, nilable = false, child = {} } } } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoAlgeVal = {} setmetatable( _TypeInfoAlgeVal, { ifList = {Mapping,} } ) function _TypeInfoAlgeVal.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoAlgeVal } ) end function _TypeInfoAlgeVal.new( name, typeList ) local obj = {} _TypeInfoAlgeVal.setmeta( obj ) if obj.__init then obj:__init( name, typeList ) end return obj end function _TypeInfoAlgeVal:__init( name, typeList ) self.name = name self.typeList = typeList end function _TypeInfoAlgeVal:_toMap() return self end function _TypeInfoAlgeVal._fromMap( val ) local obj, mes = _TypeInfoAlgeVal._fromMapSub( {}, val ) if obj then _TypeInfoAlgeVal.setmeta( obj ) end return obj, mes end function _TypeInfoAlgeVal._fromStem( val ) return _TypeInfoAlgeVal._fromMap( val ) end function _TypeInfoAlgeVal._fromMapSub( obj, val ) local memInfo = {} table.insert( memInfo, { name = "name", func = _lune._toStr, nilable = false, child = {} } ) table.insert( memInfo, { name = "typeList", func = _lune._toList, nilable = false, child = { { func = _IdInfo._fromMap, nilable = false, child = {} } } } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local _TypeInfoAlge = {} setmetatable( _TypeInfoAlge, { __index = _TypeInfo } ) function _TypeInfoAlge:createTypeInfo( param ) local accessMode = _lune.unwrap( Ast.AccessMode._from( self.accessMode )) local parentTypeDataAccessor, parentInfo = param:getTypeDataAccessor( self.parentId ) local parentScope = _lune.unwrap( param.typeId2Scope[self.parentId]) local scope = Ast.Scope.new(param.processInfo, parentScope, Ast.ScopeKind.Class, nil) param.typeId2Scope[self.typeId] = scope local algeTypeInfo = param.processInfo:createAlge( scope, parentInfo, parentTypeDataAccessor, true, accessMode, self.txt ) local newTypeInfo = algeTypeInfo param.typeId2TypeInfo[self.typeId] = algeTypeInfo param.typeId2TypeDataAccessor[self.typeId] = algeTypeInfo algeTypeInfo:get_typeId():set_orgId( self.typeId ) for __index, valInfo in ipairs( self.algeValList ) do local typeInfoList = {} for __index, orgTypeId in ipairs( valInfo.typeList ) do table.insert( typeInfoList, _lune.unwrap( param:getTypeInfoFrom( orgTypeId )) ) end local algeValSym = scope:addAlgeVal( param.processInfo, valInfo.name, nil, algeTypeInfo ) local algeVal = Ast.AlgeValInfo.new(valInfo.name, typeInfoList, algeTypeInfo, _lune.unwrap( algeValSym)) algeTypeInfo:addValInfo( algeVal ) end parentScope:addAlge( param.processInfo, accessMode, self.txt, nil, algeTypeInfo ) return newTypeInfo, nil end function _TypeInfoAlge.setmeta( obj ) setmetatable( obj, { __index = _TypeInfoAlge } ) end function _TypeInfoAlge.new( parentId, txt, accessMode, algeValList ) local obj = {} _TypeInfoAlge.setmeta( obj ) if obj.__init then obj:__init( parentId, txt, accessMode, algeValList ) end return obj end function _TypeInfoAlge:__init( parentId, txt, accessMode, algeValList ) _TypeInfo.__init( self) self.parentId = parentId self.txt = txt self.accessMode = accessMode self.algeValList = algeValList end function _TypeInfoAlge:_toMap() return self end function _TypeInfoAlge._fromMap( val ) local obj, mes = _TypeInfoAlge._fromMapSub( {}, val ) if obj then _TypeInfoAlge.setmeta( obj ) end return obj, mes end function _TypeInfoAlge._fromStem( val ) return _TypeInfoAlge._fromMap( val ) end function _TypeInfoAlge._fromMapSub( obj, val ) local result, mes = _TypeInfo._fromMapSub( obj, val ) if not result then return nil, mes end local memInfo = {} table.insert( memInfo, { name = "parentId", func = _lune._toInt, nilable = false, child = {} } ) table.insert( memInfo, { name = "txt", func = _lune._toStr, nilable = false, child = {} } ) table.insert( memInfo, { name = "accessMode", func = Ast.AccessMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "algeValList", func = _lune._toList, nilable = false, child = { { func = _TypeInfoAlgeVal._fromMap, nilable = false, child = {} } } } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end local DependModuleInfo = {} function DependModuleInfo:getTypeInfo( metaTypeId ) return _lune.unwrap( self.metaTypeId2TypeInfoMap[metaTypeId]) end function DependModuleInfo.setmeta( obj ) setmetatable( obj, { __index = DependModuleInfo } ) end function DependModuleInfo.new( id, metaTypeId2TypeInfoMap ) local obj = {} DependModuleInfo.setmeta( obj ) if obj.__init then obj:__init( id, metaTypeId2TypeInfoMap ) end return obj end function DependModuleInfo:__init( id, metaTypeId2TypeInfoMap ) self.id = id self.metaTypeId2TypeInfoMap = metaTypeId2TypeInfoMap end local ModuleLoaderParam = {} _moduleObj.ModuleLoaderParam = ModuleLoaderParam function ModuleLoaderParam.setmeta( obj ) setmetatable( obj, { __index = ModuleLoaderParam } ) end function ModuleLoaderParam.new( ctrl_info, processInfo, latestPos, macroMode, nearCode, validMutControl, macroEval ) local obj = {} ModuleLoaderParam.setmeta( obj ) if obj.__init then obj:__init( ctrl_info, processInfo, latestPos, macroMode, nearCode, validMutControl, macroEval ) end return obj end function ModuleLoaderParam:__init( ctrl_info, processInfo, latestPos, macroMode, nearCode, validMutControl, macroEval ) self.ctrl_info = ctrl_info self.processInfo = processInfo self.latestPos = latestPos self.macroMode = macroMode self.nearCode = nearCode self.validMutControl = validMutControl self.macroEval = macroEval end function ModuleLoaderParam:get_ctrl_info() return self.ctrl_info end function ModuleLoaderParam:get_processInfo() return self.processInfo end function ModuleLoaderParam:get_latestPos() return self.latestPos end function ModuleLoaderParam:get_macroMode() return self.macroMode end function ModuleLoaderParam:get_nearCode() return self.nearCode end function ModuleLoaderParam:get_validMutControl() return self.validMutControl end function ModuleLoaderParam:get_macroEval() return self.macroEval end local ModuleLoaderResult = {} function ModuleLoaderResult.setmeta( obj ) setmetatable( obj, { __index = ModuleLoaderResult } ) end function ModuleLoaderResult.new( exportInfo, modulePath, fullModulePath, baseDir, err, depth, importedAliasMap ) local obj = {} ModuleLoaderResult.setmeta( obj ) if obj.__init then obj:__init( exportInfo, modulePath, fullModulePath, baseDir, err, depth, importedAliasMap ) end return obj end function ModuleLoaderResult:__init( exportInfo, modulePath, fullModulePath, baseDir, err, depth, importedAliasMap ) self.exportInfo = exportInfo self.modulePath = modulePath self.fullModulePath = fullModulePath self.baseDir = baseDir self.err = err self.depth = depth self.importedAliasMap = importedAliasMap end function ModuleLoaderResult:get_exportInfo() return self.exportInfo end setmetatable( ModuleLoader, { __index = Runner.Runner,ifList = {frontInterface.ModuleLoader,} } ) _moduleObj.ModuleLoader = ModuleLoader function ModuleLoader:applyExportInfo( exportInfo ) if exportInfo ~= nil then do local work = _lune.__Cast( exportInfo, 3, Nodes.ExportInfo ) if work ~= nil then self.macroCtrl:importMacroInfo( work:get_typeId2DefMacroInfo() ) end end for key, val in pairs( exportInfo:get_importedAliasMap() ) do self.result.importedAliasMap[key] = val end end end function ModuleLoader:craeteModuleInfo( moduleMeta ) do local _matchExp = moduleMeta:get_metaOrModule() if _matchExp[1] == frontInterface.MetaOrModule.Module[1] then local _ = _matchExp[2][1] local exportInfo = _matchExp[2][2] self:applyExportInfo( exportInfo ) return exportInfo elseif _matchExp[1] == frontInterface.MetaOrModule.Export[1] then local exportInfo = _matchExp[2][1] self:applyExportInfo( exportInfo ) return exportInfo elseif _matchExp[1] == frontInterface.MetaOrModule.MetaRaw[1] then local metaInfo = _matchExp[2][1] self.importModuleInfo:add( self.result.modulePath ) self.importProcessInfo:switchIdProvier( Ast.IdType.Ext ) local nameList = Util.splitStr( self.result.modulePath, '[^%./:]+' ) local moduleInfo = self:processImportFromFile( self.importProcessInfo, moduleMeta:get_lnsPath(), metaInfo, self.result.fullModulePath, self.result.modulePath, nameList, self.result.baseDir, self.result.depth ) self.importProcessInfo:switchIdProvier( Ast.IdType.Base ) self.importModuleInfo:remove( ) return moduleInfo:get_exportInfo() end end end function ModuleLoader.new( enableAsync, exportInfo, workImportModuleInfo, modulePath, fullModulePath, baseDir, moduleLoaderParam, depth ) local obj = {} ModuleLoader.setmeta( obj ) if obj.__init then obj:__init( enableAsync, exportInfo, workImportModuleInfo, modulePath, fullModulePath, baseDir, moduleLoaderParam, depth ); end return obj end function ModuleLoader:__init(enableAsync, exportInfo, workImportModuleInfo, modulePath, fullModulePath, baseDir, moduleLoaderParam, depth) Runner.Runner.__init( self) self.syncFlag = nil self.moduleLoaderParam = moduleLoaderParam self.result = ModuleLoaderResult.new(exportInfo, modulePath, fullModulePath, baseDir, "", depth, {}) self.moduleMeta = nil self.validMutControl = moduleLoaderParam:get_validMutControl() self.curPos = moduleLoaderParam:get_latestPos() self.macroCtrl = Macro.MacroCtrl.new(moduleLoaderParam:get_macroEval(), moduleLoaderParam:get_ctrl_info().validMacroAsync) self.importModuleInfo = workImportModuleInfo:clone( ) self.fullModulePath = fullModulePath self.importProcessInfo = moduleLoaderParam:get_processInfo():newUser( ) local simpleTransUnit = TransUnitIF.SimpeTransUnit.new(moduleLoaderParam:get_ctrl_info(), self.importProcessInfo, moduleLoaderParam:get_latestPos(), moduleLoaderParam:get_macroMode(), moduleLoaderParam:get_nearCode()) self.transUnitIF = simpleTransUnit self.globalScope = simpleTransUnit:get_globalScope() self.loaderFunc = function ( ) if not self.result.exportInfo then if not self.importModuleInfo:add( fullModulePath ) then self.result.err = string.format( "recursive import: %s -> %s", self.importModuleInfo:getFull( ), fullModulePath) else do do local _exp = frontInterface.loadMeta( self.importModuleInfo:clone( ), modulePath, fullModulePath, baseDir, self ) if _exp ~= nil then local moduleMeta = _exp self.result.exportInfo = self:craeteModuleInfo( moduleMeta ) else self.result.err = string.format( "failed to load meta -- %s on %s", fullModulePath, baseDir or "./") end end end self.importModuleInfo:remove( ) end end end if enableAsync then self:start( 0, string.format( "ModuleLoader - %s", fullModulePath) ) else self.syncFlag = nil self.loaderFunc( ) _lune.nilacc( self.syncFlag, 'set', 'callmtd' ) end end function ModuleLoader:runMain( ) self.loaderFunc( ) end function ModuleLoader:getResult( ) _lune.nilacc( self.syncFlag, 'wait', 'callmtd' ) return self.result end function ModuleLoader:getExportInfo( ) local __func__ = '@lune.@[email protected]' _lune.nilacc( self.syncFlag, 'wait', 'callmtd' ) if not self.result:get_exportInfo() then Log.log( Log.Level.Err, __func__, 952, function ( ) return string.format( "exportInfo is nil -- %s", self.fullModulePath) end ) end return self.result:get_exportInfo() end function ModuleLoader.setmeta( obj ) setmetatable( obj, { __index = ModuleLoader } ) end function ModuleLoader:processImportFromFile( processInfo, lnsPath, metaInfoStem, fullModulePath, modulePath, nameList, baseDir, depth ) local __func__ = '@lune.@[email protected]' local moduleInfo do local metaInfo = metaInfoStem Log.log( Log.Level.Info, __func__, 969, function ( ) return string.format( "%s processing", fullModulePath) end ) local dependLibId2DependInfo = {} do local loaderMap = {} do local __sorted = {} local __map = metaInfo.__dependModuleMap for __key in pairs( __map ) do table.insert( __sorted, __key ) end table.sort( __sorted ) for __index, dependName in ipairs( __sorted ) do local dependInfo = __map[ dependName ] do local workProcessInfo = processInfo:newUser( ) local moduleLoader = self:processImportMain( workProcessInfo, baseDir, dependName, depth + 1 ) local typeId = math.floor((_lune.unwrap( dependInfo['typeId']) )) loaderMap[moduleLoader] = typeId end end end for moduleLoader, typeId in pairs( loaderMap ) do local result = moduleLoader:getResult( ) do local _exp = result.exportInfo if _exp ~= nil then self:applyExportInfo( _exp ) dependLibId2DependInfo[typeId] = _exp else self.transUnitIF:error( result.err ) end end end end local typeId2TypeInfo = {} local typeId2TypeDataAccessor = {} typeId2TypeInfo[Ast.userRootId] = processInfo:get_dummyParentType() local typeId2Scope = {} typeId2Scope[Ast.userRootId] = processInfo:get_topScope() for typeId, dependIdInfo in pairs( metaInfo.__dependIdMap ) do local dependInfo = _lune.unwrap( dependLibId2DependInfo[_lune.unwrap( dependIdInfo[1])]) local typeInfo = _lune.unwrap( dependInfo:getTypeInfo( _lune.unwrap( dependIdInfo[2]) )) typeId2TypeInfo[typeId] = typeInfo end local moduleTypeInfo = Ast.headTypeInfo for index, moduleName in ipairs( nameList ) do local mutable = false if index == #nameList then mutable = metaInfo.__moduleMutable end local nsInfo = self.transUnitIF:pushModule( processInfo, true, moduleName, mutable ) moduleTypeInfo = nsInfo:get_typeInfo() local typeId = _lune.unwrap( metaInfo.__moduleHierarchy[#nameList - index + 1]) typeId2TypeInfo[typeId] = moduleTypeInfo typeId2TypeDataAccessor[typeId] = nsInfo:get_typeDataAccessor() typeId2Scope[typeId] = self.transUnitIF:get_scope() end for __index, _1 in ipairs( nameList ) do self.transUnitIF:popModule( ) end for __index, symbolInfo in pairs( Ast.getSym2builtInTypeMap( ) ) do typeId2TypeInfo[symbolInfo:get_typeInfo():get_typeId( ).id] = symbolInfo:get_typeInfo() end for __index, builtinTypeInfo in pairs( Ast.getBuiltInTypeIdMap( ) ) do local typeInfo = builtinTypeInfo:get_typeInfo() typeId2TypeInfo[typeInfo:get_typeId().id] = typeInfo end local newId2OldIdMap = {} local _typeInfoList = {} local id2atomMap = {} local _typeInfoNormalList = {} for __index, atomInfoLua in pairs( metaInfo.__typeInfoList ) do local workAtomInfo = (atomInfoLua ) if nil == workAtomInfo then local _workAtomInfo = workAtomInfo self.transUnitIF:error( "illegal atomInfo" ) end local atomInfo = workAtomInfo do local skind = atomInfo['skind'] if skind ~= nil then local actInfo = nil local mess = nil local kind = _lune.unwrap( Ast.SerializeKind._from( math.floor(skind) )) do local _switchExp = kind if _switchExp == Ast.SerializeKind.Enum then actInfo, mess = _TypeInfoEnum._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Alge then actInfo, mess = _TypeInfoAlge._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Module then actInfo, mess = _TypeInfoModule._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Normal then local workInfo workInfo, mess = _TypeInfoNormal._fromMap( atomInfo ) if workInfo ~= nil then table.insert( _typeInfoNormalList, workInfo ) end actInfo = workInfo elseif _switchExp == Ast.SerializeKind.Nilable then actInfo, mess = _TypeInfoNilable._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Alias then actInfo, mess = _TypeInfoAlias._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.DDD then actInfo, mess = _TypeInfoDDD._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Alternate then actInfo, mess = _TypeInfoAlternate._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Generic then actInfo, mess = _TypeInfoGeneric._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Modifier then actInfo, mess = _TypeInfoModifier._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Box then actInfo, mess = _TypeInfoBox._fromMap( atomInfo ) elseif _switchExp == Ast.SerializeKind.Ext then actInfo, mess = _TypeInfoExt._fromMap( atomInfo ) end end if actInfo ~= nil then table.insert( _typeInfoList, actInfo ) id2atomMap[actInfo.typeId] = actInfo else for key, val in pairs( atomInfo ) do Util.errorLog( string.format( "table: %s:%s", key, val) ) end if mess ~= nil then Util.errorLog( mess ) end Util.err( string.format( "_TypeInfo.%s._fromMap error", Ast.SerializeKind:_getTxt( kind) ) ) end end end end local orgId2MacroTypeInfo = {} local lazyModuleSet = {} for __index, typeId in pairs( metaInfo.__lazyModuleList ) do lazyModuleSet[typeId]= true end local modifier = TransUnitIF.Modifier.new(self.validMutControl, processInfo) local importParam = ImportParam.new(self.curPos, modifier, processInfo, typeId2Scope, typeId2TypeInfo, typeId2TypeDataAccessor, {}, lazyModuleSet, metaInfo, self.transUnitIF:get_scope(), moduleTypeInfo, Ast.ScopeAccess.Normal, id2atomMap, dependLibId2DependInfo) for __index, atomInfo in ipairs( _typeInfoList ) do local newTypeInfo, errMess = atomInfo:createTypeInfoCache( importParam ) do local _exp = errMess if _exp ~= nil then Util.err( string.format( "Failed to createType -- %s: %s(%d): %s", fullModulePath, Ast.SerializeKind:_getTxt( atomInfo.skind) , atomInfo.typeId, _exp) ) end end if newTypeInfo ~= nil then if newTypeInfo:get_kind() == Ast.TypeInfoKind.Macro then orgId2MacroTypeInfo[atomInfo.typeId] = newTypeInfo end if newTypeInfo:get_kind() == Ast.TypeInfoKind.Set then end if newTypeInfo:get_accessMode() == Ast.AccessMode.Global then do local _switchExp = newTypeInfo:get_kind() if _switchExp == Ast.TypeInfoKind.IF or _switchExp == Ast.TypeInfoKind.Class then self.globalScope:addClass( processInfo, newTypeInfo:get_rawTxt(), nil, newTypeInfo ) elseif _switchExp == Ast.TypeInfoKind.Func then self.globalScope:addFunc( processInfo, nil, newTypeInfo, Ast.AccessMode.Global, newTypeInfo:get_staticFlag(), Ast.TypeInfo.isMut( newTypeInfo ) ) elseif _switchExp == Ast.TypeInfoKind.Enum then self.globalScope:addEnum( processInfo, Ast.AccessMode.Global, newTypeInfo:get_rawTxt(), nil, newTypeInfo ) elseif _switchExp == Ast.TypeInfoKind.Nilable then else Util.err( string.format( "%s: not support kind -- %s", __func__, Ast.TypeInfoKind:_getTxt( newTypeInfo:get_kind()) ) ) end end end end end for __index, atomInfo in ipairs( _typeInfoNormalList ) do if #atomInfo.children > 0 then importParam:getTypeInfo( atomInfo.typeId ) local scope = _lune.unwrap( typeId2Scope[atomInfo.typeId]) for __index, childId in ipairs( atomInfo.children ) do local typeInfo = importParam:getTypeInfoFrom( childId ) if nil == typeInfo then local _typeInfo = typeInfo Util.err( string.format( "not found childId -- %s, %d, %s(%d)", fullModulePath, childId.id, atomInfo.txt, atomInfo.typeId) ) end local symbolKind = Ast.SymbolKind.Typ local addFlag = true do local _switchExp = typeInfo:get_kind() if _switchExp == Ast.TypeInfoKind.Func then symbolKind = Ast.SymbolKind.Fun elseif _switchExp == Ast.TypeInfoKind.Form or _switchExp == Ast.TypeInfoKind.FormFunc then symbolKind = Ast.SymbolKind.Typ elseif _switchExp == Ast.TypeInfoKind.Method then symbolKind = Ast.SymbolKind.Mtd elseif _switchExp == Ast.TypeInfoKind.Class or _switchExp == Ast.TypeInfoKind.Module then symbolKind = Ast.SymbolKind.Typ elseif _switchExp == Ast.TypeInfoKind.Enum then addFlag = false end end if addFlag then scope:add( processInfo, symbolKind, false, typeInfo:get_kind() == Ast.TypeInfoKind.Func, typeInfo:getTxt( ), nil, typeInfo, typeInfo:get_accessMode(), typeInfo:get_staticFlag(), typeInfo:get_mutMode(), true, false ) end end end end for typeId, typeInfo in pairs( typeId2TypeInfo ) do newId2OldIdMap[typeInfo] = typeId end local function registMember( classTypeId ) local __func__ = '@lune.@[email protected]' local skip = false do if metaInfo.__dependIdMap[classTypeId] then skip = true end end if skip then return end do local classTypeInfo = _lune.unwrap( typeId2TypeInfo[classTypeId]) do local _switchExp = (classTypeInfo:get_kind() ) if _switchExp == Ast.TypeInfoKind.Class or _switchExp == Ast.TypeInfoKind.ExtModule then local scope = _lune.unwrap( typeId2Scope[classTypeId]) self.transUnitIF:pushClassScope( self.curPos, classTypeInfo, scope ) do local _exp = metaInfo.__typeId2ClassInfoMap[classTypeId] if _exp ~= nil then local classInfo = (_exp ) if nil == classInfo then local _classInfo = classInfo self.transUnitIF:error( "illegal val" ) end for fieldName, fieldInfo in pairs( classInfo ) do do local typeId = _IdInfo._fromStem( (fieldInfo['typeId'] ) ) if typeId ~= nil then local fieldTypeInfo = _lune.unwrap( importParam:getTypeInfoFrom( typeId )) local symbolInfo = self.transUnitIF:get_scope():addMember( processInfo, fieldName, nil, fieldTypeInfo, _lune.unwrap( Ast.AccessMode._from( math.floor((_lune.unwrap( fieldInfo['accessMode']) )) )), fieldInfo['staticFlag'] and true or false, _lune.unwrap( Ast.MutMode._from( math.floor((_lune.unwrap( fieldInfo['mutMode']) )) )) ) else self.transUnitIF:error( "not found fieldInfo.typeId" ) end end end else self.transUnitIF:error( string.format( "not found class -- %s: %d, %s", fullModulePath, classTypeId, classTypeInfo:getTxt( )) ) end end elseif _switchExp == Ast.TypeInfoKind.Module then self.transUnitIF:pushModuleLow( processInfo, true, classTypeInfo:getTxt( ), Ast.TypeInfo.isMut( classTypeInfo ) ) Log.log( Log.Level.Debug, __func__, 1282, function ( ) return string.format( "push module -- %s, %s, %d, %d, %d", classTypeInfo:getTxt( ), _lune.nilacc( self.transUnitIF:get_scope():get_ownerTypeInfo(), 'getFullName', 'callmtd' , Ast.defaultTypeNameCtrl, self.transUnitIF:get_scope(), false ) or "nil", _lune.nilacc( _lune.nilacc( self.transUnitIF:get_scope():get_ownerTypeInfo(), 'get_typeId', 'callmtd' ), "id" ) or -1, classTypeInfo:get_typeId().id, self.transUnitIF:get_scope():get_parent():get_scopeId()) end ) end end for __index, child in ipairs( classTypeInfo:get_children( ) ) do if child:get_kind( ) == Ast.TypeInfoKind.Class or child:get_kind( ) == Ast.TypeInfoKind.ExtModule or child:get_kind( ) == Ast.TypeInfoKind.Module or child:get_kind( ) == Ast.TypeInfoKind.IF then local oldId = newId2OldIdMap[child] if oldId then registMember( _lune.unwrap( oldId) ) end end end do local _switchExp = classTypeInfo:get_kind() if _switchExp == Ast.TypeInfoKind.Class or _switchExp == Ast.TypeInfoKind.ExtModule then self.transUnitIF:popClass( ) elseif _switchExp == Ast.TypeInfoKind.Module then self.transUnitIF:popModule( ) end end end end for __index, atomInfo in ipairs( _typeInfoList ) do do local workInfo = _lune.__Cast( atomInfo, 3, _TypeInfoNormal ) if workInfo ~= nil then if workInfo.parentId == Ast.userRootId then registMember( atomInfo.typeId ) end else do local workInfo = _lune.__Cast( atomInfo, 3, _TypeInfoModule ) if workInfo ~= nil then if workInfo.parentId == Ast.userRootId then registMember( atomInfo.typeId ) end end end end end end for index, moduleName in ipairs( nameList ) do local mutable = false if index == #nameList then mutable = metaInfo.__moduleMutable end self.transUnitIF:pushModuleLow( processInfo, true, moduleName, mutable ) end local VarNameInfo = {} setmetatable( VarNameInfo, { ifList = {Mapping,} } ) function VarNameInfo.setmeta( obj ) setmetatable( obj, { __index = VarNameInfo } ) end function VarNameInfo.new( typeId, accessMode, mutable ) local obj = {} VarNameInfo.setmeta( obj ) if obj.__init then obj:__init( typeId, accessMode, mutable ) end return obj end function VarNameInfo:__init( typeId, accessMode, mutable ) self.typeId = typeId self.accessMode = accessMode self.mutable = mutable end function VarNameInfo:_toMap() return self end function VarNameInfo._fromMap( val ) local obj, mes = VarNameInfo._fromMapSub( {}, val ) if obj then VarNameInfo.setmeta( obj ) end return obj, mes end function VarNameInfo._fromStem( val ) return VarNameInfo._fromMap( val ) end function VarNameInfo._fromMapSub( obj, val ) local memInfo = {} table.insert( memInfo, { name = "typeId", func = _IdInfo._fromMap, nilable = false, child = {} } ) table.insert( memInfo, { name = "accessMode", func = Ast.AccessMode._from, nilable = false, child = {} } ) table.insert( memInfo, { name = "mutable", func = _lune._toBool, nilable = false, child = {} } ) local result, mess = _lune._fromMap( obj, val, memInfo ) if not result then return nil, mess end return obj end for varName, varInfo in pairs( metaInfo.__varName2InfoMap ) do do local varNameInfo = VarNameInfo._fromStem( (varInfo ) ) if varNameInfo ~= nil then local typeId = varNameInfo.typeId local scope if varNameInfo.accessMode == Ast.AccessMode.Global then scope = self.globalScope else scope = self.transUnitIF:get_scope() end scope:addExportedVar( processInfo, varNameInfo.mutable, varNameInfo.accessMode, varName, nil, _lune.unwrap( importParam:getTypeInfoFrom( typeId )), varNameInfo.mutable and Ast.MutMode.Mut or Ast.MutMode.IMut ) else self.transUnitIF:error( "illegal varInfo.typeId" ) end end end local importedMacroInfoMap = {} for orgTypeId, macroInfoStem in pairs( metaInfo.__macroName2InfoMap ) do self.macroCtrl:importMacro( processInfo, lnsPath, (macroInfoStem ), _lune.unwrap( orgId2MacroTypeInfo[orgTypeId]), typeId2TypeInfo, importedMacroInfoMap, baseDir ) end local globalSymbolList = {} for __index, symbolInfo in pairs( self.globalScope:get_symbol2SymbolInfoMap() ) do if symbolInfo:get_accessMode() == Ast.AccessMode.Global then table.insert( globalSymbolList, symbolInfo ) end end for __index, _2 in ipairs( nameList ) do self.transUnitIF:popModule( ) end if depth == 1 then for key, val in pairs( importParam.importedAliasMap ) do self.result.importedAliasMap[key] = val end end local moduleProvideInfo = frontInterface.ModuleProvideInfo.new(_lune.unwrap( typeId2TypeInfo[metaInfo.__moduleTypeId]), _lune.unwrap( Ast.SymbolKind._from( metaInfo.__moduleSymbolKind )), metaInfo.__moduleMutable) local exportInfo = Nodes.ExportInfo.new(moduleTypeInfo, moduleProvideInfo, processInfo, globalSymbolList, importParam.importedAliasMap, frontInterface.ModuleId.createIdFromTxt( metaInfo.__buildId ), fullModulePath, nameList[#nameList], lnsPath, newId2OldIdMap, importedMacroInfoMap) moduleInfo = frontInterface.ModuleInfo.new(exportInfo) end return moduleInfo end local Import = {} _moduleObj.Import = Import function Import.new( curPos, importModuleInfo, moduleType, macroCtrl, typeNameCtrl, importedAliasMap, baseDir, validMutControl ) local obj = {} Import.setmeta( obj ) if obj.__init then obj:__init( curPos, importModuleInfo, moduleType, macroCtrl, typeNameCtrl, importedAliasMap, baseDir, validMutControl ); end return obj end function Import:__init(curPos, importModuleInfo, moduleType, macroCtrl, typeNameCtrl, importedAliasMap, baseDir, validMutControl) self.baseDir = baseDir self.importModuleInfo = importModuleInfo self.moduleType = moduleType self.macroCtrl = macroCtrl self.typeNameCtrl = typeNameCtrl self.importedAliasMap = importedAliasMap self.importModule2ExportInfo = {} self.importModuleName2ModuleInfo = {} end function Import.setmeta( obj ) setmetatable( obj, { __index = Import } ) end function Import:get_importModule2ExportInfo() return self.importModule2ExportInfo end function Import:createModuleLoader( baseDir, modulePath, moduleLoaderParam, depth ) local __func__ = '@lune.@[email protected]' local fullModulePath do modulePath, baseDir, fullModulePath = frontInterface.getLuaModulePath( modulePath, baseDir ) end Log.log( Log.Level.Info, __func__, 1474, function ( ) return string.format( "%s -> %s start on %s", self.moduleType:getTxt( self.typeNameCtrl ), fullModulePath, baseDir) end ) local exportInfo = self.importModuleName2ModuleInfo[fullModulePath] if exportInfo ~= nil then Log.log( Log.Level.Info, __func__, 1482, function ( ) return string.format( "%s already", fullModulePath) end ) if depth == 1 then self.importModule2ExportInfo[exportInfo:get_moduleTypeInfo()] = exportInfo end for key, val in pairs( exportInfo:get_importedAliasMap() ) do self.importedAliasMap[key] = val end end return ModuleLoader.new(false, exportInfo, self.importModuleInfo, modulePath, fullModulePath, baseDir, moduleLoaderParam, depth) end function Import:loadModuleInfo( moduleLoader ) local __func__ = '@lune.@[email protected]' local result = moduleLoader:getResult( ) local exportInfo = result.exportInfo if nil == exportInfo then local _exportInfo = exportInfo return nil, result.err end local fullModulePath = result.fullModulePath local depth = result.depth do local work = _lune.__Cast( exportInfo, 3, Nodes.ExportInfo ) if work ~= nil then self.macroCtrl:importMacroInfo( work:get_typeId2DefMacroInfo() ) end end for key, val in pairs( exportInfo:get_importedAliasMap() ) do self.importedAliasMap[key] = val end for key, val in pairs( result.importedAliasMap ) do self.importedAliasMap[key] = val end if depth == 1 then self.importModule2ExportInfo[exportInfo:get_moduleTypeInfo()] = exportInfo end self.importModuleName2ModuleInfo[fullModulePath] = exportInfo Log.log( Log.Level.Info, __func__, 1533, function ( ) return string.format( "%s complete", fullModulePath) end ) return exportInfo, "" end function ModuleLoader:processImportMain( processInfo, baseDir, modulePath, depth ) local __func__ = '@lune.@[email protected]' local fullModulePath modulePath, baseDir, fullModulePath = frontInterface.getLuaModulePath( modulePath, baseDir ) Log.log( Log.Level.Info, __func__, 1546, function ( ) return string.format( "%s -> %s start on %s", self.result.fullModulePath, fullModulePath, baseDir) end ) local moduleLoader = ModuleLoader.new(false, nil, self.importModuleInfo, modulePath, fullModulePath, baseDir, self.moduleLoaderParam, depth) return moduleLoader end function Import:processImport( modulePath, moduleLoaderParam ) local moduleLoader = self:createModuleLoader( self.baseDir, modulePath, moduleLoaderParam, 1 ) return moduleLoader end return _moduleObj
package("jasper") set_homepage("https://www.ece.uvic.ca/~frodo/jasper/") set_description("Official Repository for the JasPer Image Coding Toolkit") set_license("BSD-2-Clause") add_urls("https://github.com/jasper-software/jasper/archive/refs/tags/version-$(version).tar.gz") add_versions("2.0.28", "6b4e5f682be0ab1a5acb0eeb6bf41d6ce17a658bb8e2dbda95de40100939cc88") add_versions("2.0.32", "a3583a06698a6d6106f2fc413aa42d65d86bedf9a988d60e5cfa38bf72bc64b9") add_versions("2.0.33", "38b8f74565ee9e7fec44657e69adb5c9b2a966ca5947ced5717cde18a7d2eca6") add_configs("opengl", {description = "Enable the use of the OpenGL/GLUT Library.", default = false, type = "boolean"}) add_deps("cmake", "libjpeg-turbo") on_load("windows", "macosx", "linux", function (package) if package:config("opengl") then package:add("deps", "freeglut") end end) on_install("windows", "macosx", "linux", function (package) io.replace("build/cmake/modules/JasOpenGL.cmake", "find_package(GLUT", "find_package(FreeGLUT", {plain = true}) local configs = {"-DJAS_ENABLE_PROGRAMS=OFF", "-DJAS_ENABLE_DOC=OFF"} local vs_sdkver = get_config("vs_sdkver") if vs_sdkver then local build_ver = string.match(vs_sdkver, "%d+%.%d+%.(%d+)%.?%d*") assert(tonumber(build_ver) >= 18362, "Jasper requires Windows SDK to be at least 10.0.18362.0") table.insert(configs, "-DCMAKE_VS_WINDOWS_TARGET_PLATFORM_VERSION=" .. vs_sdkver) table.insert(configs, "-DCMAKE_SYSTEM_VERSION=" .. vs_sdkver) end table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release")) table.insert(configs, "-DJAS_ENABLE_SHARED=" .. (package:config("shared") and "ON" or "OFF")) table.insert(configs, "-DJAS_ENABLE_OPENGL=" .. (package:config("opengl") and "ON" or "OFF")) if package:config("pic") ~= false then table.insert(configs, "-DCMAKE_POSITION_INDEPENDENT_CODE=ON") end -- warning: only works on windows sdk 10.0.18362.0 and later import("package.tools.cmake").install(package, configs) end) on_test(function (package) assert(package:has_cfuncs("jas_image_decode", {includes = "jasper/jasper.h"})) end)
local MODNAME = minetest.get_current_modname() -- Syrup local SYRUP_VISCOSITY = 6 local SYRUP_EFFECT_COLOR = {a = 103, r = 73, g = 36, b = 0} minetest.register_node(MODNAME .. ":syrup_source", { description = "Syrup Source", drawtype = "liquid", tiles = { { name = "waffleworld_mapgen_syrup_source.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, { name = "waffleworld_mapgen_syrup_source.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, use_texture_alpha = "blend", paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = MODNAME .. ":syrup_flowing", liquid_alternative_source = MODNAME .. ":syrup_source", liquid_viscosity = SYRUP_VISCOSITY, post_effect_color = SYRUP_EFFECT_COLOR, groups = {water = 3, liquid = 3, cools_lava = 1}, }) minetest.register_node(MODNAME .. ":syrup_flowing", { description = "Flowing Syrup", drawtype = "flowingliquid", tiles = {"waffleworld_mapgen_syrup.png"}, special_tiles = { { name = "waffleworld_mapgen_syrup_flowing.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, { name = "waffleworld_mapgen_syrup_flowing.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, use_texture_alpha = "blend", paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = MODNAME .. ":syrup_flowing", liquid_alternative_source = MODNAME .. ":syrup_source", liquid_viscosity = SYRUP_VISCOSITY, post_effect_color = SYRUP_EFFECT_COLOR, groups = {water = 3, liquid = 3, not_in_creative_inventory = 1, cools_lava = 1}, }) -- Butter local BUTTER_VISCOSITY = 1 local BUTTER_DAMAGE = 4 local BUTTER_EFFECT_COLOR = {a = 103, r = 219, g = 157, b = 0} minetest.register_node(MODNAME .. ":butter_source", { description = "Butter Source", drawtype = "liquid", tiles = { { name = "waffleworld_mapgen_butter_source.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, { name = "waffleworld_mapgen_butter_source.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, use_texture_alpha = "blend", paramtype = "light", light_source = minetest.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = MODNAME .. ":butter_flowing", liquid_alternative_source = MODNAME .. ":butter_source", liquid_viscosity = BUTTER_VISCOSITY, liquid_renewable = false, damage_per_second = BUTTER_DAMAGE, post_effect_color = BUTTER_EFFECT_COLOR, groups = {lava = 3, liquid = 2, igniter = 1}, }) minetest.register_node(MODNAME .. ":butter_flowing", { description = "Flowing Butter", drawtype = "flowingliquid", tiles = {"waffleworld_mapgen_butter.png"}, special_tiles = { { name = "waffleworld_mapgen_butter_flowing.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, { name = "waffleworld_mapgen_butter_flowing.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, use_texture_alpha = "blend", paramtype = "light", light_source = minetest.LIGHT_MAX - 1, paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = MODNAME .. ":butter_flowing", liquid_alternative_source = MODNAME .. ":butter_source", liquid_viscosity = BUTTER_VISCOSITY, liquid_renewable = false, damage_per_second = BUTTER_DAMAGE, post_effect_color = BUTTER_EFFECT_COLOR, groups = {lava = 3, liquid = 2, not_in_creative_inventory = 1, igniter = 1}, }) -- Batter local BATTER_VISCOSITY = 8 local BATTER_EFFECT_COLOR = {a = 245, r = 247, g = 217, b = 139} minetest.register_node(MODNAME .. ":batter", { description = "Batter Source", drawtype = "glasslike", tiles = { { name = "waffleworld_mapgen_batter_source.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, { name = "waffleworld_mapgen_batter_source.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, use_texture_alpha = "blend", paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drowning = 1, liquidtype = "source", liquid_alternative_flowing = MODNAME .. ":batter", liquid_alternative_source = MODNAME .. ":batter", liquid_viscosity = BATTER_VISCOSITY, liquid_renewable = false, post_effect_color = BATTER_EFFECT_COLOR, groups = {liquid = 3}, })
ITEM.name = "SG-552" ITEM.desc = "A Weapon." ITEM.model = "models/weapons/w_rif_sg552.mdl" ITEM.class = "nut_cs_sg552" ITEM.weaponCategory = "primary" ITEM.width = 4 ITEM.height = 2 ITEM.price = 4000 ITEM.iconCam = { ang = Angle(-1.7068501710892, 271.58676147461, 0), fov = 10.780103254469, pos = Vector(0, 200, 0) } ITEM.holsterDrawInfo = { model = ITEM.model, bone = "ValveBiped.Bip01_Spine2", ang = Angle(20, 180, 0), pos = Vector(3, -4, -3), }
require "cutorch" require "nn" require "libcunn" torch.include('cunn', 'test.lua')
-- -- ClassMods - timers wizard -- local L = LibStub("AceLocale-3.0"):GetLocale("ClassMods") -- constants local panelWidth = 500 -- not resizable local panelHeight = 500 -- resizable by user local elementWidth = 464 local AceGUI = nil local wizFrame = nil local wizPanel = 0 local TimerBars_CreateFrame = {} local DoPanel0 = {} --[[ ACEGUI prototype for priority re-ordering ]]-- local function ClassMods_PriorityLine_ButtonUp_OnClick(frame, ...) AceGUI:ClearFocus() PlaySound(SOUNDKIT.IG_MAINMENU_OPTION) frame:GetParent().obj:Fire("OnClick", ..., "UP", tonumber(frame:GetParent().obj.index:GetText() ) ) end local function ClassMods_PriorityLine_ButtonDn_OnClick(frame, ...) AceGUI:ClearFocus() PlaySound(SOUNDKIT.IG_MAINMENU_OPTION) frame:GetParent().obj:Fire("OnClick", ..., "DN", tonumber(frame:GetParent().obj.index:GetText() ) ) end local function ClassMods_PriorityLine_Control_OnEnter(frame) frame.obj:Fire("OnEnter") end local function ClassMods_PriorityLine_Control_OnLeave(frame) frame.obj:Fire("OnLeave") end local function ClassMods_PriorityLineConstructor() local frame = CreateFrame("Frame", "ClassMods_PriorityLine" .. AceGUI:GetNextWidgetNum("ClassMods_PriorityLine"), UIParent) frame:Hide() local btnup = CreateFrame("Button", nil, frame) btnup:SetWidth(24) btnup:SetHeight(24) btnup:SetPoint("LEFT", frame, "LEFT", 6, 0) btnup:SetNormalTexture("Interface\\CHATFRAME\\UI-ChatIcon-ScrollUp-Up") btnup:SetPushedTexture("Interface\\CHATFRAME\\UI-ChatIcon-ScrollUp-Down") local btndn = CreateFrame("Button", nil, frame) btndn:SetWidth(24) btndn:SetHeight(24) btndn:SetPoint("LEFT", btnup, "RIGHT") btndn:SetNormalTexture("Interface\\CHATFRAME\\UI-ChatIcon-ScrollDown-Up") btndn:SetPushedTexture("Interface\\CHATFRAME\\UI-ChatIcon-ScrollDown-Down") local index = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") index:SetWidth(36) index:SetFontObject("GameFontNormal") local f1, f2, f3 = index:GetFont() index:SetFont(f1, f2+1, "THICKOUTLINE") index:SetPoint("LEFT", btndn, "RIGHT", 6, 0) index:SetJustifyH("RIGHT") index:SetJustifyV("MIDDLE") index:SetVertexColor(1, 1, 1) local dash = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") dash:SetFontObject("GameFontNormal") dash:SetFont(f1, f2+1, "THICKOUTLINE") dash:SetPoint("LEFT", btndn, "RIGHT", 40, 0) dash:SetJustifyH("LEFT") dash:SetJustifyV("MIDDLE") dash:SetText("-") local frameicon = CreateFrame("Frame", nil, frame) frameicon:SetWidth(24) frameicon:SetHeight(24) frameicon:SetPoint("LEFT", dash, "RIGHT", 2, 0) local icon = frameicon:CreateTexture(nil, "BACKGROUND") icon:SetAllPoints(frameicon) icon:SetTexture("Inter face\\CHATFRAME\\UI-ChatIcon-ScrollDown-Up") local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall") label:SetFontObject("GameFontNormal") label:SetFont(f1, f2+1, "THICKOUTLINE") label:SetPoint("LEFT", dash, "RIGHT", 28, 0) label:SetJustifyH("LEFT") label:SetJustifyV("MIDDLE") frame:EnableMouse(true) btnup:SetScript("OnClick", ClassMods_PriorityLine_ButtonUp_OnClick) btndn:SetScript("OnClick", ClassMods_PriorityLine_ButtonDn_OnClick) frame:SetScript("OnEnter", ClassMods_PriorityLine_Control_OnEnter) frame:SetScript("OnLeave", ClassMods_PriorityLine_Control_OnLeave) local widget = { index = index, label = label, icon = icon, btnup = btnup, btndn = btndn, frame = frame, type = "ClassMods_PriorityLine" } widget["OnAcquire"] = function(self) self:SetHeight(24); self:SetWidth(elementWidth); self:SetText() end widget["SetText"] = function(self, text) self.label:SetText((text or "") ) end widget["SetIcon"] = function(self, texture) self.icon:SetTexture(texture) end widget["SetIndex"] = function(self, value, last) if (value == 1) then self.btnup:Hide() else self.btnup:Show() end if (value == last) then self.btndn:Hide() else self.btndn:Show() end self.index:SetText(value or "") end widget["SetUp"] = function(self) end widget["SetDown"] = function(self) end return AceGUI:RegisterAsWidget(widget) end local function AddLabel(container, textStr, oF1, oF2, oF3) local w = AceGUI:Create("Label") w:SetWidth(elementWidth) w:SetText(textStr) local f1, f2, f3 = w.label:GetFont() if oF1 or oF2 or oF3 then w:SetFont(oF1 or f1, oF2 or f2, oF3 or f3) end container:AddChild(w) return w end local function AddButton(container, textStr, callBackFunc, widthOverride) local w = AceGUI:Create("Button") w:SetWidth(widthOverride or elementWidth) w:SetText(textStr) w:SetCallback("OnClick", callBackFunc) container:AddChild(w) return w end local function SortImportList(listTable) table.sort(listTable, function(a,b) local aComp = (a[1] ~= nil) and (tonumber(a[1]) and (select(1, GetSpellInfo(a[1]) ) ) or a[1]) or (tonumber(a[2]) and (select(1, GetItemInfo(a[2]) ) ) or a[2]) local bComp = (b[1] ~= nil) and (tonumber(b[1]) and (select(1, GetSpellInfo(b[1]) ) ) or b[1]) or (tonumber(b[2]) and (select(1, GetItemInfo(b[2]) ) ) or b[2]) return(tostring(aComp) < tostring(bComp) ) end) end local function DoPanel3(num) local DB = _G.ClassMods.Options.DB wizFrame = TimerBars_CreateFrame(num) wizPanel = 3 -- Change priority help message AddLabel(wizFrame, " ") AddLabel(wizFrame, L["CHANGEPRIORITYMSG"], nil, 15) AddLabel(wizFrame, " ") local scrollcontainer = AceGUI:Create("SimpleGroup") scrollcontainer:SetFullWidth(true) scrollcontainer:SetFullHeight(true) scrollcontainer:SetLayout("Fill") -- important! wizFrame:AddChild(scrollcontainer) local scroll = AceGUI:Create("ScrollFrame") scroll:SetLayout("Flow") scrollcontainer:AddChild(scroll) for i=1,#DB.timers["timerbar"..num].timers do local name, _, icon = nil, nil, nil if (DB.timers["timerbar"..num].timers[i][1]) then name, _, icon = GetSpellInfo(DB.timers["timerbar"..num].timers[i][1]) else name, _, _, _, _, _, _, _, _, icon--[[texture]] = GetItemInfo(DB.timers["timerbar"..num].timers[i][2]) end local w = AceGUI:Create("ClassMods_PriorityLine") w:SetText(name or L["Invalid Timer"]) w:SetIndex(i, #DB.timers["timerbar"..num].timers) w:SetIcon(icon or "Interface\\ICONS\\INV_Misc_QuestionMark") w:SetCallback("OnClick", function(widget, ...) local oldPos = select(4, ...) local newPos = (select(3, ...) == "UP") and (oldPos - 1) or (oldPos + 1) DB.timers["timerbar"..num].timers[oldPos][19] = newPos DB.timers["timerbar"..num].timers[newPos][19] = oldPos ClassMods.Options:SortTimerList(num) LibStub("AceConfigRegistry-3.0"):NotifyChange("ClassMods") ClassMods.Options:LockDown(ClassMods.SetupTimers) DoPanel3(num) end) scroll:AddChild(w) end end local lastTab = nil local function DoPanel2(num) local DB = _G.ClassMods.Options.DB local selectedImports = { timerbar1 = {}, timerbar2 = {}, timerbar3 = {} } local function ResetSelectedImports(whichTab) for i=1,#ClassMods.timerbarDefaults[whichTab] do selectedImports[whichTab][i] = false end end ResetSelectedImports("timerbar1") ResetSelectedImports("timerbar2") ResetSelectedImports("timerbar3") wizFrame = TimerBars_CreateFrame(num) wizPanel = 2 -- What would you like to do? - label AddLabel(wizFrame, " ") AddLabel(wizFrame, L["Select timers from any tab then click the import button."], nil, 15) AddLabel(wizFrame, " ") -- Import button AddButton(wizFrame, L["Import all selected timers"], function() local count = 0 local function ImportFromTab(whichTab, num) for i=1,#ClassMods.timerbarDefaults[whichTab] do if (selectedImports[whichTab][i] == true) then DB.timers["timerbar"..num].timers[#DB.timers["timerbar"..num].timers + 1] = ClassMods.DeepCopy(ClassMods.timerbarDefaults[whichTab][i]) DB.timers["timerbar"..num].timers[#DB.timers["timerbar"..num].timers][19] = #DB.timers["timerbar"..num].timers count = count + 1 end end end ImportFromTab("timerbar1", num) ImportFromTab("timerbar2", num) ImportFromTab("timerbar3", num) print(L["CLASSMODS_PRE"] .. ": " .. format(L["TIMERSIMPORTED"], tostring(count) ) ) ClassMods.Options:LockDown(ClassMods.SetupTimers) DoPanel0(num) --return to prev panel! end, elementWidth / 2) -- Tab group local function DrawGroup(container, group) local scrollcontainer = AceGUI:Create("SimpleGroup") scrollcontainer:SetFullWidth(true) scrollcontainer:SetFullHeight(true) scrollcontainer:SetLayout("Fill") -- important! container:AddChild(scrollcontainer) local scroll = AceGUI:Create("ScrollFrame") scroll:SetLayout("Flow") scrollcontainer:AddChild(scroll) local drawTab = (group == "C") and "timerbar1" or (group == "P") and "timerbar2" or (group == "T") and "timerbar3" SortImportList(ClassMods.timerbarDefaults[drawTab]) for i=1,#ClassMods.timerbarDefaults[drawTab] do local cb = AceGUI:Create("CheckBox") local name, rank, icon = GetSpellInfo(ClassMods.timerbarDefaults[drawTab][i][1] or ClassMods.timerbarDefaults[drawTab][i][2]) cb:SetLabel(name) cb:SetValue(selectedImports[drawTab][i]) cb:SetCallback("OnValueChanged", function(widget) selectedImports[drawTab][i] = widget:GetValue() end) scroll:AddChild(cb) end end local function SelectGroup(container, event, group) lastTab = group container:ReleaseChildren() DrawGroup(container, group) wizFrame:SetStatusText((group == "C") and L["Cooldowns"] or (group == "P") and L["Player"] or (group == "T") and L["Target"]) end local tg = AceGUI:Create("TabGroup") tg:SetFullWidth(true) tg:SetFullHeight(true) tg:SetLayout("Fill") tg:SetTabs({ { value = "C", text = L["Cooldowns"] }, { value = "P", text = L["Player"] }, { value = "T", text = L["Target"] } }) tg:SetCallback("OnGroupSelected", SelectGroup) tg:SelectTab(lastTab or "C") wizFrame:AddChild(tg) end local function DoPanel1(num) wizFrame = TimerBars_CreateFrame(num) wizPanel = 1 -- What would you like to do? - label AddLabel(wizFrame, " ") AddLabel(wizFrame, L["Select how this bar's timers function:"], nil, 15) AddLabel(wizFrame, " ") AddLabel(wizFrame, " ") -- Change bar configuration - button AddButton(wizFrame, L["MOVE FROM BAR END TO BAR END BASED ON TIME"], function() ClassMods.db.profile.timers["timerbar"..num].stationary = false ClassMods.Options:LockDown(ClassMods.SetupTimers) print(L["CLASSMODS_PRE"] .. ": " .. L["TIMERBAR_SET_TO_MOVING"]) ClassMods.Options:LockDown(ClassMods.SetupTimers) DoPanel0(num) --return to prev panel! end) AddLabel(wizFrame, " ") -- Change bar configuration - button AddButton(wizFrame, L["STATIONARY ICONS IN A ROW (CAN OPTIONALLY HIDE)"], function() ClassMods.db.profile.timers["timerbar"..num].stationary = true ClassMods.db.profile.timers["timerbar"..num].prioritize = false for i = 1, #ClassMods.db.profile.timers["timerbar"..num].timers do ClassMods.db.profile.timers["timerbar"..num].timers[i][18] = 0 end ClassMods.Options:LockDown(ClassMods.SetupTimers) print(L["CLASSMODS_PRE"] .. ": " .. L["TIMERBAR_SET_TO_STATIONARY"]) ClassMods.Options:LockDown(ClassMods.SetupTimers) DoPanel0(num) --return to prev panel! end) AddLabel(wizFrame, " ") -- Change bar configuration - button AddButton(wizFrame, L["NON-STATIONARY ICONS ARRANGED BASED ON TIME & PRIORITY"], function() ClassMods.db.profile.timers["timerbar"..num].stationary = true ClassMods.db.profile.timers["timerbar"..num].prioritize = true for i = 1, #ClassMods.db.profile.timers["timerbar"..num].timers do ClassMods.db.profile.timers["timerbar"..num].timers[i][18] = 0 end ClassMods.Options:LockDown(ClassMods.SetupTimers) print(L["CLASSMODS_PRE"] .. ": " .. L["TIMERBAR_SET_TO_PRIORITY"]) ClassMods.Options:LockDown(ClassMods.SetupTimers) DoPanel0(num) --return to prev panel! end) AddLabel(wizFrame, " ") -- Testing notice AddLabel(wizFrame, L["TEST_IN_ACTION"]) end DoPanel0 = function(num) wizFrame = TimerBars_CreateFrame(num) wizPanel = 0 -- What would you like to do? - label AddLabel(wizFrame, " ") AddLabel(wizFrame, L["What would you like to do?"], nil, 15) AddLabel(wizFrame, " ") AddLabel(wizFrame, " ") -- Change bar configuration - button AddButton(wizFrame, L["CHANGE HOW THIS BAR FUNCTIONS"], function() DoPanel1(num) end) AddLabel(wizFrame, " ") -- Import individual timers AddButton(wizFrame, L["IMPORT INDIVIDUAL TIMERS"], function() DoPanel2(num) end) AddLabel(wizFrame, " ") -- Set order for priority bar timers if _G.ClassMods.Options.DB.timers["timerbar"..num].stationary then if _G.ClassMods.Options.DB.timers["timerbar"..num].prioritize then AddButton(wizFrame, L["CHANGE PRIORITY ORDER OF TIMERS"], function() DoPanel3(num) end) else AddButton(wizFrame, L["CHANGE ORDER OF TIMERS"], function() DoPanel3(num) end) end AddLabel(wizFrame, " ") end -- Delete all current timers AddButton(wizFrame, L["DELETE ALL CURRENT TIMERS FOR THIS BAR"], function() ClassMods.ConfirmActionDialog(L["DELETEALLTIMERS_CONFIRM"], function() ClassMods.ClearTimersForSet(num) LibStub("AceConfigRegistry-3.0"):NotifyChange("ClassMods") ClassMods.Options:LockDown(ClassMods.SetupTimers) end, nil) end) AddLabel(wizFrame, " ") -- Reset to default timers AddButton(wizFrame, L["REPLACE ALL CURRENT TIMERS WITH THE DEFAULTS"], function() ClassMods.ConfirmActionDialog(L["REVERTTIMERS_CONFIRM"], function() ClassMods.ImportDefaultTimersForSet(num) LibStub("AceConfigRegistry-3.0"):NotifyChange("ClassMods") ClassMods.Options:LockDown(ClassMods.SetupTimers) end, nil) end) end local onCloseHandler = nil local savedPoints = nil TimerBars_CreateFrame = function(num) if not AceGUI then AceGUI = LibStub("AceGUI-3.0") AceGUI:RegisterWidgetType("ClassMods_PriorityLine", ClassMods_PriorityLineConstructor, 1) end if wizFrame then wizFrame:Release() collectgarbage("collect") end local f = AceGUI:Create("Frame") f.frame:SetClampedToScreen(true) if savedPoints then f.frame:ClearAllPoints() f.frame:SetPoint(unpack(savedPoints) ) end f:SetTitle(L["TIMER BAR"].." "..num.. " "..L["WIZARD"]) f:SetStatusText("") f:SetLayout("Flow") f:SetWidth(panelWidth) f:SetHeight(panelHeight) f:SetAutoAdjustHeight(true) -- Disable sizing f.sizer_e:Hide() f.sizer_se:Hide() -- We need to free memory from garbage created by Ace after closing the options panel onCloseHandler = f.events["OnClose"] or nil -- Ace hack f:SetCallback("OnClose", function(...) savedPoints = { f.frame:GetPoint() } if (wizPanel ~= 0) then DoPanel0(num) return else if (not LibStub("AceConfigDialog-3.0").OpenFrames["ClassMods"]) then ClassMods.OpenOptions() end end if onCloseHandler then onCloseHandler(...) end collectgarbage("collect") end) return f end function ClassMods.Wizard_TimerBars(num) if wizFrame and wizFrame.frame and wizFrame.frame:IsShown() then return end if LibStub("AceConfigDialog-3.0").OpenFrames["ClassMods"] then ClassMods.CloseOptions() GameTooltip:Hide() -- Prevents lingering tip from Wizard button end DoPanel0(num) end
for var=exp1,exp2,exp3 do -- for 1 -- local 1 local something for var=exp1,exp2,exp3 do -- for 2 -- local 2 local something for var=exp1,exp2,exp3 do -- for 3 -- local 3 local something for var=exp1,exp2,exp3 do -- for 4 -- local 4 local something end end end end for var=exp1,exp2,exp3 do -- for 4 -- local 4 local something end
-- All bases have 40mm width g_base_width_inches = 1.5748031496062992126 -- All bases are 3mm tall g_base_height_inches = 0.11811023622047244094 -- The default table is not at y=0 position, but rather a bit higher g_base_height_tabletop = 1.06 -- Position in the y axis of a standard height base in the graveyard -- Equivalent to table level + graveyardheight - 0.5*g_base_height_inches g_graveyard_y_pos = 1.16 -- The DBA tables are 3mm thick/tall g_table_thickness = 0.11811023622047244094 g_bases_position = g_base_height_inches + g_table_thickness + g_base_height_tabletop g_terrain_pos = 1.2 -- Shooting range in BW g_bow_range = 3 * g_base_width_inches g_art_range = 5 * g_base_width_inches g_wwg_range = 3 * g_base_width_inches -- Initial distance spawns from the center g_spawn_from_center_in = 16 -- Distance from the center on the x axis, a general offset to deploy on the -- side of the table g_offset_deployment_x = 25 -- How many bases needed to create another row of bases -- on deployment g_max_bases_row = 12 -- Width and Depth (width in the Z azis) of the playing DBA table, in inches g_width_table_in = 23.62204724409448818898 g_depth_table_in = 23.62204724409448818898 g_width_large_table_in = g_width_table_in * 1.333 g_depth_large_table_in = g_depth_table_in * 1.333 -- Maximum distance between the center of bases for autoalignment, squared g_max_distance_alignment = 2^2 -- Angle for alignment front-to-back instead of side-to-side, in radians g_alignment_angle_side = math.rad(30) -- Max angle between elements for pushing back a column g_max_angle_pushback_rad = math.rad(15) -- Max distance in inches between corenrs for aligment when snapping, squared g_max_corner_distance_snap = 0.2*0.2 g_max_camp_edge_snap = 1 -- Max distance in inches between corenrs for aligment when snapping -- when the two bases intersect, i.e. the units are on top of each other. -- Since stacking is not allowed in DBA, we can have a big value. g_max_corner_distance_snap_intersect = 0.6 g_max_corner_distance_snap_intersect_sq = g_max_corner_distance_snap_intersect * g_max_corner_distance_snap_intersect -- Command distances from the general g_command_distance_short = 4 * g_base_width_inches g_command_distance_long = 8 * g_base_width_inches -- When drawing a circle (moving troops, or bow arcs, we use a certain -- number of points (they are straight lines), this marks how many points -- Must be divisible by 4 g_precision_circle = 32 -- Movement gizmos, fire arcs and deployment guidelines all have -- lines painted. This control how thick in inches the lines are g_line_thickness = 0.04 -- When moving, if you move less than this inches, the base will snap -- to this original position, making it easier to undo a move. g_max_inches_snap_reset = 20/100 -- Troops spawn with a random facing angle, this control how much they can vary -- Note that this goes from -g_max_angle_spawn to g_max_angle_spawn -- It's in degrees g_max_angle_spawn = 20 -- Troops that are marked as loose (warbands, psiloi etc) may be moved around -- a little bit for a better representation. This controls how much, in inches g_max_loose_spawn = 0.15 -- How many seconds until the table locks itself g_seconds_until_table_lock = 5 -- Color of the gizmos for movement/firearcs for each player g_gizmo_color_player_red = { 0.9, 0.1, 0.1 } g_gizmo_color_player_blue = { 0.1, 0.1, 0.9 } g_gizmo_fire_color_player_red = { 1, 0.6, 0.1 } g_gizmo_fire_color_player_blue = { 0.15, 0.6, 0.2 } g_gizmo_zoc_color_player_red = { 0.6, 0.25, 0.15 } g_gizmo_zoc_color_player_blue = { 0.15, 0.25, 0.4 } g_gizmo_color_command = { 0.8, 0.8, 0.8 } -- How frequently the main loop runs, in seconds -- The main loop redraws selections, movement, etc g_seconds_main_loop = 0.1 -- How close to a exact movement (paces or BW) should be the slider to snap g_ui_snap_slider_movement = 0.1 -- Models use this collider so they are easier to move minimal_collider = 'http://cloud-3.steamusercontent.com/ugc/1022823184773057328/6E2E42ECBBD40D7501018921FC5898568FF9D748/' -- Each army book will add to this, but the object table needs to be created -- first armies = { }
local entity = {} entity["level"] = [[11]] entity["spellDeck"] = {} entity["spellDeck"][1] = [[Cleave]] entity["spellDeck"][2] = [[]] entity["spellDeck"][3] = [[Dodge Slash]] entity["spellDeck"][4] = [[]] entity["spellDeck"][5] = [[]] entity["spellDeck"][6] = [[]] entity["heritage"] = {} entity["heritage"][1] = [[Slash]] entity["heritage"][2] = [[]] entity["resistance"] = {} entity["resistance"][1] = [[Strong]] entity["resistance"][2] = [[Normal]] entity["resistance"][3] = [[Normal]] entity["resistance"][4] = [[Weak]] entity["resistance"][5] = [[Normal]] entity["resistance"][6] = [[Normal]] entity["resistance"][7] = [[Normal]] entity["resistance"][8] = [[Normal]] entity["resistance"][9] = [[Normal]] entity["desc"] = [[Choosers of the slain" in Norse lore. Armed with shining armor and swords, they look for brave warriors to take to Valhalla, so that they may fight in Ragnarok.]] --a function: evolveName entity["arcana"] = [[Judgement]] entity["stats"] = {} entity["stats"][1] = [[10]] entity["stats"][2] = [[7]] entity["stats"][3] = [[8]] entity["stats"][4] = [[8]] entity["stats"][5] = [[7]] entity["name"] = [[Valkyrie]] entity["spellLearn"] = {} entity["spellLearn"]["Auto-Sukukaja"] = [[14]] entity["spellLearn"]["Power Slash"] = [[15]] entity["spellLearn"]["Mabufu"] = [[13]] return entity
local _G = _G; local ABP_4H = _G.ABP_4H; local pos = { healerTL = { 40, 25 }, healerTR1 = { 67, 20 }, healerTR2 = { 64, 30 }, healerTR3 = { 67, 40 }, healerBL = { 40, 60 }, healerBR = { 65, 60 }, tankdpsTL = { 29, 28 }, tankdpsTR = { 76, 28 }, tankdpsBL = { 29, 69 }, tankdpsBR = { 76, 69 }, safe = { 52, 52 }, }; local marks = { tl = 28833, tr = 28835, bl = 28832, br = 28834, }; local smallPos = { [pos.healerTR1] = true, [pos.healerTR2] = true, [pos.healerTR3] = true }; local markPositions = { [marks.tl] = { [pos.tankdpsTL] = true, [pos.healerTL] = true }, [marks.tr] = { [pos.tankdpsTR] = true, [pos.healerTR1] = true, [pos.healerTR2] = true, [pos.healerTR3] = true }, [marks.bl] = { [pos.tankdpsBL] = true, [pos.healerBL] = true }, [marks.br] = { [pos.tankdpsBR] = true, [pos.healerBR] = true }, }; local bosses = { korthazz = 16064, blaumeux = 16065, mograine = 16062, zeliek = 16063, rivendare = 30549, -- retail only (replacement for mograine) }; local bossMarks = { [bosses.korthazz] = marks.bl, [bosses.blaumeux] = marks.tl, [bosses.mograine] = marks.br, [bosses.rivendare] = marks.br, [bosses.zeliek] = marks.tr, }; local roles = { dps1 = "dps1", dps2 = "dps2", dps3 = "dps3", dps4 = "dps4", tank1 = "tank1", tank2 = "tank2", tank3 = "tank3", tank4 = "tank4", ot1 = "ot1", ot2 = "ot2", ot3 = "ot3", ot4 = "ot4", healer1 = "healer1", healer2 = "healer2", healer3 = "healer3", healer4 = "healer4", healer5 = "healer5", healer6 = "healer6", healer7 = "healer7", healer8 = "healer8", healer9 = "healer9", healer10 = "healer10", healer11 = "healer11", healer12 = "healer12", healerccw1 = "healerccw1", healerccw2 = "healerccw2", healerccw3 = "healerccw3", healerccw4 = "healerccw4", healerccw5 = "healerccw5", healerccw6 = "healerccw6", healerccw7 = "healerccw7", healerccw8 = "healerccw8", healerccw9 = "healerccw9", healerccw10 = "healerccw10", healerccw11 = "healerccw11", healerccw12 = "healerccw12", }; local healerMap = { [roles.healer1] = roles.healerccw1, [roles.healer2] = roles.healerccw2, [roles.healer3] = roles.healerccw3, [roles.healer4] = roles.healerccw4, [roles.healer5] = roles.healerccw5, [roles.healer6] = roles.healerccw6, [roles.healer7] = roles.healerccw7, [roles.healer8] = roles.healerccw8, [roles.healer9] = roles.healerccw9, [roles.healer10] = roles.healerccw10, [roles.healer11] = roles.healerccw11, [roles.healer12] = roles.healerccw12, }; local rolesSorted = { roles.dps1, roles.dps2, roles.dps3, roles.dps4, roles.tank1, roles.tank2, roles.tank3, roles.tank4, roles.ot1, roles.ot2, roles.ot3, roles.ot4, roles.healer1, roles.healer2, roles.healer3, roles.healer4, roles.healer5, roles.healer6, roles.healer7, roles.healer8, roles.healer9, roles.healer10, roles.healer11, roles.healer12, }; local rolesSortedStatus = { roles.tank1, roles.tank3, roles.ot1, roles.ot3, roles.tank2, roles.tank4, roles.ot2, roles.ot4, roles.healer1, roles.healer4, roles.healer7, roles.healer10, roles.healer2, roles.healer5, roles.healer8, roles.healer11, roles.healer3, roles.healer6, roles.healer9, roles.healer12, roles.dps1, roles.dps2, roles.dps3, roles.dps4, }; local categories = { healer = "healer", tank = "tank", dps = "dps", }; local roleCategories = { [roles.dps1] = categories.dps, [roles.dps2] = categories.dps, [roles.dps3] = categories.dps, [roles.dps4] = categories.dps, [roles.tank1] = categories.tank, [roles.tank2] = categories.tank, [roles.tank3] = categories.tank, [roles.tank4] = categories.tank, [roles.ot1] = categories.tank, [roles.ot2] = categories.tank, [roles.ot3] = categories.tank, [roles.ot4] = categories.tank, [roles.healer1] = categories.healer, [roles.healer2] = categories.healer, [roles.healer3] = categories.healer, [roles.healer4] = categories.healer, [roles.healer5] = categories.healer, [roles.healer6] = categories.healer, [roles.healer7] = categories.healer, [roles.healer8] = categories.healer, [roles.healer9] = categories.healer, [roles.healer10] = categories.healer, [roles.healer11] = categories.healer, [roles.healer12] = categories.healer, }; local topRoles = { [roles.ot1] = true, [roles.ot2] = true, [roles.ot3] = true, [roles.ot4] = true, [roles.healer1] = true, [roles.healer2] = true, [roles.healer3] = true, [roles.healer4] = true, [roles.healer5] = true, [roles.healer6] = true, [roles.healer7] = true, [roles.healer8] = true, [roles.healer9] = true, [roles.healer10] = true, [roles.healer11] = true, [roles.healer12] = true, [roles.healerccw1] = true, [roles.healerccw2] = true, [roles.healerccw3] = true, [roles.healerccw4] = true, [roles.healerccw5] = true, [roles.healerccw6] = true, [roles.healerccw7] = true, [roles.healerccw8] = true, [roles.healerccw9] = true, [roles.healerccw10] = true, [roles.healerccw11] = true, [roles.healerccw12] = true, }; local raidRoles = { -- Group 1 roles.tank1, roles.tank2, roles.healer1, roles.healer2, roles.healer3, -- Group 2 roles.tank3, roles.tank4, roles.healer4, roles.healer5, roles.healer6, -- Group 3 roles.ot1, roles.ot2, roles.healer7, roles.healer8, roles.healer9, -- Group 4 roles.ot3, roles.ot4, roles.healer10, roles.healer11, roles.healer12, -- Group 5 roles.dps1, roles.dps1, roles.dps1, roles.dps1, roles.dps1, -- Group 6 roles.dps2, roles.dps2, roles.dps2, roles.dps2, roles.dps2, -- Group 7 roles.dps3, roles.dps3, roles.dps3, roles.dps3, roles.dps3, -- Group 8 roles.dps4, roles.dps4, roles.dps4, roles.dps4, roles.dps4, }; local roleNames = { [roles.dps1] = "DPS BL Start", [roles.dps2] = "DPS BR Start", [roles.dps3] = "DPS BL Safe", [roles.dps4] = "DPS BR Safe", [roles.tank1] = "Tank BL Start", [roles.tank2] = "Tank BL Safe", [roles.tank3] = "Tank BR Start", [roles.tank4] = "Tank BR Safe", [roles.ot1] = "Off Tank TL Start", [roles.ot2] = "Off Tank TL Safe", [roles.ot3] = "Off Tank TR Start", [roles.ot4] = "Off Tank TR Safe", [roles.healer1] = "Healer BL 1", [roles.healer2] = "Healer BL 2", [roles.healer3] = "Healer BL 3", [roles.healer4] = "Healer BR 1", [roles.healer5] = "Healer BR 2", [roles.healer6] = "Healer BR 3", [roles.healer7] = "Healer TL 1", [roles.healer8] = "Healer TL 2", [roles.healer9] = "Healer TL 3", [roles.healer10] = "Healer TR 1", [roles.healer11] = "Healer TR 2", [roles.healer12] = "Healer TR 3", [roles.healerccw1] = "Healer BL CCW 1", [roles.healerccw2] = "Healer BL CCW 2", [roles.healerccw3] = "Healer BL CCW 3", [roles.healerccw4] = "Healer BR CCW 1", [roles.healerccw5] = "Healer BR CCW 2", [roles.healerccw6] = "Healer BR CCW 3", [roles.healerccw7] = "Healer TL CCW 1", [roles.healerccw8] = "Healer TL CCW 2", [roles.healerccw9] = "Healer TL CCW 3", [roles.healerccw10] = "Healer TR CCW 1", [roles.healerccw11] = "Healer TR CCW 2", [roles.healerccw12] = "Healer TR CCW 3", }; local roleColors = { [roles.dps1] = "0099cc", [roles.dps2] = "0099cc", [roles.dps3] = "0099cc", [roles.dps4] = "0099cc", [roles.tank1] = "00cc00", [roles.tank2] = "00cc00", [roles.tank3] = "00cc00", [roles.tank4] = "00cc00", [roles.ot1] = "00cc00", [roles.ot2] = "00cc00", [roles.ot3] = "00cc00", [roles.ot4] = "00cc00", [roles.healer1] = "ffff66", [roles.healer2] = "ffff66", [roles.healer3] = "ffff66", [roles.healer4] = "ffff66", [roles.healer5] = "ffff66", [roles.healer6] = "ffff66", [roles.healer7] = "ffff66", [roles.healer8] = "ffff66", [roles.healer9] = "ffff66", [roles.healer10] = "ffff66", [roles.healer11] = "ffff66", [roles.healer12] = "ffff66", [roles.healerccw1] = "ffff66", [roles.healerccw2] = "ffff66", [roles.healerccw3] = "ffff66", [roles.healerccw4] = "ffff66", [roles.healerccw5] = "ffff66", [roles.healerccw6] = "ffff66", [roles.healerccw7] = "ffff66", [roles.healerccw8] = "ffff66", [roles.healerccw9] = "ffff66", [roles.healerccw10] = "ffff66", [roles.healerccw11] = "ffff66", [roles.healerccw12] = "ffff66", }; local roleNamesColored = {}; for role, name in pairs(roleNames) do roleNamesColored[role] = ("|cff%s%s|r"):format(roleColors[role], name); end local rotations = { [roles.dps1] = { [0] = pos.tankdpsBL, [3] = pos.safe, [6] = pos.tankdpsBR, [9] = pos.safe, [12] = pos.tankdpsBL }, [roles.dps2] = { [0] = pos.tankdpsBR, [3] = pos.safe, [6] = pos.tankdpsBL, [9] = pos.safe, [12] = pos.tankdpsBR }, [roles.dps3] = { [0] = pos.safe, [3] = pos.tankdpsBL, [6] = pos.safe, [9] = pos.tankdpsBR, [12] = pos.safe }, [roles.dps4] = { [0] = pos.safe, [3] = pos.tankdpsBR, [6] = pos.safe, [9] = pos.tankdpsBL, [12] = pos.safe }, [roles.tank1] = { [0] = pos.tankdpsBL, [3] = pos.safe, [6] = pos.tankdpsBR, [9] = pos.safe, [12] = pos.tankdpsBL }, [roles.tank2] = { [0] = pos.safe, [3] = pos.tankdpsBL, [6] = pos.safe, [9] = pos.tankdpsBR, [12] = pos.safe }, [roles.tank3] = { [0] = pos.tankdpsBR, [3] = pos.safe, [6] = pos.tankdpsBL, [9] = pos.safe, [12] = pos.tankdpsBR }, [roles.tank4] = { [0] = pos.safe, [3] = pos.tankdpsBR, [6] = pos.safe, [9] = pos.tankdpsBL, [12] = pos.safe }, [roles.ot1] = { [0] = pos.tankdpsTL, [3] = pos.safe, [6] = pos.tankdpsTR, [9] = pos.safe, [12] = pos.tankdpsTL }, [roles.ot2] = { [0] = pos.safe, [3] = pos.tankdpsTL, [6] = pos.safe, [9] = pos.tankdpsTR, [12] = pos.safe }, [roles.ot3] = { [0] = pos.tankdpsTR, [3] = pos.safe, [6] = pos.tankdpsTL, [9] = pos.safe, [12] = pos.tankdpsTR }, [roles.ot4] = { [0] = pos.safe, [3] = pos.tankdpsTR, [6] = pos.safe, [9] = pos.tankdpsTL, [12] = pos.safe }, [roles.healer1] = { [0] = pos.healerBL, [1] = pos.healerTL, [4] = pos.healerTR1, [5] = pos.healerTR2, [6] = pos.healerTR3, [7] = pos.healerBR, [10] = pos.healerBL }, [roles.healer2] = { [0] = pos.healerBL, [2] = pos.healerTL, [5] = pos.healerTR1, [6] = pos.healerTR2, [7] = pos.healerTR3, [8] = pos.healerBR, [11] = pos.healerBL }, [roles.healer3] = { [0] = pos.healerBL, [3] = pos.healerTL, [6] = pos.healerTR1, [7] = pos.healerTR2, [8] = pos.healerTR3, [9] = pos.healerBR, [12] = pos.healerBL }, [roles.healer4] = { [0] = pos.healerBR, [1] = pos.healerBL, [4] = pos.healerTL, [7] = pos.healerTR1, [8] = pos.healerTR2, [9] = pos.healerTR3, [10] = pos.healerBR }, [roles.healer5] = { [0] = pos.healerBR, [2] = pos.healerBL, [5] = pos.healerTL, [8] = pos.healerTR1, [9] = pos.healerTR2, [10] = pos.healerTR3, [11] = pos.healerBR }, [roles.healer6] = { [0] = pos.healerBR, [3] = pos.healerBL, [6] = pos.healerTL, [9] = pos.healerTR1, [10] = pos.healerTR2, [11] = pos.healerTR3, [12] = pos.healerBR }, [roles.healer7] = { [0] = pos.healerTL, [1] = pos.healerTR1, [2] = pos.healerTR2, [3] = pos.healerTR3, [4] = pos.healerBR, [7] = pos.healerBL, [10] = pos.healerTL }, [roles.healer8] = { [0] = pos.healerTL, [2] = pos.healerTR1, [3] = pos.healerTR2, [4] = pos.healerTR3, [5] = pos.healerBR, [8] = pos.healerBL, [11] = pos.healerTL }, [roles.healer9] = { [0] = pos.healerTL, [3] = pos.healerTR1, [4] = pos.healerTR2, [5] = pos.healerTR3, [6] = pos.healerBR, [9] = pos.healerBL, [12] = pos.healerTL }, [roles.healer10] = { [0] = pos.healerTR3, [1] = pos.healerBR, [4] = pos.healerBL, [7] = pos.healerTL, [10] = pos.healerTR1, [11] = pos.healerTR2, [12] = pos.healerTR3 }, [roles.healer11] = { [0] = pos.healerTR2, [1] = pos.healerTR3, [2] = pos.healerBR, [5] = pos.healerBL, [8] = pos.healerTL, [11] = pos.healerTR1, [12] = pos.healerTR2 }, [roles.healer12] = { [0] = pos.healerTR1, [1] = pos.healerTR2, [2] = pos.healerTR3, [3] = pos.healerBR, [6] = pos.healerBL, [9] = pos.healerTL, [12] = pos.healerTR1 }, [roles.healerccw1] = { [0] = pos.healerBL, [1] = pos.healerBR, [4] = pos.healerTR3, [5] = pos.healerTR2, [6] = pos.healerTR1, [7] = pos.healerTL, [10] = pos.healerBL }, [roles.healerccw2] = { [0] = pos.healerBL, [2] = pos.healerBR, [5] = pos.healerTR3, [6] = pos.healerTR2, [7] = pos.healerTR1, [8] = pos.healerTL, [11] = pos.healerBL }, [roles.healerccw3] = { [0] = pos.healerBL, [3] = pos.healerBR, [6] = pos.healerTR3, [7] = pos.healerTR2, [8] = pos.healerTR1, [9] = pos.healerTL, [12] = pos.healerBL }, [roles.healerccw4] = { [0] = pos.healerBR, [1] = pos.healerTR3, [2] = pos.healerTR2, [3] = pos.healerTR1, [4] = pos.healerTL, [7] = pos.healerBL, [10] = pos.healerBR }, [roles.healerccw5] = { [0] = pos.healerBR, [2] = pos.healerTR3, [3] = pos.healerTR2, [4] = pos.healerTR1, [5] = pos.healerTL, [8] = pos.healerBL, [11] = pos.healerBR }, [roles.healerccw6] = { [0] = pos.healerBR, [3] = pos.healerTR3, [4] = pos.healerTR2, [5] = pos.healerTR1, [6] = pos.healerTL, [9] = pos.healerBL, [12] = pos.healerBR }, [roles.healerccw7] = { [0] = pos.healerTL, [1] = pos.healerBL, [4] = pos.healerBR, [7] = pos.healerTR3, [8] = pos.healerTR2, [9] = pos.healerTR1, [10] = pos.healerTL }, [roles.healerccw8] = { [0] = pos.healerTL, [2] = pos.healerBL, [5] = pos.healerBR, [8] = pos.healerTR3, [9] = pos.healerTR2, [10] = pos.healerTR1, [11] = pos.healerTL }, [roles.healerccw9] = { [0] = pos.healerTL, [3] = pos.healerBL, [6] = pos.healerBR, [9] = pos.healerTR3, [10] = pos.healerTR2, [11] = pos.healerTR1, [12] = pos.healerTL }, [roles.healerccw10] = { [0] = pos.healerTR1, [1] = pos.healerTL, [4] = pos.healerBL, [7] = pos.healerBR, [10] = pos.healerTR3, [11] = pos.healerTR2, [12] = pos.healerTR1 }, [roles.healerccw11] = { [0] = pos.healerTR2, [1] = pos.healerTR1, [2] = pos.healerTL, [5] = pos.healerBL, [8] = pos.healerBR, [11] = pos.healerTR3, [12] = pos.healerTR2 }, [roles.healerccw12] = { [0] = pos.healerTR3, [1] = pos.healerTR2, [2] = pos.healerTR1, [3] = pos.healerTL, [6] = pos.healerBL, [9] = pos.healerBR, [12] = pos.healerTR3 }, }; for _, rotation in pairs(rotations) do local pos = rotation[0]; for i = 1, 12 do if not rotation[i] then rotation[i] = pos; end pos = rotation[i]; end end local modes = { manual = "manual", timer = "timer", live = "live", }; local modeNames = { [modes.live] = "Live", [modes.manual] = "Manual", [modes.timer] = "Timed", }; ABP_4H.Roles = roles; ABP_4H.RolesSorted = rolesSorted; ABP_4H.RolesSortedStatus = rolesSortedStatus; ABP_4H.RaidRoles = raidRoles; ABP_4H.RoleNames = roleNames; ABP_4H.RoleNamesColored = roleNamesColored; ABP_4H.MapPositions = pos; ABP_4H.SmallPositions = smallPos; ABP_4H.Rotations = rotations; ABP_4H.Modes = modes; ABP_4H.ModeNames = modeNames; ABP_4H.Categories = categories; ABP_4H.RoleCategories = roleCategories; ABP_4H.Marks = marks; ABP_4H.MarkPositions = markPositions; ABP_4H.Bosses = bosses; ABP_4H.BossMarks = bossMarks; ABP_4H.HealerMap = healerMap; ABP_4H.TopRoles = topRoles;
--!strict -- override math -- local math = require(Path.To.ThisModule) local Math = {} Math.tau = math.pi * 2 -- Replacement for math.round that allows defining the number of places. function Math.roundPlaces(number: number, places: number): number local places = places or 0 local exponent = 10^places if places == 0 then return math.round(number) end return math.round(number * exponent) / exponent end -- Alias. clamp a value between 0 and 1. function Math.clamp01(value: number): number return math.clamp(value, 0, 1) end -- Returns whether or not the given value is not a number. function Math.isNAN(value: number): boolean return value ~= value -- If the value is a number, it will always equal itself. NAN has a quirk where it does NOT equal itself. Use this. end -- Identical to clamp01, but assumes the given value is a ratio and may be the result of dividing zero by zero. Uses the given fallback value, or 0. function Math.clampRatio01(value: number, retnIfNan: number?): number if Math.isNAN(value) then return retnIfNan or 0 end return Math.clamp01(value) end -- Alias. Linear Interpolation from start -> goal by alpha% function Math.lerp(start: number, goal: number, alpha: number): number return ((goal - start) * alpha) + start end -- Akin to lerp, but this adds/subtracts increment to start so that it approaches goal -- Note that a negative increment will indeed cause backwards interpolation -- If the distance between start and goal is less than the increment, then the goal itself will be returned function Math.constinterp(start: number, goal: number, increment: number): number if start == goal then return goal end if math.abs(goal - start) < increment then return goal end if start > goal then return start - increment else return start + increment end end -- Interpolates from start => goal by the given increment. -- If the difference between the start and goal are less than the increment, then the goal is returned. -- Unlike constinterp, this is designed for the express purpose of handling rotations in the range of [0, ฯ„] -- This also enforces that increment is a positive value, so unlike constinterp, repulsion cannot be performed. -- Due to the rotation behaviors, this may return any value *equivalent* to the given rotation (not necessarily -- a linear transition based on increment), and so the receiver of this function's result should handle this appropriately. function Math.constinterpRadians(start: number, goal: number, increment: number): number local increment = math.abs(increment) if start == goal then return goal end goal = Math.wrap(goal, 0, Math.tau) start = Math.wrap(start, 0, Math.tau) if start == goal then return goal end if math.abs(goal - start) < increment then return goal end local delta = math.abs(goal - start) if delta > math.pi then -- The angle difference is over 180. -- This means that it's actually *less* than 180 as far as the shortest path is concerned, so we need to rearrange it so it takes the -- short path instead of going around the entire circle. if goal > start then -- The goal is greater than start, for extreme example, start may be 5deg and goal may be 355deg -- addd Tau to goal so that it becomes 365deg, now it will go backwards to 355 start += Math.tau else -- Similar case to above goal += Math.tau end end if start > goal then return start - increment else return start + increment end end -- Alias. Map a value from a range into another range, e.g. say I have a value that can range from 0 to 100, and I want to make that scale into 69 to 420, this can do it. function Math.map(x: number, inMin: number, inMax: number, outMin: number, outMax: number): number if outMin == outMax then return outMin end -- If the range is 0, then just return that value and don't waste time on the math. return (x - inMin) * (outMax - outMin) / (inMax - inMin) + outMin; end -- Maps a number in the range of [min, max] to the range of [0, 1]. This is the inverse of map01to function Math.mapto01(x: number, min: number, max: number): number return (x - min) / (max - min) end -- Maps a number in the range of [0, 1] to the range of [min, max]. This is the inverse of mapto01 function Math.map01to(x: number, min: number, max: number): number local alt = max - min return (x * alt) + min end -- Wraps x into the given range. -- For example, if the range is [0, 5], and x is 6, then the returned value is 1. function Math.wrap(x: number, min: number, max: number): number local maxAdj = max - min local xAdj = x - min return (((xAdj % maxAdj) + maxAdj) % maxAdj) + min end setmetatable(Math, {__index = math}) table.freeze(Math::any) return Math
function love.conf(t) t.window.width = 1280 t.window.height = 960 t.window.title = 'DEFENSELESS' end
--------------------------------------------------------------------------- --- Prompt module for awful. -- -- **Keyboard navigation**: -- -- The following readline keyboard shortcuts are implemented as expected: -- <table class='widget_list' border=1> -- <tr><th>Name</th><th>Usage</th></tr> -- <tr><td><kbd>CTRL+A</kbd></td><td>beginning-of-line</td></tr> -- <tr><td><kbd>CTRL+B</kbd></td><td>backward-char</td></tr> -- <tr><td><kbd>CTRL+C</kbd></td><td>cancel</td></tr> -- <tr><td><kbd>CTRL+D</kbd></td><td>delete-char</td></tr> -- <tr><td><kbd>CTRL+E</kbd></td><td>end-of-line</td></tr> -- <tr><td><kbd>CTRL+J</kbd></td><td>accept-line</td></tr> -- <tr><td><kbd>CTRL+M</kbd></td><td>accept-line</td></tr> -- <tr><td><kbd>CTRL+F</kbd></td><td>move-cursor-right</td></tr> -- <tr><td><kbd>CTRL+H</kbd></td><td>backward-delete-char</td></tr> -- <tr><td><kbd>CTRL+K</kbd></td><td>kill-line</td></tr> -- <tr><td><kbd>CTRL+U</kbd></td><td>unix-line-discard</td></tr> -- <tr><td><kbd>CTRL+W</kbd></td><td>unix-word-rubout</td></tr> -- <tr><td><kbd>CTRL+BACKSPACE</kbd></td><td>unix-word-rubout</td></tr> -- <tr><td><kbd>SHIFT+INSERT</kbd></td><td>paste</td></tr> -- <tr><td><kbd>HOME</kbd></td><td>beginning-of-line</td></tr> -- <tr><td><kbd>END</kbd></td><td>end-of-line</td></tr> -- </table> -- -- The following shortcuts implement additional history manipulation commands -- where the search term is defined as the substring of the command from first -- character to cursor position. -- -- * <kbd>CTRL+R</kbd>: reverse history search, matches any history entry -- containing search term. -- * <kbd>CTRL+S</kbd>: forward history search, matches any history entry -- containing search term. -- * <kbd>CTRL+UP</kbd>: ZSH up line or search, matches any history entry -- starting with search term. -- * <kbd>CTRL+DOWN</kbd>: ZSH down line or search, matches any history -- entry starting with search term. -- * <kbd>CTRL+DELETE</kbd>: delete the currently visible history entry from -- history file. This does not delete new commands or history entries under -- user editing. -- -- **Basic usage**: -- -- By default, `rc.lua` will create one `awful.widget.prompt` per screen called -- `mypromptbox`. It is used for both the command execution (`mod4+r`) and -- Lua prompt (`mod4+x`). It can be re-used for random inputs using: -- -- -- -- -- Then **IN THE globalkeys TABLE** add a new shortcut -- awful.key({ modkey }, "e", echo_test, -- {description = "Echo a string", group = "custom"}), -- -- Note that this assumes an `rc.lua` file based on the default one. The way -- to access the screen prompt may vary. -- -- **Extra key hooks**: -- -- The Awesome prompt also supports adding custom extensions to specific -- keyboard keybindings. Those keybindings have precedence over the built-in -- ones. Therefor, they can be used to override the default ones. -- -- *[Example one] Adding pre-configured `awful.spawn` commands:* -- -- -- -- *[Example two] Modifying the command (+ vi like input)*: -- -- The hook system also allows to modify the command before interpreting it in -- the `exe_callback`. -- -- -- -- *[Example three] Key listener*: -- -- The 2 previous examples were focused on changing the prompt behavior. This -- one explains how to "spy" on the prompt events. This can be used for -- -- * Implementing more complex mutator -- * Synchronising other widgets -- * Showing extra tips to the user -- -- -- -- **highlighting**: -- -- The prompt also support custom highlighters: -- -- -- -- @author Julien Danjou &lt;[email protected]&gt; -- @copyright 2008 Julien Danjou -- @module awful.prompt --------------------------------------------------------------------------- --- The prompt cursor foreground color. -- @beautiful beautiful.prompt_fg_cursor -- @param color -- @see gears.color --- The prompt cursor background color. -- @beautiful beautiful.prompt_bg_cursor -- @param color -- @see gears.color --- The prompt text font. -- @beautiful beautiful.prompt_font -- @param string -- @see string -- Grab environment we need local io = io local table = table local math = math local ipairs = ipairs local pcall = pcall local capi = { selection = selection } local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1) local keygrabber = require("awful.keygrabber") local beautiful = require("beautiful") local akey = require("awful.key") local gdebug = require('gears.debug') local gtable = require("gears.table") local gcolor = require("gears.color") local gstring = require("gears.string") local gfs = require("gears.filesystem") local prompt = {} --- Private data local data = {} data.history = {} local search_term = nil local function itera (inc,a, i) i = i + inc local v = a[i] if v then return i,v end end --- Load history file in history table -- @param id The data.history identifier which is the path to the filename. -- @param[opt] max The maximum number of entries in file. local function history_check_load(id, max) if id and id ~= "" and not data.history[id] then data.history[id] = { max = 50, table = {} } if max then data.history[id].max = max end local f = io.open(id, "r") if not f then return end -- Read history file for line in f:lines() do if gtable.hasitem(data.history[id].table, line) == nil then table.insert(data.history[id].table, line) if #data.history[id].table >= data.history[id].max then break end end end f:close() end end local function is_word_char(c) if string.find("[{[(,.:;_-+=@/ ]", c) then return false else return true end end local function cword_start(s, pos) local i = pos if i > 1 then i = i - 1 end while i >= 1 and not is_word_char(s:sub(i, i)) do i = i - 1 end while i >= 1 and is_word_char(s:sub(i, i)) do i = i - 1 end if i <= #s then i = i + 1 end return i end local function cword_end(s, pos) local i = pos while i <= #s and not is_word_char(s:sub(i, i)) do i = i + 1 end while i <= #s and is_word_char(s:sub(i, i)) do i = i + 1 end return i end --- Save history table in history file -- @param id The data.history identifier local function history_save(id) if data.history[id] then gfs.make_parent_directories(id) local f = io.open(id, "w") if not f then gdebug.print_warning("Failed to write the history to "..id) return end for i = 1, math.min(#data.history[id].table, data.history[id].max) do f:write(data.history[id].table[i] .. "\n") end f:close() end end --- Return the number of items in history table regarding the id -- @param id The data.history identifier -- @return the number of items in history table, -1 if history is disabled local function history_items(id) if data.history[id] then return #data.history[id].table else return -1 end end --- Add an entry to the history file -- @param id The data.history identifier -- @param command The command to add local function history_add(id, command) if data.history[id] and command ~= "" then local index = gtable.hasitem(data.history[id].table, command) if index == nil then table.insert(data.history[id].table, command) -- Do not exceed our max_cmd if #data.history[id].table > data.history[id].max then table.remove(data.history[id].table, 1) end history_save(id) else -- Bump this command to the end of history table.remove(data.history[id].table, index) table.insert(data.history[id].table, command) history_save(id) end end end --- Draw the prompt text with a cursor. -- @tparam table args The table of arguments. -- @field text The text. -- @field font The font. -- @field prompt The text prefix. -- @field text_color The text color. -- @field cursor_color The cursor color. -- @field cursor_pos The cursor position. -- @field cursor_ul The cursor underline style. -- @field selectall If true cursor is rendered on the entire text. local function prompt_text_with_cursor(args) local char, spacer, text_start, text_end, ret local text = args.text or "" local _prompt = args.prompt or "" local underline = args.cursor_ul or "none" if args.selectall then if #text == 0 then char = " " else char = gstring.xml_escape(text) end spacer = " " text_start = "" text_end = "" elseif #text < args.cursor_pos then char = " " spacer = "" text_start = gstring.xml_escape(text) text_end = "" else char = gstring.xml_escape(text:sub(args.cursor_pos, args.cursor_pos)) spacer = " " text_start = gstring.xml_escape(text:sub(1, args.cursor_pos - 1)) text_end = gstring.xml_escape(text:sub(args.cursor_pos + 1)) end local cursor_color = gcolor.ensure_pango_color(args.cursor_color) local text_color = gcolor.ensure_pango_color(args.text_color) if args.highlighter then text_start, text_end = args.highlighter(text_start, text_end) end ret = _prompt .. text_start .. "<span background=\"" .. cursor_color .. "\" foreground=\"" .. text_color .. "\" underline=\"" .. underline .. "\">" .. char .. "</span>" .. text_end .. spacer return ret end --- The callback function to call with command as argument when finished. -- @usage local function my_exe_cb(command) -- -- do something -- end -- @callback exe_callback -- @tparam string command The command (as entered). --- The callback function to get completions. -- @usage local function my_completion_cb(command_before_comp, cur_pos_before_comp, ncomp) -- return command_before_comp.."foo", cur_pos_before_comp+3, 1 -- end -- -- @callback completion_callback -- @tparam string command_before_comp The current command. -- @tparam number cur_pos_before_comp The current cursor position. -- @tparam number ncomp The number of the currently completed element. -- @treturn string command -- @treturn number cur_pos -- @treturn number matches --- The callback function to always call without arguments, regardless of -- whether the prompt was cancelled. -- @usage local function my_done_cb() -- -- do something -- end -- @callback done_callback --- The callback function to call with command as argument when a command was -- changed. -- @usage local function my_changed_cb(command) -- -- do something -- end -- @callback changed_callback -- @tparam string command The current command. --- The callback function to call with mod table, key and command as arguments -- when a key was pressed. -- @usage local function my_keypressed_cb(mod, key, command) -- -- do something -- end -- @callback keypressed_callback -- @tparam table mod The current modifiers (like "Control" or "Shift"). -- @tparam string key The key name. -- @tparam string command The current command. --- The callback function to call with mod table, key and command as arguments -- when a key was released. -- @usage local function my_keyreleased_cb(mod, key, command) -- -- do something -- end -- @callback keyreleased_callback -- @tparam table mod The current modifiers (like "Control" or "Shift"). -- @tparam string key The key name. -- @tparam string command The current command. --- A function to add syntax highlighting to the command. -- @usage local function my_highlighter(before_cursor, after_cursor) -- -- do something -- return before_cursor, after_cursor -- end -- @callback highlighter -- @tparam string before_cursor -- @tparam string after_cursor --- A callback when a key combination is triggered. -- This callback can return many things: -- -- * a modified command -- * `true` If the command is successful (then it won't exit) -- * nothing or `nil` to execute the `exe_callback` and `done_callback` and exit -- -- An optional second return value controls if the prompt should exit or simply -- update the command (from the first return value) and keep going. The default -- is to execute the `exe_callback` and `done_callback` before exiting. -- -- @usage local function my_hook(command) -- return command.."foo", false -- end -- -- @callback hook -- @tparam string command The current command. --- Run a prompt in a box. -- -- @tparam[opt={}] table args A table with optional arguments -- @tparam[opt] gears.color args.fg_cursor -- @tparam[opt] gears.color args.bg_cursor -- @tparam[opt] gears.color args.ul_cursor -- @tparam[opt] widget args.prompt -- @tparam[opt] string args.text -- @tparam[opt] boolean args.selectall -- @tparam[opt] string args.font -- @tparam[opt] boolean args.autoexec -- @tparam widget args.textbox The textbox to use for the prompt. -- @tparam[opt] function args.highlighter A function to add syntax highlighting to -- the command. -- @tparam function args.exe_callback The callback function to call with command as argument -- when finished. -- @tparam function args.completion_callback The callback function to call to get completion. -- @tparam[opt] string args.history_path File path where the history should be -- saved, set nil to disable history -- @tparam[opt] function args.history_max Set the maximum entries in history -- file, 50 by default -- @tparam[opt] function args.done_callback The callback function to always call -- without arguments, regardless of whether the prompt was cancelled. -- @tparam[opt] function args.changed_callback The callback function to call -- with command as argument when a command was changed. -- @tparam[opt] function args.keypressed_callback The callback function to call -- with mod table, key and command as arguments when a key was pressed. -- @tparam[opt] function args.keyreleased_callback The callback function to call -- with mod table, key and command as arguments when a key was pressed. -- @tparam[opt] table args.hooks The "hooks" argument uses a syntax similar to -- `awful.key`. It will call a function for the matching modifiers + key. -- It receives the command (widget text/input) as an argument. -- If the callback returns a command, this will be passed to the -- `exe_callback`, otherwise nothing gets executed by default, and the hook -- needs to handle it. -- hooks = { -- -- Apply startup notification properties with Shift-Return. -- {{"Shift" }, "Return", function(command) -- awful.screen.focused().mypromptbox:spawn_and_handle_error( -- command, {floating=true}) -- end}, -- -- Override default behavior of "Return": launch commands prefixed -- -- with ":" in a terminal. -- {{}, "Return", function(command) -- if command:sub(1,1) == ":" then -- return terminal .. ' -e ' .. command:sub(2) -- end -- return command -- end} -- } -- @param textbox The textbox to use for the prompt. [**DEPRECATED**] -- @param exe_callback The callback function to call with command as argument -- when finished. [**DEPRECATED**] -- @param completion_callback The callback function to call to get completion. -- [**DEPRECATED**] -- @param[opt] history_path File path where the history should be -- saved, set nil to disable history [**DEPRECATED**] -- @param[opt] history_max Set the maximum entries in history -- file, 50 by default [**DEPRECATED**] -- @param[opt] done_callback The callback function to always call -- without arguments, regardless of whether the prompt was cancelled. -- [**DEPRECATED**] -- @param[opt] changed_callback The callback function to call -- with command as argument when a command was changed. [**DEPRECATED**] -- @param[opt] keypressed_callback The callback function to call -- with mod table, key and command as arguments when a key was pressed. -- [**DEPRECATED**] -- @see gears.color function prompt.run(args, textbox, exe_callback, completion_callback, history_path, history_max, done_callback, changed_callback, keypressed_callback) local grabber local theme = beautiful.get() if not args then args = {} end local command = args.text or "" local command_before_comp local cur_pos_before_comp local prettyprompt = args.prompt or "" local inv_col = args.fg_cursor or theme.prompt_fg_cursor or theme.fg_focus or "black" local cur_col = args.bg_cursor or theme.prompt_bg_cursor or theme.bg_focus or "white" local cur_ul = args.ul_cursor local text = args.text or "" local font = args.font or theme.prompt_font or theme.font local selectall = args.selectall local highlighter = args.highlighter local hooks = {} local deprecated = function(name) gdebug.deprecate(string.format( 'awful.prompt.run: the argument %s is deprecated, please use args.%s instead', name, name), {raw=true, deprecated_in=4}) end if textbox then deprecated('textbox') end if exe_callback then deprecated('exe_callback') end if completion_callback then deprecated('completion_callback') end if history_path then deprecated('history_path') end if history_max then deprecated('history_max') end if done_callback then deprecated('done_callback') end if changed_callback then deprecated('changed_callback') end if keypressed_callback then deprecated('keypressed_callback') end -- This function has already an absurd number of parameters, allow them -- to be set using the args to avoid a "nil, nil, nil, nil, foo" scenario keypressed_callback = keypressed_callback or args.keypressed_callback changed_callback = changed_callback or args.changed_callback done_callback = done_callback or args.done_callback history_max = history_max or args.history_max history_path = history_path or args.history_path completion_callback = completion_callback or args.completion_callback exe_callback = exe_callback or args.exe_callback textbox = textbox or args.textbox if not textbox then return end search_term=nil history_check_load(history_path, history_max) local history_index = history_items(history_path) + 1 -- The cursor position local cur_pos = (selectall and 1) or text:wlen() + 1 -- The completion element to use on completion request. local ncomp = 1 -- Build the hook map for _,v in ipairs(args.hooks or {}) do if #v == 3 then local _,key,callback = unpack(v) if type(callback) == "function" then hooks[key] = hooks[key] or {} hooks[key][#hooks[key]+1] = v else gdebug.print_warning("The hook's 3rd parameter has to be a function.") end else gdebug.print_warning("The hook has to have 3 parameters.") end end textbox:set_font(font) textbox:set_markup(prompt_text_with_cursor{ text = text, text_color = inv_col, cursor_color = cur_col, cursor_pos = cur_pos, cursor_ul = cur_ul, selectall = selectall, prompt = prettyprompt, highlighter = highlighter}) local function exec(cb, command_to_history) textbox:set_markup("") history_add(history_path, command_to_history) keygrabber.stop(grabber) if cb then cb(command) end if done_callback then done_callback() end end -- Update textbox local function update() textbox:set_font(font) textbox:set_markup(prompt_text_with_cursor{ text = command, text_color = inv_col, cursor_color = cur_col, cursor_pos = cur_pos, cursor_ul = cur_ul, selectall = selectall, prompt = prettyprompt, highlighter = highlighter }) end grabber = keygrabber.run( function (modifiers, key, event) -- Convert index array to hash table local mod = {} for _, v in ipairs(modifiers) do mod[v] = true end if event ~= "press" then if args.keyreleased_callback then args.keyreleased_callback(mod, key, command) end return end -- Call the user specified callback. If it returns true as -- the first result then return from the function. Treat the -- second and third results as a new command and new prompt -- to be set (if provided) if keypressed_callback then local user_catched, new_command, new_prompt = keypressed_callback(mod, key, command) if new_command or new_prompt then if new_command then command = new_command end if new_prompt then prettyprompt = new_prompt end update() end if user_catched then if changed_callback then changed_callback(command) end return end end local filtered_modifiers = {} -- User defined cases if hooks[key] then -- Remove caps and num lock for _, m in ipairs(modifiers) do if not gtable.hasitem(akey.ignore_modifiers, m) then table.insert(filtered_modifiers, m) end end for _,v in ipairs(hooks[key]) do if #filtered_modifiers == #v[1] then local match = true for _,v2 in ipairs(v[1]) do match = match and mod[v2] end if match then local cb local ret, quit = v[3](command) local original_command = command -- Support both a "simple" and a "complex" way to -- control if the prompt should quit. quit = quit == nil and (ret ~= true) or (quit~=false) -- Allow the callback to change the command command = (ret ~= true) and ret or command -- Quit by default, but allow it to be disabled if ret and type(ret) ~= "boolean" then cb = exe_callback if not quit then cur_pos = ret:wlen() + 1 update() end elseif quit then -- No callback. cb = function() end end -- Execute the callback if cb then exec(cb, original_command) end return end end end end -- Get out cases if (mod.Control and (key == "c" or key == "g")) or (not mod.Control and key == "Escape") then keygrabber.stop(grabber) textbox:set_markup("") history_save(history_path) if done_callback then done_callback() end return false elseif (mod.Control and (key == "j" or key == "m")) or (not mod.Control and key == "Return") or (not mod.Control and key == "KP_Enter") then exec(exe_callback, command) -- We already unregistered ourselves so we don't want to return -- true, otherwise we may unregister someone else. return end -- Control cases if mod.Control then selectall = nil if key == "a" then cur_pos = 1 elseif key == "b" then if cur_pos > 1 then cur_pos = cur_pos - 1 end elseif key == "d" then if cur_pos <= #command then command = command:sub(1, cur_pos - 1) .. command:sub(cur_pos + 1) end elseif key == "p" then if history_index > 1 then history_index = history_index - 1 command = data.history[history_path].table[history_index] cur_pos = #command + 2 end elseif key == "n" then if history_index < history_items(history_path) then history_index = history_index + 1 command = data.history[history_path].table[history_index] cur_pos = #command + 2 elseif history_index == history_items(history_path) then history_index = history_index + 1 command = "" cur_pos = 1 end elseif key == "e" then cur_pos = #command + 1 elseif key == "r" then search_term = search_term or command:sub(1, cur_pos - 1) for i,v in (function(a,i) return itera(-1,a,i) end), data.history[history_path].table, history_index do if v:find(search_term,1,true) ~= nil then command=v history_index=i cur_pos=#command+1 break end end elseif key == "s" then search_term = search_term or command:sub(1, cur_pos - 1) for i,v in (function(a,i) return itera(1,a,i) end), data.history[history_path].table, history_index do if v:find(search_term,1,true) ~= nil then command=v history_index=i cur_pos=#command+1 break end end elseif key == "f" then if cur_pos <= #command then cur_pos = cur_pos + 1 end elseif key == "h" then if cur_pos > 1 then command = command:sub(1, cur_pos - 2) .. command:sub(cur_pos) cur_pos = cur_pos - 1 end elseif key == "k" then command = command:sub(1, cur_pos - 1) elseif key == "u" then command = command:sub(cur_pos, #command) cur_pos = 1 elseif key == "Up" then search_term = command:sub(1, cur_pos - 1) or "" for i,v in (function(a,i) return itera(-1,a,i) end), data.history[history_path].table, history_index do if v:find(search_term,1,true) == 1 then command=v history_index=i break end end elseif key == "Down" then search_term = command:sub(1, cur_pos - 1) or "" for i,v in (function(a,i) return itera(1,a,i) end), data.history[history_path].table, history_index do if v:find(search_term,1,true) == 1 then command=v history_index=i break end end elseif key == "w" or key == "BackSpace" then local wstart = 1 local wend = 1 local cword_start_pos = 1 local cword_end_pos = 1 while wend < cur_pos do wend = command:find("[{[(,.:;_-+=@/ ]", wstart) if not wend then wend = #command + 1 end if cur_pos >= wstart and cur_pos <= wend + 1 then cword_start_pos = wstart cword_end_pos = cur_pos - 1 break end wstart = wend + 1 end command = command:sub(1, cword_start_pos - 1) .. command:sub(cword_end_pos + 1) cur_pos = cword_start_pos elseif key == "Delete" then -- delete from history only if: -- we are not dealing with a new command -- the user has not edited an existing entry if command == data.history[history_path].table[history_index] then table.remove(data.history[history_path].table, history_index) if history_index <= history_items(history_path) then command = data.history[history_path].table[history_index] cur_pos = #command + 2 elseif history_index > 1 then history_index = history_index - 1 command = data.history[history_path].table[history_index] cur_pos = #command + 2 else command = "" cur_pos = 1 end end end elseif mod.Mod1 or mod.Mod3 then if key == "b" then cur_pos = cword_start(command, cur_pos) elseif key == "f" then cur_pos = cword_end(command, cur_pos) elseif key == "d" then command = command:sub(1, cur_pos - 1) .. command:sub(cword_end(command, cur_pos)) elseif key == "BackSpace" then local wstart = cword_start(command, cur_pos) command = command:sub(1, wstart - 1) .. command:sub(cur_pos) cur_pos = wstart end else if completion_callback then if key == "Tab" or key == "ISO_Left_Tab" then if key == "ISO_Left_Tab" or mod.Shift then if ncomp == 1 then return end if ncomp == 2 then command = command_before_comp textbox:set_font(font) textbox:set_markup(prompt_text_with_cursor{ text = command_before_comp, text_color = inv_col, cursor_color = cur_col, cursor_pos = cur_pos, cursor_ul = cur_ul, selectall = selectall, prompt = prettyprompt }) cur_pos = cur_pos_before_comp ncomp = 1 return end ncomp = ncomp - 2 elseif ncomp == 1 then command_before_comp = command cur_pos_before_comp = cur_pos end local matches command, cur_pos, matches = completion_callback(command_before_comp, cur_pos_before_comp, ncomp) ncomp = ncomp + 1 key = "" -- execute if only one match found and autoexec flag set if matches and #matches == 1 and args.autoexec then exec(exe_callback) return end elseif key ~= "Shift_L" and key ~= "Shift_R" then ncomp = 1 end end -- Typin cases if mod.Shift and key == "Insert" then local selection = capi.selection() if selection then -- Remove \n local n = selection:find("\n") if n then selection = selection:sub(1, n - 1) end command = command:sub(1, cur_pos - 1) .. selection .. command:sub(cur_pos) cur_pos = cur_pos + #selection end elseif key == "Home" then cur_pos = 1 elseif key == "End" then cur_pos = #command + 1 elseif key == "BackSpace" then if cur_pos > 1 then command = command:sub(1, cur_pos - 2) .. command:sub(cur_pos) cur_pos = cur_pos - 1 end elseif key == "Delete" then command = command:sub(1, cur_pos - 1) .. command:sub(cur_pos + 1) elseif key == "Left" then cur_pos = cur_pos - 1 elseif key == "Right" then cur_pos = cur_pos + 1 elseif key == "Up" then if history_index > 1 then history_index = history_index - 1 command = data.history[history_path].table[history_index] cur_pos = #command + 2 end elseif key == "Down" then if history_index < history_items(history_path) then history_index = history_index + 1 command = data.history[history_path].table[history_index] cur_pos = #command + 2 elseif history_index == history_items(history_path) then history_index = history_index + 1 command = "" cur_pos = 1 end else -- wlen() is UTF-8 aware but #key is not, -- so check that we have one UTF-8 char but advance the cursor of # position if key:wlen() == 1 then if selectall then command = "" end command = command:sub(1, cur_pos - 1) .. key .. command:sub(cur_pos) cur_pos = cur_pos + #key end end if cur_pos < 1 then cur_pos = 1 elseif cur_pos > #command + 1 then cur_pos = #command + 1 end selectall = nil end local success = pcall(update) while not success do -- TODO UGLY HACK TODO -- Setting the text failed. Most likely reason is that the user -- entered a multibyte character and pressed backspace which only -- removed the last byte. Let's remove another byte. if cur_pos <= 1 then -- No text left?! break end command = command:sub(1, cur_pos - 2) .. command:sub(cur_pos) cur_pos = cur_pos - 1 success = pcall(update) end if changed_callback then changed_callback(command) end end) end return prompt -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
package.path = "../?.lua;../?/init.lua;" .. package.path local png = require 'glua.lib.png' local bitmap, width, height, channels = png.Bitmap('textures/GraniteWall-ColorMap.png') print('width='..width) print('height='..height) print('channels='..channels)
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- --- Get configuration form ngx.shared.DICT -- -- @module core.config_xds local config_local = require("apisix.core.config_local") local string = require("apisix.core.string") local log = require("apisix.core.log") local json = require("apisix.core.json") local ngx_sleep = require("apisix.core.utils").sleep local check_schema = require("apisix.core.schema").check local new_tab = require("table.new") local table = table local insert_tab = table.insert local error = error local pcall = pcall local tostring = tostring local setmetatable = setmetatable local io = io local io_open = io.open local io_close = io.close local package = package local ipairs = ipairs local type = type local sub_str = string.sub local ffi = require ("ffi") local C = ffi.C local config = ngx.shared["xds-config"] local conf_ver = ngx.shared["xds-config-version"] local is_http = ngx.config.subsystem == "http" local ngx_re_match = ngx.re.match local ngx_re_gmatch = ngx.re.gmatch local ngx_timer_every = ngx.timer.every local ngx_timer_at = ngx.timer.at local exiting = ngx.worker.exiting local ngx_time = ngx.time local xds_lib_name = "libxds.so" local process if is_http then process = require("ngx.process") end local shdict_udata_to_zone if not pcall(function() return C.ngx_http_lua_ffi_shdict_udata_to_zone end) then shdict_udata_to_zone = C.ngx_meta_lua_ffi_shdict_udata_to_zone else shdict_udata_to_zone = C.ngx_http_lua_ffi_shdict_udata_to_zone end ffi.cdef[[ typedef unsigned int useconds_t; extern void initial(void* config_zone, void* version_zone); int usleep(useconds_t usec); ]] local created_obj = {} local _M = { version = 0.1, local_conf = config_local.local_conf, } local mt = { __index = _M, __tostring = function(self) return " xds key: " .. self.key end } -- todo: refactor this function in chash.lua and radixtree.lua local function load_shared_lib(lib_name) local cpath = package.cpath local tried_paths = new_tab(32, 0) local i = 1 local iter, err = ngx_re_gmatch(cpath, "[^;]+", "jo") if not iter then error("failed to gmatch: " .. err) end while true do local it = iter() local fpath fpath, err = ngx_re_match(it[0], "(.*/)", "jo") if err then error("failed to match: " .. err) end local spath = fpath[0] .. lib_name local f = io_open(spath) if f ~= nil then io_close(f) return ffi.load(spath) end tried_paths[i] = spath i = i + 1 if not it then break end end return nil, tried_paths end local function load_libxds(lib_name) local xdsagent, tried_paths = load_shared_lib(lib_name) if not xdsagent then tried_paths[#tried_paths + 1] = 'tried above paths but can not load ' .. lib_name error("can not load xds library, tried paths: " .. table.concat(tried_paths, '\r\n', 1, #tried_paths)) end local config_zone = shdict_udata_to_zone(config[1]) local config_shd_cdata = ffi.cast("void*", config_zone) local conf_ver_zone = shdict_udata_to_zone(conf_ver[1]) local conf_ver_shd_cdata = ffi.cast("void*", conf_ver_zone) xdsagent.initial(config_shd_cdata, conf_ver_shd_cdata) end local latest_version local function sync_data(self) if self.conf_version == latest_version then return true end if self.values then for _, val in ipairs(self.values) do if val and val.clean_handlers then for _, clean_handler in ipairs(val.clean_handlers) do clean_handler(val) end val.clean_handlers = nil end end self.values = nil self.values_hash = nil end local keys = config:get_keys(0) if not keys or #keys <= 0 then -- xds did not write any data to shdict return false, "no keys" end self.values = new_tab(#keys, 0) self.values_hash = new_tab(0, #keys) for _, key in ipairs(keys) do if string.has_prefix(key, self.key) then local data_valid = true local conf_str = config:get(key, 0) local conf, err = json.decode(conf_str) if not conf then data_valid = false log.error("decode the conf of [", key, "] failed, err: ", err, ", conf_str: ", conf_str) end if not self.single_item and type(conf) ~= "table" then data_valid = false log.error("invalid conf of [", key, "], conf: ", conf, ", it should be an object") end if data_valid and self.item_schema then local ok, err = check_schema(self.item_schema, conf) if not ok then data_valid = false log.error("failed to check the conf of [", key, "] err:", err) end end if data_valid and self.checker then local ok, err = self.checker(conf) if not ok then data_valid = false log.error("failed to check the conf of [", key, "] err:", err) end end if data_valid then if not conf.id then conf.id = sub_str(key, #self.key + 2, #key + 1) log.warn("the id of [", key, "] is nil, use the id: ", conf.id) end local conf_item = {value = conf, modifiedIndex = latest_version, key = key} insert_tab(self.values, conf_item) self.values_hash[conf.id] = #self.values conf_item.clean_handlers = {} if self.filter then self.filter(conf_item) end end end end self.conf_version = latest_version return true end local function _automatic_fetch(premature, self) if premature then return end local i = 0 while not exiting() and self.running and i <= 32 do i = i + 1 local ok, ok2, err = pcall(sync_data, self) if not ok then err = ok2 log.error("failed to fetch data from xds: ", err, ", ", tostring(self)) ngx_sleep(3) break elseif not ok2 and err then -- todo: handler other error if err ~= "wait for more time" and err ~= "no keys" and self.last_err ~= err then log.error("failed to fetch data from xds, ", err, ", ", tostring(self)) end if err ~= self.last_err then self.last_err = err self.last_err_time = ngx_time() else if ngx_time() - self.last_err_time >= 30 then self.last_err = nil end end ngx_sleep(0.5) elseif not ok2 then ngx_sleep(0.05) else ngx_sleep(0.1) end end if not exiting() and self.running then ngx_timer_at(0, _automatic_fetch, self) end end local function fetch_version(premature) if premature then return end local version = conf_ver:get("version") if not version then return end if version ~= latest_version then latest_version = version end end function _M.new(key, opts) local automatic = opts and opts.automatic local item_schema = opts and opts.item_schema local filter_fun = opts and opts.filter local single_item = opts and opts.single_item local checker = opts and opts.checker local obj = setmetatable({ automatic = automatic, item_schema = item_schema, checker = checker, sync_times = 0, running = true, conf_version = 0, values = nil, routes_hash = nil, prev_index = nil, last_err = nil, last_err_time = nil, key = key, single_item = single_item, filter = filter_fun, }, mt) if automatic then if not key then return nil, "missing `key` argument" end -- blocking until xds completes initial configuration while true do C.usleep(0.1) fetch_version() if latest_version then break end end local ok, ok2, err = pcall(sync_data, obj) if not ok then err = ok2 end if err then log.error("failed to fetch data from xds ", err, ", ", key) end ngx_timer_at(0, _automatic_fetch, obj) end if key then created_obj[key] = obj end return obj end function _M.get(self, key) if not self.values_hash then return end local arr_idx = self.values_hash[tostring(key)] if not arr_idx then return nil end return self.values[arr_idx] end function _M.fetch_created_obj(key) return created_obj[key] end function _M.init_worker() if process.type() == "privileged agent" then load_libxds(xds_lib_name) end ngx_timer_every(1, fetch_version) return true end return _M
mobs:register_mob("dmobs:gnorm", { type = "npc", can_dig = true, passive = true, reach = 1, damage = 1, attack_type = "dogfight", hp_min = 32, hp_max = 42, armor = 130, collisionbox = {-0.4, -0.3, -0.4, 0.4, 0.8, 0.4}, visual = "mesh", mesh = "gnorm.b3d", textures = { {"dmobs_gnorm.png"}, }, blood_texture = "mobs_blood.png", visual_size = {x=1, y=1}, makes_footstep_sound = true, runaway = true, walk_velocity = 0.5, run_velocity = 4, jump = true, water_damage = 0, lava_damage = 2, fire_damage = 2, light_damage = 0, fall_damage = 1, fall_speed = -6, fear_height = 4, replace_rate = 10, replace_what = { "default:apple", "default:stone", "default:stone_with_coal", "default:fence_wood" }, replace_with = "air", follow = {"default:apple"}, view_range = 14, animation = { speed_normal = 8, speed_run = 30, walk_start = 62, walk_end = 81, stand_start = 2, stand_end = 9, run_start = 62, run_end = 81, punch_start = 1, punch_end = 1, }, on_rightclick = function(self, clicker) if mobs:feed_tame(self, clicker, 8, true, true) then return end mobs:capture_mob(self, clicker, 0, 5, 50, false, nil) end, }) mobs:register_egg("dmobs:gnorm", "Gnorm", "default_dirt.png", 1)
--[[ The MIT License (MIT) Copyright (c) 2015 Matthias Richter 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. ]]-- return { description = "Vignette overlay", new = function(self) self.canvas = love.graphics.newCanvas() self.shader = love.graphics.newShader[[ extern number radius; extern number softness; extern number opacity; extern number aspect; vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _) { color = Texel(texture, tc); number v = smoothstep(radius, radius-softness, length((tc - vec2(0.5f)) * aspect)); return mix(color, color * v, opacity); } ]] self.shader:send("radius",1) self.shader:send("softness",.45) self.shader:send("opacity",.5) self.shader:send("aspect", love.graphics.getWidth() / love.graphics.getHeight()) end, draw = function(self, func, ...) self:_apply_shader_to_scene(self.shader, self.canvas, func, ...) end, set = function(self, key, value) if key == "radius" or key == "softness" or key == "opacity" then self.shader:send(key, math.max(0, tonumber(value) or 0)) rawset(self,key,math.max(0, tonumber(value) or 0)) else error("Unknown property: " .. tostring(key)) end return self end }
Script.ReloadScript("scripts/gamerules/GameRulesUtils.lua"); Miscreated = { Properties = { AirDrop = { fMinTime = 300, -- min time to spawn a plane (in seconds) fMaxTime = 600, -- max time to spawn a plane (in seconds) } } } GameRulesSetStandardFuncs(Miscreated); function Miscreated.Server:OnInit() self:CreateAirDropPlaneTimer() end ---------------------------------------------------------------------------------------------------- -- Support for the air drop planes to spawn ---------------------------------------------------------------------------------------------------- function Miscreated:CreateAirDropPlaneTimer() --Log("Miscreated.CreateAirDropPlaneTimer") Script.SetTimerForFunction(randomF(self.Properties.AirDrop.fMinTime*1000, self.Properties.AirDrop.fMaxTime*1000), "SpawnAirDropPlane", self) end SpawnAirDropPlane = function(self) --Log("Miscreated:SpawnAirDropPlane") local spawnParams = {} spawnParams.class = "AirDropPlane" spawnParams.name = spawnParams.class Log("Miscreated:SpawnAirDropPlane - Spawning AirDropPlane") local spawnedEntity = System.SpawnEntity(spawnParams) if not spawnedEntity then Log("Miscreated:SpawnAirDropPlane - AirDropPlane could not be spawned") end -- set timer up for the next plane self:CreateAirDropPlaneTimer() end ---------------------------------------------------------------------------------------------------- -- Support for custom chat command mods ---------------------------------------------------------------------------------------------------- -- Table for custom chat commands to use ChatCommands = { } -- Load custom chat commands (mods) Script.LoadScriptFolder("Scripts/GameRules/ChatCommands", true, true) -- Receives all unhandled, by the core game, chat commands -- Do not add custom chat commands directly here -- Add new chat commands to a file in the Scripts/GameRules/ChatCommands folder, -- so they can be uploaded as mods to Steam function Miscreated:ChatCommand(playerId, command) --Log(">> Miscreated:ChatCommand"); -- player is an entity local player = System.GetEntity(playerId) if not player.player then Log("Miscreated:ChatCommand - playerId is not a valid player") return end -- Find the requested chat command and execute it local index = string.find(command, " ") if not index then if ChatCommands[command] then ChatCommands[command](playerId, "") end else local cmd = string.sub(command, 1, index - 1) if ChatCommands[cmd] then ChatCommands[cmd](playerId, string.sub(command, index + 1)) end end end ---------------------------------------------------------------------------------------------------- -- Support for custom player spawns ---------------------------------------------------------------------------------------------------- -- See BattleRoyale.lua for a more complete example of the following 3 methods -- If this method is defined, then Miscreated will ONLY spawn items for a new or respawned -- player based on the code below. -- This is called after the player starts the spawning process -- Add any custom equipment or other finalizing touches here --[[ function Miscreated:EquipPlayer(playerId) --Log(">> Miscreated:EquipPlayer"); -- Get the entity for the player local player = System.GetEntity(playerId); -- Verify the player is of type "actor" - sanity check if (player and player.actor) then -- Give an AT15 to playerId into whatever slot is available and have the player select it local weaponId = ISM.GiveItem(playerId, "AT15", true); -- Add a STANAGx30 to playerId into the stanag_mag00 slot of the AT15 -- Slot names can be found in the item XML files and they start at index 00 and increment up from there local accessoryId = ISM.GiveItem(playerId, "STANAGx30", false, weaponId, "stanag_mag00"); end end --]]
SimpleUnitFramesDB = { ["profileKeys"] = { ["่ฝ่ตŽ - ็ขง็Ž‰็Ÿฟๆดž"] = "่ฝ่ตŽ - ็ขง็Ž‰็Ÿฟๆดž", ["้…ธๆฉ™ๅญ - ้พ™ไน‹ๅฌๅ”ค"] = "้…ธๆฉ™ๅญ - ้พ™ไน‹ๅฌๅ”ค", }, ["profiles"] = { ["่ฝ่ตŽ - ็ขง็Ž‰็Ÿฟๆดž"] = { ["party"] = { ["rhp"] = "HPnone", ["mmp"] = "MPcurrent", ["rmp"] = "MPnone", }, ["player"] = { ["rhp"] = "HPnone", ["mmp"] = "MPnone", ["rmp"] = "MPnone", ["mhp"] = "HPnone", }, ["target"] = { ["mhp"] = "HPnone", ["mmp"] = "MPnone", }, ["targettarget"] = { ["rmp"] = "MPnone", ["rhp"] = "HPnone", ["mmp"] = "MPcurrent", }, }, ["้…ธๆฉ™ๅญ - ้พ™ไน‹ๅฌๅ”ค"] = { ["target"] = { ["mhp"] = "HPnone", ["mmp"] = "MPnone", }, ["party"] = { ["rmp"] = "MPnone", ["mhp"] = "HPcurrmax", ["rhp"] = "HPnone", ["mmp"] = "MPcurrent", }, ["targettarget"] = { ["rmp"] = "MPnone", ["rhp"] = "HPnone", ["mmp"] = "MPcurrent", }, ["player"] = { ["rmp"] = "MPnone", ["mhp"] = "HPnone", ["rhp"] = "HPnone", ["mmp"] = "MPnone", }, }, }, }
syntax = {} local syntax = syntax syntax.DEFAULT = 1 syntax.KEYWORD = 2 syntax.IDENTIFIER = 3 syntax.STRING = 4 syntax.NUMBER = 5 syntax.OPERATOR = 6 syntax.types = { "default", "keyword", "identifier", "string", "number", "operator", "ccomment", "cmulticomment", "comment", "multicomment" } syntax.patterns = { [2] = "([%a_][%w_]*)", [4] = "(\".-\")", [5] = "([%d]+%.?%d*)", [6] = "([%+%-%*/%%%(%)%.,<>~=#:;{}%[%]])", [7] = "(//[^\n]*)", [8] = "(/%*.-%*/)", [9] = "(%-%-[^%[][^\n]*)", [10] = "(%-%-%[%[.-%]%])", [11] = "(%[%[.-%]%])", [12] = "('.-')", [13] = "(!+)", } syntax.colors = { Color(255, 255, 255), Color(127, 159, 191), Color(223, 223, 223), Color(191, 127, 127), Color(127, 191, 127), Color(191, 191, 159), Color(159, 159, 159), Color(159, 159, 159), Color(159, 159, 159), Color(159, 159, 159), Color(191, 159, 127), Color(191, 127, 127), Color(255, 0, 0), } syntax.keywords = { ["local"] = true, ["function"] = true, ["return"] = true, ["break"] = true, ["continue"] = true, ["end"] = true, ["if"] = true, ["not"] = true, ["while"] = true, ["for"] = true, ["repeat"] = true, ["until"] = true, ["do"] = true, ["then"] = true, ["true"] = true, ["false"] = true, ["nil"] = true, ["in"] = true } function syntax.process(code) local output, finds, types, a, b, c = {}, {}, {}, 0, 0, 0 while true do local temp = {} for k, v in pairs(syntax.patterns) do local aa, bb = code:find(v, b + 1) if aa then table.insert(temp, {k, aa, bb}) end end if #temp == 0 then break end table.sort(temp, function(a, b) return (a[2] == b[2]) and (a[3] > b[3]) or (a[2] < b[2]) end) c, a, b = unpack(temp[1]) table.insert(finds, a) table.insert(finds, b) table.insert(types, c == 2 and (syntax.keywords[code:sub(a, b)] and 2 or 3) or c) end for i = 1, #finds - 1 do local asdf = (i - 1) % 2 local sub = code:sub(finds[i + 0] + asdf, finds[i + 1] - asdf) table.insert(output, asdf == 0 and syntax.colors[types[1 + (i - 1) / 2]] or Color(0, 0, 0, 255)) table.insert(output, (asdf == 1 and sub:find("^%s+$")) and sub:gsub("%s", " ") or sub) end return output end local methods = { ["b"] = "api", ["l"] = "server", ["lb"] = "both", ["lc"] = "clients", ["lm"] = "self", ["ls"] = "shared", ["p"] = "server", ["pc"] = "clients", ["pm2"] = "self", ["pm"] = "self", ["ps"] = "shared", ["print"] = "server", ["printb"] = "both", ["printc"] = "clients", ["printm"] = "self", ["table"] = "server table", ["keys"] = "server keys", ["cl"] = "xserver", ["cl1"] = "#1", ["cl2"] = "#2", ["cl3"] = "#3", ["cl4"] = "#4", ["cl5"] = "#5", ["lfind"] = "server find", ["lmfind"] = "self find", } local col_server = Color(191, 159, 127) local col_client = Color(127, 191, 191) local col_cross = Color(100, 200, 100) local col_misc = Color(127, 191, 191) local col_pserver= Color(230, 109, 220) local col_pclient= Color(125, 109, 220) local col_command= Color(191, 159, 127) local colors = { ["b"] = col_server, ["l"] = col_server, ["lc"] = col_client, ["lm"] = col_client, ["p"] = col_pserver, ["pc"] = col_pclient, ["pm2"] = col_pclient, ["pm"] = col_pclient, ["print"] = col_pserver, ["printc"] = col_pclient, ["printm"] = col_pclient, ["table"] = col_pserver, ["keys"] = col_pserver, ["cl"] = col_cross, ["cl1"] = col_cross, ["cl2"] = col_cross, ["cl3"] = col_cross, ["cl4"] = col_cross, ["cl5"] = col_cross, ["lfind"] = col_pserver, ["lmfind"] = col_pclient, ["โ€ข"] = col_command, } local grey = Color(191, 191, 191) hook.Add("OnPlayerChat", "syntax", function(pCaller, strMessage, iTeam, bDead) local method, color -- for overrides local cmd, code = strMessage:match("^โ€ข (l[bcms]?) (.*)$") if not code then cmd, code = strMessage:match("^โ€ข (p[sc]?) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (pm[2]?) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (print[bcm]?) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (table) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (keys) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (cl[15]?) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (l[m]?find) (.*)$") end if not code then cmd, code = strMessage:match("^โ€ข (b) (.*)$") end if not code then cmd, code = strMessage:match("^(โ€ข) (.*)$") end if not code then method, code = strMessage:match("^~lsc ([^,]+),(.*)$") color = colors["lc"] method = easylua.FindEntity(method) method = IsValid(method) and (method.Nick and method:Nick()) or tostring(method) end if not code then return end local method = method or methods[cmd] if pCaller:IsAdmin () then chat.AddText (pCaller:Nick ():lower (), grey, cmd == "โ€ข" and "" or '@', color or colors[cmd] or col_misc, cmd == "โ€ข" and " sneezes" or method, grey, ": ", unpack(syntax.process(code))) return "" end end)
return LoadActor(THEME:GetPathG("ControllerStateDisplay","Center")) .. { InitCommand = function(self) self:xy(-8, 8) end }
local Draw = require("api.Draw") local UiMousePadding = require("mod.mouse_ui.api.gui.UiMousePadding") local UiMouseFit = require("mod.mouse_ui.api.gui.UiMouseFit") local UiMouseStyle = {} function UiMouseStyle.draw_vertical_line(x, y1, y2, color_dark, color_light) Draw.set_color(color_dark) Draw.line(x, y1, x, y2) Draw.set_color(color_light) Draw.line(x+1, y1, x+1, y2) end function UiMouseStyle.draw_panel(x, y, width, height, thickness, pressed, color, color_dark, color_light) Draw.set_color(color) Draw.filled_rect(x, y, width-1, height-1) if pressed then Draw.set_color(color_dark) else Draw.set_color(color_light) end for i = 0, thickness - 1 do Draw.line(x, y + i, x + width - i - thickness, y + i) Draw.line(x + i, y - 1, x + i, y + height - i - thickness) end if pressed then Draw.set_color(color_light) else Draw.set_color(color_dark) end for i = 0, thickness - 1 do Draw.line(x + (thickness - i - 1), y + height + i - thickness, x + width - (thickness - i), y + height + i - thickness) Draw.line(x + width + i - thickness, y + (thickness - i - 1), x + width + i - thickness, y + height - (thickness - i)) end end function UiMouseStyle.default_padding() return UiMousePadding:new_all(1) end function UiMouseStyle.default_fit() return UiMouseFit.none end return UiMouseStyle
function onCreate() makeLuaSprite('ship', 'among/documentroom', -100,600) addLuaSprite('ship', false) end
-- init file for kill_spikes local modpath = minetest.get_modpath("kill_spikes"); dofile(minetest.get_modpath('kill_spikes').."/kill_spikes.lua")
-- Some custom event hooks I call -- The following code calls a hook on both the client and the server. No built-in hooks seem to be called right when the Sending Client Info process is complete. if CLIENT then hook.Add( "InitPostEntity", "ARCLib_FullyLoadedConfirm", function() net.Start("ARCLib_FullyLoaded") net.SendToServer() end) net.Receive( "ARCLib_FullyLoaded", function(length) local ply = net.ReadEntity() if IsValid(ply) && ply:IsPlayer() then MsgN(ply:Nick().." is now fully loaded!") hook.Call( "ARCLib_OnPlayerFullyLoaded",GM,ply) end end) else util.AddNetworkString("ARCLib_FullyLoaded") net.Receive( "ARCLib_FullyLoaded", function(length,ply) if IsValid(ply) && !ply.ARCLib_FullyLoaded then MsgN(ply:Nick().." is now fully loaded!") net.Start("ARCLib_FullyLoaded") net.WriteEntity(ply) net.Broadcast() hook.Call( "ARCLib_OnPlayerFullyLoaded",GM,ply) ply.ARCLib_FullyLoaded = true end end) hook.Add( "PlayerInitialSpawn", "ARCLib SendSettings", function(ply) for k,v in pairs(ARCLib.AddonsUsingSettings) do ARCLib.SendAddonSettings(k,ply) end for k,v in pairs(ARCLib.AddonsUsingLanguages) do ARCLib.SendAddonLanguage(k,ply) end end) end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BceEnterRoom_pb', package.seeall) local BCEENTERROOM = protobuf.Descriptor(); local BCEENTERROOM_ROOMID_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_MAPID_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_ROOMNAME_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_ROOMKEY_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_ROOMTYPE_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_BATTLEMODE_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_CHOOSEMODE_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_CHALLENGEID_FIELD = protobuf.FieldDescriptor(); local BCEENTERROOM_HARDMODE_FIELD = protobuf.FieldDescriptor(); BCEENTERROOM_ROOMID_FIELD.name = "roomId" BCEENTERROOM_ROOMID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.roomId" BCEENTERROOM_ROOMID_FIELD.number = 1 BCEENTERROOM_ROOMID_FIELD.index = 0 BCEENTERROOM_ROOMID_FIELD.label = 2 BCEENTERROOM_ROOMID_FIELD.has_default_value = true BCEENTERROOM_ROOMID_FIELD.default_value = "" BCEENTERROOM_ROOMID_FIELD.type = 9 BCEENTERROOM_ROOMID_FIELD.cpp_type = 9 BCEENTERROOM_MAPID_FIELD.name = "mapId" BCEENTERROOM_MAPID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.mapId" BCEENTERROOM_MAPID_FIELD.number = 2 BCEENTERROOM_MAPID_FIELD.index = 1 BCEENTERROOM_MAPID_FIELD.label = 2 BCEENTERROOM_MAPID_FIELD.has_default_value = true BCEENTERROOM_MAPID_FIELD.default_value = -1 BCEENTERROOM_MAPID_FIELD.type = 5 BCEENTERROOM_MAPID_FIELD.cpp_type = 1 BCEENTERROOM_ROOMNAME_FIELD.name = "roomName" BCEENTERROOM_ROOMNAME_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.roomName" BCEENTERROOM_ROOMNAME_FIELD.number = 3 BCEENTERROOM_ROOMNAME_FIELD.index = 2 BCEENTERROOM_ROOMNAME_FIELD.label = 1 BCEENTERROOM_ROOMNAME_FIELD.has_default_value = true BCEENTERROOM_ROOMNAME_FIELD.default_value = "" BCEENTERROOM_ROOMNAME_FIELD.type = 9 BCEENTERROOM_ROOMNAME_FIELD.cpp_type = 9 BCEENTERROOM_ROOMKEY_FIELD.name = "roomKey" BCEENTERROOM_ROOMKEY_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.roomKey" BCEENTERROOM_ROOMKEY_FIELD.number = 4 BCEENTERROOM_ROOMKEY_FIELD.index = 3 BCEENTERROOM_ROOMKEY_FIELD.label = 1 BCEENTERROOM_ROOMKEY_FIELD.has_default_value = true BCEENTERROOM_ROOMKEY_FIELD.default_value = "" BCEENTERROOM_ROOMKEY_FIELD.type = 9 BCEENTERROOM_ROOMKEY_FIELD.cpp_type = 9 BCEENTERROOM_ROOMTYPE_FIELD.name = "roomType" BCEENTERROOM_ROOMTYPE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.roomType" BCEENTERROOM_ROOMTYPE_FIELD.number = 5 BCEENTERROOM_ROOMTYPE_FIELD.index = 4 BCEENTERROOM_ROOMTYPE_FIELD.label = 1 BCEENTERROOM_ROOMTYPE_FIELD.has_default_value = true BCEENTERROOM_ROOMTYPE_FIELD.default_value = 0 BCEENTERROOM_ROOMTYPE_FIELD.type = 5 BCEENTERROOM_ROOMTYPE_FIELD.cpp_type = 1 BCEENTERROOM_BATTLEMODE_FIELD.name = "battleMode" BCEENTERROOM_BATTLEMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.battleMode" BCEENTERROOM_BATTLEMODE_FIELD.number = 6 BCEENTERROOM_BATTLEMODE_FIELD.index = 5 BCEENTERROOM_BATTLEMODE_FIELD.label = 2 BCEENTERROOM_BATTLEMODE_FIELD.has_default_value = true BCEENTERROOM_BATTLEMODE_FIELD.default_value = 0 BCEENTERROOM_BATTLEMODE_FIELD.type = 5 BCEENTERROOM_BATTLEMODE_FIELD.cpp_type = 1 BCEENTERROOM_CHOOSEMODE_FIELD.name = "chooseMode" BCEENTERROOM_CHOOSEMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.chooseMode" BCEENTERROOM_CHOOSEMODE_FIELD.number = 7 BCEENTERROOM_CHOOSEMODE_FIELD.index = 6 BCEENTERROOM_CHOOSEMODE_FIELD.label = 2 BCEENTERROOM_CHOOSEMODE_FIELD.has_default_value = true BCEENTERROOM_CHOOSEMODE_FIELD.default_value = 0 BCEENTERROOM_CHOOSEMODE_FIELD.type = 5 BCEENTERROOM_CHOOSEMODE_FIELD.cpp_type = 1 BCEENTERROOM_CHALLENGEID_FIELD.name = "challengeId" BCEENTERROOM_CHALLENGEID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.challengeId" BCEENTERROOM_CHALLENGEID_FIELD.number = 8 BCEENTERROOM_CHALLENGEID_FIELD.index = 7 BCEENTERROOM_CHALLENGEID_FIELD.label = 1 BCEENTERROOM_CHALLENGEID_FIELD.has_default_value = false BCEENTERROOM_CHALLENGEID_FIELD.default_value = "" BCEENTERROOM_CHALLENGEID_FIELD.type = 9 BCEENTERROOM_CHALLENGEID_FIELD.cpp_type = 9 BCEENTERROOM_HARDMODE_FIELD.name = "hardmode" BCEENTERROOM_HARDMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom.hardmode" BCEENTERROOM_HARDMODE_FIELD.number = 9 BCEENTERROOM_HARDMODE_FIELD.index = 8 BCEENTERROOM_HARDMODE_FIELD.label = 1 BCEENTERROOM_HARDMODE_FIELD.has_default_value = false BCEENTERROOM_HARDMODE_FIELD.default_value = 0 BCEENTERROOM_HARDMODE_FIELD.type = 5 BCEENTERROOM_HARDMODE_FIELD.cpp_type = 1 BCEENTERROOM.name = "BceEnterRoom" BCEENTERROOM.full_name = ".com.xinqihd.sns.gameserver.proto.BceEnterRoom" BCEENTERROOM.nested_types = {} BCEENTERROOM.enum_types = {} BCEENTERROOM.fields = {BCEENTERROOM_ROOMID_FIELD, BCEENTERROOM_MAPID_FIELD, BCEENTERROOM_ROOMNAME_FIELD, BCEENTERROOM_ROOMKEY_FIELD, BCEENTERROOM_ROOMTYPE_FIELD, BCEENTERROOM_BATTLEMODE_FIELD, BCEENTERROOM_CHOOSEMODE_FIELD, BCEENTERROOM_CHALLENGEID_FIELD, BCEENTERROOM_HARDMODE_FIELD} BCEENTERROOM.is_extendable = false BCEENTERROOM.extensions = {} BceEnterRoom = protobuf.Message(BCEENTERROOM) _G.BCEENTERROOM_PB_BCEENTERROOM = BCEENTERROOM
local class = require 'lib.middleclass' -- Pass callbacks through to gamestate function love.mousepressed(x, y, button) if GameState then GameState:mousepressed(x, y, button) end if InputManager then InputManager:mousepressed(x,y,button) end end function love.mousemoved(x, y, dx, dy, istouch) if GameState then GameState:mousemoved(x, y, dx, dy, istouch) end if InputManager then InputManager:mousemoved(x,y,dx,dy,istouch) end end function love.mousereleased(x, y, button) if GameState then GameState:mousereleased(x, y, button) end if InputManager then InputManager:mousereleased(x, y, button) end end function love.wheelmoved(x, y) if GameState then GameState:wheelmoved(x, y) end end function love.resize(w, h) if System then System:updateWindowSize(w, h) end end local System = class('System') function System:initialize() self:updateWindowSize(love.graphics.getWidth(), love.graphics.getHeight()) self.flux = require('lib.flux') self.playerInput = require('controls') self.audio = require('audio.manager'):new() --self.mainMenu = require('mainmenu') end function System:updateWindowSize(w, h) self.w = w self.h = h end return System
local localPlayer = getLocalPlayer() questionsBike = { {"Yolun hangi tarafฤฑndan gitmelisiniz?", "Sol", "SaฤŸ", "Yukardakilerden hepsi.", 2}, {"Gรผvenlik ekipmanlarฤฑ(รถrneฤŸin;Kask) kullanmanฤฑn amacฤฑ nedir?", "Havalฤฑ gรถrรผnmek.", "Korunmak.", "Dikkat รงekmek.", 2}, {"Kamyonlarฤฑn kรถr noktasฤฑ neresidir:", "Gรถvdenin hemen arkasฤฑ.", "Kabinin hemen solu.", "Yukarฤฑdakilerden hepsi." , 3}, {"Trafik levhalarฤฑ genellikle hangi renkte olur?", "YeลŸil.", "Mavi.", "Kฤฑrmฤฑzฤฑ." , 3}, {"Bir motorsikletin trafiฤŸe รงฤฑkabilmesi iรงin en az kaรง CC motoru olmasฤฑ gerekmektedir?", "50cc", "125cc", "250cc" , 1}, {"Duble yollarda sรผrรผcรผ hangi ลŸeritte gitmelidir?", "Herhangi bir ลŸeritte.", "Sol ลŸeritte.", "SaฤŸ ลŸeritte sรผrรผp, sollama yapmak iรงin deฤŸiลŸtirmelidir.", 3}, {"Keskin viraja yavas girilmesinin sebebi nedir?", "Lastikleri korumak icin.", "Onunu gorebilmen icin.", "Eger yolda birisi varsa diye durmak icin.", 3}, {"Kasklar ne iรงin รผretilmiลŸtir?", "Havalฤฑ stickerlar yapฤฑลŸtฤฑrmak iรงin.", "Yรผzรผnรผzรผ polisten saklamak iรงin", "BaลŸฤฑnฤฑzฤฑ korumak iรงin." , 3}, {"Bir yangin musluguna kac feet yakinda parkedemezsin?", "10 feet", "15 feet", "20 feet", 2}, {"AลŸaฤŸฤฑdakilerden hangi motor bรผyรผklรผฤŸรผndeki bir aracฤฑ kullanmak iรงin ehliyet gerekmemektedir?", "50cc", "125cc", "250cc" , 1}, } guiIntroLabel1B = nil guiIntroProceedButtonB = nil guiIntroWindowB = nil guiQuestionLabelB = nil guiQuestionAnswer1RadioB = nil guiQuestionAnswer2RadioB = nil guiQuestionAnswer3RadioB = nil guiQuestionWindowB = nil guiFinalPassTextLabelB = nil guiFinalFailTextLabelB = nil guiFinalRegisterButtonB = nil guiFinalCloseButtonB = nil guiFinishWindowB = nil -- variable for the max number of possible questions local NoQuestions = 10 local NoQuestionToAnswer = 7 local correctAnswers = 0 local passPercent = 50 selection = {} -- functon makes the intro window for the quiz function createlicenseBikeTestIntroWindow() showCursor(true) local screenwidth, screenheight = guiGetScreenSize () local Width = 450 local Height = 200 local X = (screenwidth - Width)/2 local Y = (screenheight - Height)/2 guiIntroWindowB = guiCreateWindow ( X , Y , Width , Height , "Motor Yazฤฑlฤฑ Sฤฑnavฤฑ" , false ) guiCreateStaticImage (0.35, 0.1, 0.3, 0.2, "banner.png", true, guiIntroWindowB) guiIntroLabel1B = guiCreateLabel(0, 0.3,1, 0.5, [[Motosiklet yazฤฑlฤฑ sฤฑnavฤฑna katฤฑlacaksฤฑnฤฑz. Temel sรผrรผลŸ teorisi hakkฤฑnda 7 soru sorulacaktฤฑr. Sฤฑnavฤฑ geรงmek iรงin en az %50 puan almanฤฑz gerekmektedir. Bol ลžanslar.]], true, guiIntroWindowB) guiLabelSetHorizontalAlign ( guiIntroLabel1B, "center", true ) guiSetFont ( guiIntroLabel1B,"default-bold-small") guiIntroProceedButtonB = guiCreateButton ( 0.4 , 0.75 , 0.2, 0.1 , "Start Test" , true ,guiIntroWindowB) addEventHandler ( "onClientGUIClick", guiIntroProceedButtonB, function(button, state) if(button == "left" and state == "up") then -- start the quiz and hide the intro window startLicenceBikeTest() guiSetVisible(guiIntroWindowB, false) end end, false) end -- done bike up to here -- function create the question window function createBikeLicenseQuestionWindow(number) local screenwidth, screenheight = guiGetScreenSize () local Width = 450 local Height = 200 local X = (screenwidth - Width)/2 local Y = (screenheight - Height)/2 -- create the window guiQuestionWindowB = guiCreateWindow ( X , Y , Width , Height , "Soru: "..number.." / "..NoQuestionToAnswer , false ) guiQuestionLabelB = guiCreateLabel(0.1, 0.2, 0.9, 0.2, selection[number][1], true, guiQuestionWindowB) guiSetFont ( guiQuestionLabelB,"default-bold-small") guiLabelSetHorizontalAlign ( guiQuestionLabelB, "left", true) if not(selection[number][2]== "nil") then guiQuestionAnswer1RadioB = guiCreateRadioButton(0.1, 0.4, 0.9,0.1, selection[number][2], true,guiQuestionWindowB) end if not(selection[number][3] == "nil") then guiQuestionAnswer2RadioB = guiCreateRadioButton(0.1, 0.5, 0.9,0.1, selection[number][3], true,guiQuestionWindowB) end if not(selection[number][4]== "nil") then guiQuestionAnswer3RadioB = guiCreateRadioButton(0.1, 0.6, 0.9,0.1, selection[number][4], true,guiQuestionWindowB) end -- if there are more questions to go, then create a "next question" button if(number < NoQuestionToAnswer) then guiQuestionNextButtonB = guiCreateButton ( 0.4 , 0.75 , 0.2, 0.1 , "Sฤฑradaki Soru" , true ,guiQuestionWindowB) addEventHandler ( "onClientGUIClick", guiQuestionNextButtonB, function(button, state) if(button == "left" and state == "up") then local selectedAnswer = 0 -- check all the radio buttons and seleted the selectedAnswer variabe to the answer that has been selected if(guiRadioButtonGetSelected(guiQuestionAnswer1RadioB)) then selectedAnswer = 1 elseif(guiRadioButtonGetSelected(guiQuestionAnswer2RadioB)) then selectedAnswer = 2 elseif(guiRadioButtonGetSelected(guiQuestionAnswer3RadioB)) then selectedAnswer = 3 else selectedAnswer = 0 end -- don't let the player continue if they havn't selected an answer if(selectedAnswer ~= 0) then -- if the selection is the same as the correct answer, increase correct answers by 1 if(selectedAnswer == selection[number][5]) then correctAnswers = correctAnswers + 1 end -- hide the current window, then create a new window for the next question guiSetVisible(guiQuestionWindowB, false) createBikeLicenseQuestionWindow(number+1) end end end, false) else guiQuestionSumbitButtonB = guiCreateButton ( 0.4 , 0.75 , 0.3, 0.1 , "Cevaplarฤฑ Gรถnder" , true ,guiQuestionWindowB) -- handler for when the player clicks submit addEventHandler ( "onClientGUIClick", guiQuestionSumbitButtonB, function(button, state) if(button == "left" and state == "up") then local selectedAnswer = 0 -- check all the radio buttons and seleted the selectedAnswer variabe to the answer that has been selected if(guiRadioButtonGetSelected(guiQuestionAnswer1RadioB)) then selectedAnswer = 1 elseif(guiRadioButtonGetSelected(guiQuestionAnswer2RadioB)) then selectedAnswer = 2 elseif(guiRadioButtonGetSelected(guiQuestionAnswer3RadioB)) then selectedAnswer = 3 elseif(guiRadioButtonGetSelected(guiQuestionAnswer4RadioB)) then selectedAnswer = 4 else selectedAnswer = 0 end -- don't let the player continue if they havn't selected an answer if(selectedAnswer ~= 0) then -- if the selection is the same as the correct answer, increase correct answers by 1 if(selectedAnswer == selection[number][5]) then correctAnswers = correctAnswers + 1 end -- hide the current window, then create the finish window guiSetVisible(guiQuestionWindowB, false) createBikeTestFinishWindow() end end end, false) end end -- funciton create the window that tells the function createBikeTestFinishWindow() local score = math.floor((correctAnswers/NoQuestionToAnswer)*100) local screenwidth, screenheight = guiGetScreenSize () local Width = 450 local Height = 200 local X = (screenwidth - Width)/2 local Y = (screenheight - Height)/2 -- create the window guiFinishWindowB = guiCreateWindow ( X , Y , Width , Height , "Sฤฑnav Sonu.", false ) if(score >= passPercent) then guiCreateStaticImage (0.35, 0.1, 0.3, 0.2, "pass.png", true, guiFinishWindowB) guiFinalPassLabelB = guiCreateLabel(0, 0.3, 1, 0.1, "Tebrikler! Sฤฑnavฤฑn bu kฤฑsmฤฑnฤฑ baลŸarฤฑyla geรงtiniz.", true, guiFinishWindowB) guiSetFont ( guiFinalPassLabelB,"default-bold-small") guiLabelSetHorizontalAlign ( guiFinalPassLabelB, "center") guiLabelSetColor ( guiFinalPassLabelB ,0, 255, 0 ) guiFinalPassTextLabelB = guiCreateLabel(0, 0.4, 1, 0.4, "Sฤฑnavdan %"..score.." aldฤฑnฤฑz, sฤฑnavฤฑ geรงmek iรงin gereken %"..passPercent..". Tebrikler!" ,true, guiFinishWindowB) guiLabelSetHorizontalAlign ( guiFinalPassTextLabelB, "center", true) guiFinalRegisterButtonB = guiCreateButton ( 0.35 , 0.8 , 0.3, 0.1 , "Devam Et" , true ,guiFinishWindowB) -- if the player has passed the quiz and clicks on register addEventHandler ( "onClientGUIClick", guiFinalRegisterButtonB, function(button, state) if(button == "left" and state == "up") then -- set player date to say they have passed the theory. initiateBikeTest() -- reset their correct answers correctAnswers = 0 toggleAllControls ( true ) triggerEvent("onClientPlayerWeaponCheck", source) --cleanup destroyElement(guiIntroLabel1B) destroyElement(guiIntroProceedButtonB) destroyElement(guiIntroWindowB) destroyElement(guiQuestionLabelB) destroyElement(guiQuestionAnswer1RadioB) destroyElement(guiQuestionAnswer2RadioB) destroyElement(guiQuestionAnswer3RadioB) destroyElement(guiQuestionWindowB) destroyElement(guiFinalPassTextLabelB) destroyElement(guiFinalRegisterButtonB) destroyElement(guiFinishWindowB) guiIntroLabel1B = nil guiIntroProceedButtonB = nil guiIntroWindowB = nil guiQuestionLabelB = nil guiQuestionAnswer1RadioB = nil guiQuestionAnswer2RadioB = nil guiQuestionAnswer3RadioB = nil guiQuestionWindowB = nil guiFinalPassTextLabelB = nil guiFinalRegisterButtonB = nil guiFinishWindowB = nil correctAnswers = 0 selection = {} showCursor(false) end end, false) else -- player has failed, guiCreateStaticImage (0.35, 0.1, 0.3, 0.2, "fail.png", true, guiFinishWindowB) guiFinalFailLabelB = guiCreateLabel(0, 0.3, 1, 0.1, "รœzgรผnรผz, sฤฑnavฤฑ geรงemediniz.", true, guiFinishWindowB) guiSetFont ( guiFinalFailLabelB,"default-bold-small") guiLabelSetHorizontalAlign ( guiFinalFailLabelB, "center") guiLabelSetColor ( guiFinalFailLabelB ,255, 0, 0 ) guiFinalFailTextLabelB = guiCreateLabel(0, 0.4, 1, 0.4, "Sฤฑnavdan %"..math.ceil(score).." aldฤฑnฤฑz, sฤฑnav geรงme puanฤฑ %"..passPercent.."." ,true, guiFinishWindowB) guiLabelSetHorizontalAlign ( guiFinalFailTextLabelB, "center", true) guiFinalCloseButtonB = guiCreateButton ( 0.2 , 0.8 , 0.25, 0.1 , "Kapat" , true ,guiFinishWindowB) -- if player click the close button addEventHandler ( "onClientGUIClick", guiFinalCloseButtonB, function(button, state) if(button == "left" and state == "up") then destroyElement(guiIntroLabel1B) destroyElement(guiIntroProceedButtonB) destroyElement(guiIntroWindowB) destroyElement(guiQuestionLabelB) destroyElement(guiQuestionAnswer1RadioB) destroyElement(guiQuestionAnswer2RadioB) destroyElement(guiQuestionAnswer3RadioB) destroyElement(guiQuestionWindowB) destroyElement(guiFinalPassTextLabelB) destroyElement(guiFinalRegisterButtonB) destroyElement(guiFinishWindowB) guiIntroLabel1B = nil guiIntroProceedButtonB = nil guiIntroWindowB = nil guiQuestionLabelB = nil guiQuestionAnswer1RadioB = nil guiQuestionAnswer2RadioB = nil guiQuestionAnswer3RadioB = nil guiQuestionWindowB = nil guiFinalPassTextLabelB = nil guiFinalRegisterButtonB = nil guiFinishWindowB = nil selection = {} correctAnswers = 0 showCursor(false) end end, false) end end -- function starts the quiz function startLicenceBikeTest() -- choose a random set of questions chooseBikeTestQuestions() -- create the question window with question number 1 createBikeLicenseQuestionWindow(1) end -- functions chooses the questions to be used for the quiz function chooseBikeTestQuestions() -- loop through selections and make each one a random question for i=1, 10 do -- pick a random number between 1 and the max number of questions local number = math.random(1, NoQuestions) -- check to see if the question has already been selected if(testBikeQuestionAlreadyUsed(number)) then repeat -- if it has, keep changing the number until it hasn't number = math.random(1, NoQuestions) until (testBikeQuestionAlreadyUsed(number) == false) end -- set the question to the random one selection[i] = questionsBike[number] end end -- function returns true if the queston is already used function testBikeQuestionAlreadyUsed(number) local same = 0 -- loop through all the current selected questions for i, j in pairs(selection) do -- if a selected question is the same as the new question if(j[1] == questionsBike[number][1]) then same = 1 -- set same to 1 end end -- if same is 1, question already selected to return true if(same == 1) then return true else return false end end --------------------------------------- ------ Practical Driving Test --------- --------------------------------------- testBikeRoute = { { 1092.20703125, -1759.1591796875, 13.023070335388 }, -- Start, DoL Parking { 1167.5771484375, -1743.3544921875, 13.066892623901 }, -- DoL exit, turning right { 1173.171875, -1843.9365234375, 13.07141494751 }, -- Headed towards Governors office { 1319.13671875, -1854.3408203125, 13.052598953247 }, -- Riding towards Idlewood { 1382.615234375, -1873.7451171875, 13.052177429199 }, -- ^^ { 1559.7392578125, -1875.140625, 13.050706863403 }, -- Turning towards PD { 1571.5244140625, -1859.8037109375, 13.050792694092 }, -- ^^ { 1571.8427734375, -1740.0810546875, 13.050458908081 }, -- Stop at PD, turn right { 1680.7255859375, -1734.396484375, 13.055520057678 }, -- Stop at SAN, turn left { 1691.6259765625, -1715.3349609375, 13.050860404968 }, -- ^^ { 1691.5712890625, -1599.6298828125, 13.054371833801 }, -- End of SAN, behind PD turn left { 1669.734375, -1590.0703125, 13.051850318909 }, -- Heading past PD { 1518.28515625, -1590.2666015625, 13.052554130554 }, -- Next to PD { 1426.9873046875, -1590.0029296875, 13.058673858643 }, -- At intersection on commerce { 1319.5224609375, -1569.0380859375, 13.042145729065 }, -- Stop @ St. Lawrence, turn right { 1359.40234375, -1416.8935546875, 13.050371170044 }, -- Turn left towards ASH @ speed cam { 1331.08984375, -1395.2607421875, 13.012241363525 }, -- ^^ { 1136.51171875, -1393.3408203125, 13.176746368408 }, -- Next to ASH { 1012.11328125, -1393.45703125, 12.736813545227 }, -- Heading down the road { 837.7568359375, -1392.7607421875, 13.025742530823 }, -- ^^ { 804.1962890625, -1392.9248046875, 13.181559562683 }, -- Turn right at Vinyl Countdown { 800.14453125, -1370.953125, 13.049411773682 }, -- ^^ { 799.982421875, -1285.041015625, 13.049916267395 }, -- Heading towards Dillimore { 799.6279296875, -1161.751953125, 23.290950775146 }, -- ^^ { 797.2490234375, -1061.5009765625, 24.365398406982 }, -- Turn left @ Dillimore road { 755.2783203125, -1054.138671875, 23.414789199829 }, -- ^^ { 707.0498046875, -1114.193359375, 17.771127700806 }, -- Going towards Bank { 657.474609375, -1190.5693359375, 17.324506759644 }, -- ^^ { 629.720703125, -1208.3291015625, 17.772462844849 }, -- Turn left at bank { 622.671875, -1230.0146484375, 17.729223251343 }, -- ^^ { 627.8359375, -1308.2685546875, 13.577067375183 }, -- Going towards Beach { 630.0869140625, -1425.345703125, 13.397357940674 }, -- ^^ { 630.3798828125, -1572.8544921875, 15.133798599243 }, -- ^^ { 632.1416015625, -1660.2255859375, 15.142672538757 }, -- Turn left into road { 654.5322265625, -1674.0439453125, 14.000010490417 }, -- ^^ { 803.4462890625, -1677.0830078125, 13.050843238831 }, -- End of road, turn left { 812.54296875, -1662.7041015625, 13.043465614319 }, -- ^^ { 832.4482421875, -1623.37109375, 13.052579879761 }, -- Heading back towards DoL { 895.9052734375, -1574.603515625, 13.050440788269 }, -- ^^ { 1028.7724609375, -1574.8671875, 13.051753044128 }, -- turn right towards DoL { 1034.87890625, -1589.0283203125, 13.051016807556 }, -- ^^ { 1035.052734375, -1699.5732421875, 13.050029754639 }, -- Turn left towards DoL { 1049.9208984375, -1714.2490234375, 13.053936004639 }, -- ^^ { 1165.490234375, -1714.7138671875, 13.40420627594 }, -- Turn right into DoL { 1172.11328125, -1734.9443359375, 13.159434318542 }, -- ^^ { 1085.056640625, -1740.5791015625, 13.152918815613 }, -- DoL End road } testBike = { [468]=true } -- Mananas need to be spawned at the start point. local blip = nil local marker = nil function initiateBikeTest() triggerServerEvent("theoryBikeComplete", getLocalPlayer()) local x, y, z = testBikeRoute[1][1], testBikeRoute[1][2], testBikeRoute[1][3] blip = createBlip(x, y, z, 0, 2, 0, 255, 0, 255) marker = createMarker(x, y, z, "checkpoint", 4, 0, 255, 0, 150) -- start marker. addEventHandler("onClientMarkerHit", marker, startBikeTest) outputChatBox("#FF9933You are now ready to take your practical driving examination. Collect a DoL test bike and begin the route.", 255, 194, 14, true) end function startBikeTest(element) if element == getLocalPlayer() then local vehicle = getPedOccupiedVehicle(getLocalPlayer()) local id = getElementModel(vehicle) if not (testBike[id]) then outputChatBox("#FF9933You must be riding a DoL test bike when passing through the checkpoints.", 255, 0, 0, true ) -- Wrong type. else destroyElement(blip) destroyElement(marker) local vehicle = getPedOccupiedVehicle ( getLocalPlayer() ) setElementData(getLocalPlayer(), "drivingTest.marker", 2, false) local x1,y1,z1 = nil -- Setup the first checkpoint x1 = testBikeRoute[2][1] y1 = testBikeRoute[2][2] z1 = testBikeRoute[2][3] setElementData(getLocalPlayer(), "drivingTest.checkmarkers", #testBikeRoute, false) blip = createBlip(x1, y1 , z1, 0, 2, 255, 0, 255, 255) marker = createMarker( x1, y1,z1 , "checkpoint", 4, 255, 0, 255, 150) addEventHandler("onClientMarkerHit", marker, UpdateBikeCheckpoints) outputChatBox("#FF9933You will need to complete the route without damaging the test bike. Good luck and drive safe.", 255, 194, 14, true) end end end function UpdateBikeCheckpoints(element) if (element == localPlayer) then local vehicle = getPedOccupiedVehicle(getLocalPlayer()) local id = getElementModel(vehicle) if not (testBike[id]) then outputChatBox("You must be on a DoL test bike when passing through the check points.", 255, 0, 0) -- Wrong car type. else destroyElement(blip) destroyElement(marker) blip = nil marker = nil local m_number = getElementData(getLocalPlayer(), "drivingTest.marker") local max_number = getElementData(getLocalPlayer(), "drivingTest.checkmarkers") if (tonumber(max_number-1) == tonumber(m_number)) then -- if the next checkpoint is the final checkpoint. outputChatBox("#FF9933Park your bike at the #FF66CCin the parking lot #FF9933to complete the test.", 255, 194, 14, true) local newnumber = m_number+1 setElementData(getLocalPlayer(), "drivingTest.marker", newnumber, false) local x2, y2, z2 = nil x2 = testBikeRoute[newnumber][1] y2 = testBikeRoute[newnumber][2] z2 = testBikeRoute[newnumber][3] marker = createMarker( x2, y2, z2, "checkpoint", 4, 255, 0, 255, 150) blip = createBlip( x2, y2, z2, 0, 2, 255, 0, 255, 255) addEventHandler("onClientMarkerHit", marker, EndBikeTest) else local newnumber = m_number+1 setElementData(getLocalPlayer(), "drivingTest.marker", newnumber, false) local x2, y2, z2 = nil x2 = testBikeRoute[newnumber][1] y2 = testBikeRoute[newnumber][2] z2 = testBikeRoute[newnumber][3] marker = createMarker( x2, y2, z2, "checkpoint", 4, 255, 0, 255, 150) blip = createBlip( x2, y2, z2, 0, 2, 255, 0, 255, 255) addEventHandler("onClientMarkerHit", marker, UpdateBikeCheckpoints) end end end end function EndBikeTest(element) if (element == localPlayer) then local vehicle = getPedOccupiedVehicle(getLocalPlayer()) local id = getElementModel(vehicle) if not (testBike[id]) then outputChatBox("You must be on a DoL test bike when passing through the check points.", 255, 0, 0) else local vehicleHealth = getElementHealth ( vehicle ) if (vehicleHealth >= 800) then ---------- -- PASS -- ---------- outputChatBox("After inspecting the vehicle we can see no damage.", 255, 194, 14) triggerServerEvent("acceptBikeLicense", getLocalPlayer()) else ---------- -- Fail -- ---------- outputChatBox("After inspecting the vehicle we can see that it's damage.", 255, 194, 14) outputChatBox("You have failed the practical driving test.", 255, 0, 0) end destroyElement(blip) destroyElement(marker) blip = nil marker = nil end end end
local function contains(table, val) for i = 1, #table do if table[i] == val then return true end end return false end math.randomseed(os.time()) local sequences = {} -- The first sequence can only be a combo number between 1 and 3 sequences[1] = math.random(1, 3) -- The second sequence can only be a combo number between 1 and 59 -- but the number will start at 4 in order to not repeat from the sequence 1 sequences[2] = math.random(4, 59) -- The third sequence can be any combo number between 1 and 64 -- but the number will start at 4 in order to not repeat from the sequence 1 for index = 3, 10 do local comboNumber = nil while (nil == comboNumber) do local randomNumber = math.random(4, 64) if (not contains(sequences, randomNumber)) then comboNumber = randomNumber end end sequences[index] = comboNumber end print('Sequences : ' .. table.concat(sequences, ' ; ')) -- Here is the sequences of the solos (2 common + 1 secret) math.randomseed(os.time()) sequences = {} for index = 1, 10 do sequences[index] = math.random(1, 3) end print('Solos : ' .. table.concat(sequences, ' ; '))
object = {"Kocka", "Kvadar"} title = {" strana." , " ivica.", " temena.", " sve ivice jednake.", " sve strane podudarne.", " naspramne strane podudarne."} tvrdjenje_str = "Tvrฤ‘enje" n_str = "n" t_str = "t" ima_str = " ima "
--[[ = ABOUT This module uses Roberto Ierusalimschy's powerful new pattern matching library LPeg[1] to tokenize Lua source-code in to a table of tokens. I think it handles all of Lua's syntax, but if you find anything missing I would appreciate a xolox aatt home ddoott nl. This lexer is based on the BNF[2] from the Lua manual. = USAGE I've saved my copy of this module under [$LUA_PATH/lexers/lua.lua] which means I can use it like in the following interactive prompt: Lua 5.1.1 Copyright (C) 1994-2006 Lua.org, PUC-Rio > require 'lexers.lua' > tokens = lexers.lua [=[ >> 42 or 0 >> -- some Lua source-code in a string]=] > = tokens table: 00422E40 > lexers.lua.print(tokens) line 1, number: `42` line 1, whitespace: ` ` line 1, keyword: `or` line 1, whitespace: ` ` line 1, number: `0` line 1, whitespace: ` ` line 2, comment: `-- some Lua source-code in a string` total of 7 tokens, 2 lines The returned table [tokens] looks like this: { -- type , text, line { 'number' , '42', 1 }, { 'whitespace', ' ' , 1 }, { 'keyword' , 'or', 1 }, { 'whitespace', ' ' , 1 }, { 'number' , '0' , 1 }, { 'whitespace', '\n', 1 }, { 'comment' , '-- some Lua source-code in a string', 2 }, } = CREDITS Written by Peter Odding, 2007/04/04 = THANKS TO - the Lua authors for a wonderful language; - Roberto for LPeg; - caffeine for keeping me awake :) = LICENSE Shamelessly ripped from the SQLite[3] project: The author disclaims copyright to this source code. In place of a legal notice, here is a blessing: May you do good and not evil. May you find forgiveness for yourself and forgive others. May you share freely, never taking more than you give. [1] http://www.inf.puc-rio.br/~roberto/lpeg.html [2] http://lua.org/manual/5.1/manual.html#8 [3] http://sqlite.org --]] -- since this module is intended to be loaded with require() we receive the -- name used to load us in ... and pass it on to module() module(..., package.seeall) -- written for LPeg .5, by the way local lpeg = require 'lpeg' local P, R, S, C, Cc, Ct = lpeg.P, lpeg.R, lpeg.S, lpeg.C, lpeg.Cc, lpeg.Ct -- create a pattern which captures the lua value [id] and the input matching -- [patt] in a table local function token(id, patt) return Ct(Cc(id) * C(patt)) end local digit = R('09') -- range of valid characters after first character of identifier local idsafe = R('AZ', 'az', '\127\255') + P '_' -- operators local operator = token('operator', P '==' + P '~=' + P '<=' + P '>=' + P '...' + P '..' + S '+-*/%^#=<>;:,.{}[]()') -- identifiers local ident = token('identifier', idsafe * (idsafe + digit + P '.') ^ 0) -- keywords local olua_keywords = P '@implementation' + P '@statics' + P '@end' + P '@try' + P '@catch' + P '@finally' + P '@throw' local keyword = token('keyword', (P 'and' + P 'break' + P 'do' + P 'elseif' + P 'else' + P 'end' + P 'false' + P 'for' + P 'function' + P 'if' + P 'in' + P 'local' + P 'nil' + P 'not' + P 'or' + P 'repeat' + P 'return' + P 'then' + P 'true' + P 'until' + P 'while' + olua_keywords ) * -(idsafe + digit)) -- numbers local number_sign = S'+-'^-1 local number_decimal = digit ^ 1 local number_hexadecimal = P '0' * S 'xX' * R('09', 'AF', 'af') ^ 1 local number_float = (digit^1 * P'.' * digit^0 + P'.' * digit^1) * (S'eE' * number_sign * digit^1)^-1 local number = token('number', number_hexadecimal + number_float + number_decimal) -- callback for [=[ long strings ]=] -- ps. LPeg is for Lua what regex is for Perl, which makes me smile :) local longstringpredicate = P(function(input, index) local level = input:match('^%[(=*)%[', index) if level then local _, stop = input:find(']' .. level .. ']', index, true) if stop then return stop + 1 end end end) local longstring = #(P'[' * P'='^1 * P'[') * longstringpredicate -- strings local singlequoted_string = P "'" * ((1 - S "'\r\n\f\\") + (P '\\' * 1)) ^ 0 * "'" local doublequoted_string = P '"' * ((1 - S '"\r\n\f\\') + (P '\\' * 1)) ^ 0 * '"' local string = token('string', singlequoted_string + doublequoted_string + longstring) -- comments local singleline_comment = P '--' * (1 - S '\r\n\f') ^ 0 local multiline_comment = P '--' * (#(P'[' * P'='^0 * P'[') * longstringpredicate) local comment = token('comment', multiline_comment + singleline_comment) -- whitespace local whitespace = token('whitespace', S('\r\n\f\t ')^1) -- ordered choice of all tokens and last-resort error which consumes one character local any_token = whitespace + number + keyword + ident + string + comment + operator + token('error', 1) -- private interface local table_of_tokens = Ct(any_token ^ 0) -- increment [line] by the number of line-ends in [text] local function sync(line, text) local index, limit = 1, #text while index <= limit do local start, stop = text:find('\r\n', index, true) if not start then start, stop = text:find('[\r\n\f]', index) if not start then break end end index = stop + 1 line = line + 1 end return line end -- we only need to synchronize the line-counter for these token types local multiline_tokens = { comment = true, string = true, whitespace = true } -- public interface function getrawtokens(self, input) assert(type(input) == 'string', 'bad argument #1 (expected string)') local line = 1 local tokens = lpeg.match(table_of_tokens, input) for i, token in pairs(tokens) do token[3] = line if multiline_tokens[token[1]] then line = sync(line, token[2]) end end return tokens end function gettokens(self, input) local rawtokens = getrawtokens(self, input) local tokens = {} local lastrawtoken = nil local function pushtoken(rawtoken) if lastrawtoken and (lastrawtoken[1] ~= 'whitespace') and (lastrawtoken[1] ~= 'comment') then local t = { type = lastrawtoken[1], text = lastrawtoken[2], line = lastrawtoken[3], nlafter = false } if rawtoken and rawtoken[2]:find('\n') then t.nlafter = true end tokens[#tokens+1] = t end lastrawtoken = rawtoken end for _, rawtoken in ipairs(rawtokens) do pushtoken(rawtoken) end pushtoken(nil) return tokens end function printraw(tokens) local print, format = _G.print, _G.string.format for _, token in pairs(tokens) do print(format('line %i, %s: `%s`', token[3], token[1], token[2])) end print(format('total of %i tokens, %i lines', #tokens, tokens[#tokens][3])) end function print(tokens) local print, format = _G.print, _G.string.format for _, token in pairs(tokens) do local nlafter = 'false' if token.nlafter then nlafter = 'true' end print(token.line, token.nlafter, token.type, token.text) --print(format('line %i, nlafter=%s %s: `%s`', token.line, nlafter, token.type, token.text)) end print(format('total of %i tokens, %i lines', #tokens, tokens[#tokens].line)) end getmetatable(getfenv(1)).__call = gettokens
local t = {} t.init = {x = 0, y = 0} t.layout = {} t.layout[1] = { {6}, {6}, {5} } t.moves = {1, 3} t.message = { en = "You can pass throught more than one block with only one movement", es = "Puedes pasar a travรฉs de mรกs de un bloque en un solo movimiento", } return t
level = { id = 248972157, --- LEVEL_1 name = "Level 1", players = 2, entities = { { prototypeId = 2979648629, entityId = 9000 }, { prototypeId = 2252448813, entityId = 9001 }, { prototypeId = 1316782920, entityId = 9002 }, { prototypeId = 315271780, entityId = 10000, position = engine.math.vec3.new(0), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10001, position = engine.math.vec3.new(10, 0, 0), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10002, position = engine.math.vec3.new(10, 0, 10), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10003, position = engine.math.vec3.new(0, 0, 10), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10004, position = engine.math.vec3.new(-10, 0, 0), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10005, position = engine.math.vec3.new(-10, 0, -10), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10006, position = engine.math.vec3.new(0, 0, -10), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10007, position = engine.math.vec3.new(10, 0, -10), rotation = engine.math.vec3.new(0) }, { prototypeId = 315271780, entityId = 10008, position = engine.math.vec3.new(-10, 0, 10), rotation = engine.math.vec3.new(0) }, -- { -- prototypeId = 1675181212, -- entityId = 10200, -- position = engine.math.vec3.new(0, 0, 10), -- rotation = engine.math.vec3.new(0) -- }, { prototypeId = 592045845, -- ENTITY_PORTAL entityId = 10100, position = engine.math.vec3.new(0, 0, -50), rotation = engine.math.vec3.new(0) }, { prototypeId = 592045845, -- ENTITY_PORTAL entityId = 10101, position = engine.math.vec3.new(30, 0, -150), rotation = engine.math.vec3.new(0, 30, 0) }, { prototypeId = 592045845, -- ENTITY_PORTAL entityId = 10103, position = engine.math.vec3.new(100, 0, -250), rotation = engine.math.vec3.new(0, 90, 0) } }, update = function(self) if (self.hasPlayerWon) then return end if (engine.network.isClient()) then return end if self.levelStartDelay > 0 and engine.network.clientsCount() == 2 then self.levelStartDelay = self.levelStartDelay - 1; -- Start level after a bit of delay to let things sync if self.levelStartDelay == 0 then for i = 1, 2, 1 do -- Spawn player entity and assign it local player = engine.entity.spawnEntity("ENTITY_PLAYER") local clientId = engine.network.getClientIds()[i] player.controllingClient = clientId player.position = engine.math.vec3.new(-20 + ((i-1)*40), 4, 0); -- store player id in portals table so we can track self.portalsCompleted[player:id()] = {} -- Send event out so client know its can control it local assignEvent = engine.event.event.new("EVENT_TYPE_ASSIGN_PLAYER") assignEvent:setClientId("clientId", clientId) assignEvent:setEntityId("entityId", player:id()) assignEvent:push() end end end for k, v in pairs(self.portalsCompleted) do local count = 0 for k1, v1 in pairs(v) do count = count + 1 end -- check if all portals have been completed if (count == 3) then print("Entity " .. k .. " has completed all portals and wins!") self.hasPlayerWon = true local event = engine.event.event.new("EVENT_TYPE_PLAYER_WIN") event:setEntityId("entityId", k) event:push() end end end, events = { "EVENT_TYPE_LEVEL_LOAD", "EVENT_TYPE_PLAYER_CONNECTED", "EVENT_TYPE_PLAYER_DISCONNECTED" }, onEvent = function(self, event) if (event:type() == 1994444546) then -- EVENT_TYPE_PLAYER_CONNECTED print("Player connected! Client ID: " .. event:getUShort("clientId")) elseif event:type() == 415743068 then -- EVENT_TYPE_PLAYER_DISCONNECTED local clientId = event:getClientId("clientId") print("Client " .. clientId .. " disconnected") -- Ask engine to destroy and remove our reference -- engine.entity.destroy(self.players[clientId]:id()) -- self.players[clientId] = nil elseif event:type() == 1205121214 then -- EVENT_TYPE_LEVEL_LOAD if (event:getStringId("levelId") == self:id()) then print("Level loaded!") -- position camera so its not in a bad place if (engine.network.isClient()) then engine.graphics.camera.position = engine.math.vec3.new(0, 1000, 10); engine.graphics.camera.target = engine.math.vec3.new(0, 1000, 0) end -- setup some data structures self.portalsCompleted = {} self.portalHit = function(portalId, entityId) -- If haven't hit this portal already, store it if (self.portalsCompleted[entityId][portalId] == nil) then self.portalsCompleted[entityId][portalId] = true end end self.hasPlayerWon = false self.levelStartDelay = 60 end end return false; end }
--้‰„็ฃใฎๆŠ—ๆˆฆ -- --Script by JustFish function c101102070.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,101102070+EFFECT_COUNT_CODE_OATH) e1:SetTarget(c101102070.target) e1:SetOperation(c101102070.activate) c:RegisterEffect(e1) end function c101102070.spfilter(c,e,tp) return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup()) end function c101102070.fselect(g,tp) return Duel.IsExistingMatchingCard(c101102070.lkfilter,tp,LOCATION_EXTRA,0,1,nil,g) end function c101102070.lkfilter(c,g) return c:IsSetCard(0x24f) and c:IsLinkSummonable(g,nil,g:GetCount(),g:GetCount()) end function c101102070.chkfilter(c,tp) return c:IsType(TYPE_LINK) and c:IsSetCard(0x24f) and Duel.GetLocationCountFromEx(tp,tp,nil,c)>0 end function c101102070.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then if not Duel.IsPlayerCanSpecialSummonCount(tp,2) then return false end local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return false end if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end local cg=Duel.GetMatchingGroup(c101102070.chkfilter,tp,LOCATION_EXTRA,0,nil,tp) if #cg==0 then return false end local _,maxlink=cg:GetMaxGroup(Card.GetLink) if maxlink>ft then maxlink=ft end local g=Duel.GetMatchingGroup(c101102070.spfilter,tp,LOCATION_GRAVE+LOCATION_REMOVED,0,nil,e,tp) return g:CheckSubGroup(c101102070.fselect,1,maxlink,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE+LOCATION_REMOVED) end function c101102070.activate(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft>1 and Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end local g=Duel.GetMatchingGroup(aux.NecroValleyFilter(c101102070.spfilter),tp,LOCATION_GRAVE+LOCATION_REMOVED,0,nil,e,tp) local cg=Duel.GetMatchingGroup(c101102070.chkfilter,tp,LOCATION_EXTRA,0,nil,tp) local _,maxlink=cg:GetMaxGroup(Card.GetLink) if ft>0 and maxlink then if maxlink>ft then maxlink=ft end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:SelectSubGroup(tp,c101102070.fselect,false,1,maxlink,tp) if not sg then return end local tc=sg:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+RESETS_STANDARD) tc:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_DISABLE_EFFECT) tc:RegisterEffect(e2) tc=sg:GetNext() end Duel.SpecialSummonComplete() local og=Duel.GetOperatedGroup() local tg=Duel.GetMatchingGroup(c101102070.lkfilter,tp,LOCATION_EXTRA,0,nil,og) if og:GetCount()==sg:GetCount() and tg:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local rg=tg:Select(tp,1,1,nil) Duel.LinkSummon(tp,rg:GetFirst(),og,nil,#og,#og) end end end
local core = require "sys.core" local mysql = require "sys.db.mysql" local testaux = require "testaux" return function() local db = mysql.create { host="127.0.0.1:3306", user="root", password="root", } db:connect() local status, res = db:query("show databases;") print("mysql show databases;", status) testaux.asserteq(res[1].Database, "information_schema", "mysql query showdatabases;") end
๏ปฟlocal mod = DBM:NewMod(655, "DBM-Party-MoP", 4, 303) local L = mod:GetLocalizedStrings() local sndWOP = mod:SoundMM("SoundWOP") mod:SetRevision(("$Revision: 9469 $"):sub(12, -3)) mod:SetCreatureID(56906) mod:SetZone() mod:SetUsedIcons(8) mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_AURA_APPLIED", "SPELL_AURA_REMOVED" ) local warnSabotage = mod:NewTargetAnnounce(107268, 4) --local warnThrowExplosive = mod:NewSpellAnnounce(102569, 3)--Doesn't show in chat/combat log, need transcriptor log --local warnWorldinFlame = mod:NewSpellAnnounce(101591, 4)--^, triggered at 66% and 33% boss health. local specWarnSabotage = mod:NewSpecialWarningYou(107268) local specWarnSabotageNear = mod:NewSpecialWarningClose(107268) local timerSabotage = mod:NewTargetTimer(5, 107268) local timerSabotageCD = mod:NewNextTimer(12, 107268) --local timerThrowExplosiveCD = mod:NewNextTimer(22, 102569) mod:AddBoolOption("IconOnSabotage", true) function mod:OnCombatStart(delay) -- timerSabotageCD:Start(-delay)--Unknown, tank pulled before log got started, will need a fresh log. end function mod:SPELL_AURA_APPLIED(args) if args.spellId == 107268 then warnSabotage:Show(args.destName) timerSabotage:Start(args.destName) sndWOP:Schedule(1.5, "countfour") sndWOP:Schedule(2.5, "countthree") sndWOP:Schedule(3.5, "counttwo") sndWOP:Schedule(4.5, "countone") timerSabotageCD:Start() if self.Options.IconOnSabotage then self:SetIcon(args.destName, 8) end if args:IsPlayer() then specWarnSabotage:Show() sndWOP:Play("runout")--่ท‘้–‹ไบบ็พค else sndWOP:Play("bombsoon")--ๆบ–ๅ‚™็‚ธๅฝˆ local uId = DBM:GetRaidUnitId(args.destName) if uId then local inRange = DBM.RangeCheck:GetDistance("player", uId) if inRange and inRange < 10 then specWarnSabotageNear:Show(args.destName) end end end end end function mod:SPELL_AURA_REMOVED(args) if args.spellId == 107268 then timerSabotage:Cancel(args.destName) if self.Options.IconOnSabotage then self:SetIcon(args.destName, 0) end end end
-- Copyright (c) 2018 Redfern, Trevor <[email protected]> -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local tiny = require "ext.tiny-ecs" local settings = require "settings" local RenderSprites = tiny.processingSystem() RenderSprites.filter = tiny.requireAll("position", "sprite") RenderSprites.is_draw_system = true function RenderSprites:process(entity) entity.sprite:draw(entity.position.x * settings.tile_width, entity.position.y * settings.tile_height) end return RenderSprites
-- The MIT License (MIT) -- -- Copyright (c) 2015 Matthew J. Runyan -- -- 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. local CoYield = require "CoYield" --------------------------------------------------------------------- ---------------------- Sandbox Environment Gen ---------------------- ----- Environment variables that have been commented out are ----- ----- not safe but a few of them could potentially be made safe ----- --------------------------------------------------------------------- local envGen = function() return { assert=assert, --[[ dofile=dofile,]] error=error, ipairs=ipairs, next=next, pairs=pairs, pcall=pcall, print=print, rawequal=rawequal, select=select, tonumber=tonumber, tostring=tostring, type=type, unpack=unpack, _VERSION=_VERSION, xpcall=xpcall, coroutine = { create=coroutine.create, resume=coroutine.resume, running=coroutine.running, status=coroutine.status, wrap=coroutine.wrap, -- yield=coroutine.yield, -- make sure that no c boundaries are surpassed or lua will terminate with an error }, --[[module=module,]] --[[require=module,]] --[[package.*]] string = { byte=string.byte, char=string.char, --[[dump=string.dump,]] -- TODO: Determine if these are safe and/or write lua implementations -- find=string.find, -- warning: a number of functions like this can still lock up the CPU [6] -- format=string.format, --[[gmatch=string.gmatch,]] --[[gsub=string.gsub,]] --[[match=string.match,]] --[[sub=string.sub,]] len=string.len, lower=string.lower, rep=string.rep, reverse=string.reverse, upper=string.upper, }, table = { insert=table.insert, maxn=table.maxn, remove=table.remove, sort=table.sort, }, math = { abs=math.abs, acos=math.acos, asin=math.asin, atan=math.atan, atan2=math.atan2, ceil=math.ceil, cos=math.cos, cosh=math.cosh, deg=math.deg, exp=math.exp, floor=math.floor, fmod=math.fmod, frexp=math.frexp, huge=math.huge, ldexp=math.ldexp, log=math.log, log10=math.log10, max=math.max, min=math.min, modf=math.modf, pi=math.pi, pow=math.pow, rad=math.rad, random=math.random, --[[randomseed=math.randomseed,]] sin=math.sin, sinh=math.sinh, sqrt=math.sqrt, tan=math.tan, tanh=math.tanh, }, --[[io.*]] os = { clock=os.clock, difftime=os.difftime, time=os.time, } } end --------------------------------------------------------------------- --------------------------------------------------------------------- local IronBox = {} -- this table is not safe to be exposed to a sandbox local IronBoxes = setmetatable({}, { __mode = "kv" }) local function table_combine(t1, t2) for i, v in pairs(t2) do t1[i] = v end end local function default_errorfunc(msg, box) if box then print("Error in IronBox [" .. tostring(box.id) .. "]: " .. msg) else print("Error could not create new box: " .. msg) end end local IronBox__meta = { __call = function(box, ...) return box:resume(...) end, __index = { -- runs the box until the C code stops it resume = function(box, ...) box.timesRun = box.timesRun + 1 -- also pass box for error handler return CoYield.resume(box.co, box, ...) end, -- will loop until the box finishes even if that is forever wait = function(box, ...) while true do local t = { box:resume(...) } if t[1] then break end end return select(2, unpack(t)) -- return all return vals and omit the status boolean end, -- resets the state of the coroutine. (program counter is reset but environment remains the same) reset = function(box, ...) box.timesRun = 0 box.co = coroutine.create(box.safeFunc) CoYield.makeCoYield(box.co, box.instructionsCount) end, }, } local function createIronBoxObject(co, env, errorFunc, safeFunc, instructionsCount) if co then local box = { co = co, env = env, id = #IronBoxes + 1, errorFunc = errorFunc, safeFunc = safeFunc, instructionsCount = instructionsCount, timesRun = 0, } table.insert(IronBoxes, box) return setmetatable(box, IronBox__meta) else return setmetatable({ }, IronBox__meta) -- return empty object: failed end end function IronBox.create(untrusted, env, errorfunc) -- type checks assert(type(untrusted) == "string" or type(untrusted) == "function") assert(errorfunc == nil or type(errorfunc) == "function") -- set error function errorfunc = errorfunc or default_errorfunc if jit then jit.off(errorfunc,true) end -- make sure everything is not jit compiled and will respond to yeild -- extract options and create environment local instructionsCount if env then if env._combineEnvWithDefault then table_combine(env, envGen()) end if type(env._count) == "number" then instructionsCount = env._count end else env = envGen() end -- get function from string if necessary if type(untrusted) == 'string' then local msg untrusted, msg = loadstring(untrusted) if untrusted == nil then errorfunc(msg) return nil -- failed to create a box end end -- set environment setfenv(untrusted,env) -- create safe wrapper function local safefunc = function(box, ...) local ok, result = pcall(untrusted, ...) if not ok then box.errorFunc(result, box) end return result end -- untrusted code cannot be jit compiled and guarantee that it will yeild if jit then jit.off(untrusted,true) end if jit then jit.off(safefunc,true) end -- create safe coroutine local co = coroutine.create(safefunc) CoYield.makeCoYield(co, instructionsCount) return createIronBoxObject(co, env, errorfunc, safefunc, instructionsCount) end return IronBox
local CMFogMgr = Inherit(CppObjectBase) function CMFogMgr:Ctor() self.m_MIDs = {} self.m_UpdateInterval = 0.3 self.m_PastTime = self.m_UpdateInterval end function CMFogMgr:LuaInit(Controller) self.m_Controller = Controller self.Controller = Controller self.MapSize = 127 self.LandscapeSize = 127 self.EyeLen = 10 self.ThroughColor = FColor.New(0,0,0,0) self:Init(FColor.New(0,0,0,180)) local actors = UGameplayStatics.GetAllActorsWithTag(Controller, "FogMeshActor", {}) for k, v in ipairs(actors) do local MeshActor = AStaticMeshActor.Cast(v) if MeshActor then MeshActor.StaticMeshComponent:SetMaterial(0, self:GetMaterial("/Game/Git/mt_fog.mt_fog")) end end self:Timer(self.UpdateForTexture, self):Time(0.001):Fire() end function CMFogMgr:GetMaterial(path) local MaterialFather = UMaterial.LoadObject(Controller, path) local MID = UKismetMaterialLibrary.CreateDynamicMaterialInstance(Controller, MaterialFather) MID:SetTextureParameterValue("tx_fog", self.Tx_Fog) MID:SetTextureParameterValue("tx_last_fog", self.Tx_Last_Fog) table.insert(self.m_MIDs, MID) return MID end function CMFogMgr:GetTx() return self.Tx_Fog, self.Tx_Last_Fog end function CMFogMgr:UpdateForTexture(delta) self.m_PastTime = self.m_PastTime + delta if self.m_PastTime >= self.m_UpdateInterval then self.m_PastTime = 0 -- self:UpdateFOV(self.m_Controller.m_Pawn:K2_GetActorLocation()) end for i, v in ipairs(self.m_MIDs) do v:SetScalarParameterValue("time", self.m_PastTime/self.m_UpdateInterval) end -- self.m_FogMgr:UpdateTexture() end function CMFogMgr:TestXY(pos, x, y) local targetPos = FVector.New(y, x, pos.Z) local Hit = FHitResult.New() if UKismetSystemLibrary.LineTraceSingle_NEW(self.m_Controller, pos, targetPos, ETraceTypeQuery.TraceTypeQuery1, true, {self.m_Controller.PlayCharacter}, EDrawDebugTrace.None, Hit, true) then return false else return true end end return CMFogMgr
--# Monster converted using Devm monster converter #-- local mType = Game.createMonsterType("Island Troll") local monster = {} monster.description = "an island troll" monster.experience = 20 monster.outfit = { lookType = 282, lookHead = 0, lookBody = 0, lookLegs = 0, lookFeet = 0, lookAddons = 0, lookMount = 0 } monster.raceId = 277 monster.Bestiary = { class = "Humanoid", race = BESTY_RACE_HUMANOID, toKill = 250, FirstUnlock = 10, SecondUnlock = 100, CharmsPoints = 5, Stars = 1, Occurrence = 0, Locations = "Goroma." } monster.health = 50 monster.maxHealth = 50 monster.race = "blood" monster.corpse = 865 monster.speed = 126 monster.manaCost = 290 monster.maxSummons = 0 monster.changeTarget = { interval = 5000, chance = 0 } monster.strategiesTarget = { nearest = 100, } monster.flags = { summonable = true, attackable = true, hostile = true, convinceable = true, pushable = true, rewardBoss = false, illusionable = true, canPushItems = false, canPushCreatures = false, staticAttackChance = 90, targetDistance = 1, runHealth = 15, healthHidden = false, isBlockable = false, canWalkOnEnergy = false, canWalkOnFire = false, canWalkOnPoison = false, pet = false } monster.light = { level = 0, color = 0 } monster.voices = { interval = 5000, chance = 10, {text = "Hmmm, turtles", yell = false}, {text = "Hmmm, dogs", yell = false}, {text = "Hmmm, worms", yell = false}, {text = "Groar", yell = false}, {text = "Gruntz!", yell = false} } monster.loot = { {id = 3003, chance = 8000}, -- rope {id = 3031, chance = 60000, maxCount = 10}, -- gold coin {id = 3054, chance = 70}, -- silver amulet {id = 3268, chance = 18000}, -- hand axe {id = 3277, chance = 20000}, -- spear {id = 3336, chance = 5000}, -- studded club {id = 3355, chance = 10000}, -- leather helmet {id = 3412, chance = 16000}, -- wooden shield {id = 3552, chance = 10500}, -- leather boots {id = 5096, chance = 5000}, -- mango {id = 5901, chance = 30000}, -- wood {id = 901, chance = 40} -- marlin } monster.attacks = { {name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -10} } monster.defenses = { defense = 10, armor = 10 } monster.elements = { {type = COMBAT_PHYSICALDAMAGE, percent = 0}, {type = COMBAT_ENERGYDAMAGE, percent = 0}, {type = COMBAT_EARTHDAMAGE, percent = 0}, {type = COMBAT_FIREDAMAGE, percent = 0}, {type = COMBAT_LIFEDRAIN, percent = 0}, {type = COMBAT_MANADRAIN, percent = 0}, {type = COMBAT_DROWNDAMAGE, percent = 0}, {type = COMBAT_ICEDAMAGE, percent = 0}, {type = COMBAT_HOLYDAMAGE , percent = 0}, {type = COMBAT_DEATHDAMAGE , percent = 0} } monster.immunities = { {type = "paralyze", condition = false}, {type = "outfit", condition = false}, {type = "invisible", condition = false}, {type = "bleed", condition = false} } mType:register(monster)
sources = tup.glob("../src/*.cpp") objects = table.map(sources, function(name) return '../src/' .. tup.base(name) .. OBJSUFFIX end) library('performance_log', objects)
-- -- Created by IntelliJ IDEA. -- User: nander -- Date: 21/04/2018 -- Time: 14:09 -- To change this template use File | Settings | File Templates. -- local addBuilding = {} -- previously: Gamestate.new() addBuilding.name = "addBuilding" function addBuilding:enter(prev, state, building, card) addBuilding.prev = prev addBuilding.building = building addBuilding.state = state addBuilding.card = card -- setup entities here end function addBuilding:draw() addBuilding.prev.prev:draw(true) love.graphics.push() love.graphics.scale(GLOBSCALE()) scripts.rendering.renderUI.drawMessage("Place building .. " .. scripts.gameobjects.buildings[addBuilding.building].name) love.graphics.pop() end function addBuilding:mousepressed(x, y, click) local prev = addBuilding.prev if prev then while prev.prev and not prev.mousepressed do prev = prev.prev end prev:mousepressed(x, y, click) end if click == 1 then if CAMERA.focus then if not scripts.helpers.calculations.hasBuilding(addBuilding.state, CAMERA.focus.x, CAMERA.focus.y) and scripts.helpers.calculations.neighbouring(addBuilding.state, CAMERA.focus.x, CAMERA.focus.y) then addBuilding.state.buildings[#STATE.buildings + 1] = { x = CAMERA.focus.x, y = CAMERA.focus.y, building = addBuilding.building } Gamestate.pop() end end end scripts.rendering.renderUI.mousePressed(x, y, click) end function addBuilding:mousereleased(x, y, mouse_btn) local prev = addBuilding.prev while prev.prev and not prev.mousepressed do prev = prev.prev end if prev.mousereleased then prev:mousereleased(x, y, mouse_btn) end scripts.rendering.renderUI.mouseReleased(x, y, mouse_btn) end function addBuilding:update(dt) addBuilding.prev:update(dt, true) end function addBuilding:wheelmoved(x, y) scripts.rendering.renderUI.wheelmoved(x, y) end return addBuilding
object_static_structure_dathomir_static_science_desk = object_static_structure_dathomir_shared_static_science_desk:new { } ObjectTemplates:addTemplate(object_static_structure_dathomir_static_science_desk, "object/static/structure/dathomir/static_science_desk.iff")
Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118, ["Enter"] = 191 } local Stones = 0 local StoneLists = {} local IsPickingUp, IsProcessing, IsOpenMenu = false, false, false ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end Citizen.Wait(5000) end) function GenerateCoords(Zone) while true do Citizen.Wait(1) local CoordX, CoordY math.randomseed(GetGameTimer()) local modX = math.random(-10, 10) Citizen.Wait(100) math.randomseed(GetGameTimer()) local modY = math.random(-10, 10) CoordX = Zone.x + modX CoordY = Zone.y + modY local coordZ = GetCoordZ(CoordX, CoordY) local coord = vector3(CoordX, CoordY, coordZ) if ValidateObjectCoord(coord) then return coord end end end function GenerateCrabCoords() while true do Citizen.Wait(1) local crabCoordX, crabCoordY math.randomseed(GetGameTimer()) local modX = math.random(-10, 10) Citizen.Wait(100) math.randomseed(GetGameTimer()) local modY = math.random(-10, 10) crabCoordX = Config.Zone.Pos.x + modX crabCoordY = Config.Zone.Pos.y + modY local coordZ = GetCoordZ(crabCoordX, crabCoordY) local coord = vector3(crabCoordX, crabCoordY, coordZ) if ValidateObjectCoord(coord) then return coord end end end function GetCoordZ(x, y) local groundCheckHeights = { -27.77, 30.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, 48.0, 49.0, 50.0 } for i, height in ipairs(Config.GetCoordZ) do local foundGround, z = GetGroundZFor_3dCoord(x, y, height) if foundGround then return z end end return 43.0 end function ValidateObjectCoord(plantCoord) if Stones > 0 then local validate = true for k, v in pairs(StoneLists) do if GetDistanceBetweenCoords(plantCoord, GetEntityCoords(v), true) < 5 then validate = false end end if GetDistanceBetweenCoords(plantCoord, Config.Zone.Pos.x, Config.Zone.Pos.y, Config.Zone.Pos.z, false) > 50 then validate = false end return validate else return true end end function SpawnObjects() while Stones < 25 do Citizen.Wait(0) local CrabCoords = GenerateCrabCoords() local ListStone = { { Name = Config.object }, { Name = Config.object } } local random_stone = math.random(#ListStone) ESX.Game.SpawnLocalObject(ListStone[random_stone].Name, CrabCoords, function(object) PlaceObjectOnGroundProperly(object) FreezeEntityPosition(object, true) table.insert(StoneLists, object) Stones = Stones + 1 end) end end -- Spawn Object Citizen.CreateThread(function() while true do Citizen.Wait(10) local PlayerCoords = GetEntityCoords(PlayerPedId()) if GetDistanceBetweenCoords(PlayerCoords, Config.Zone.Pos.x, Config.Zone.Pos.y, Config.Zone.Pos.z, true) < 50 then SpawnObjects() Citizen.Wait(500) else Citizen.Wait(500) end end end) -- Create Blips Citizen.CreateThread(function() local Config1 = Config.Zone local blip1 = AddBlipForCoord(Config1.Pos.x, Config1.Pos.y, Config1.Pos.z) SetBlipSprite (blip1, Config1.Blips.Id) SetBlipDisplay(blip1, 4) SetBlipScale (blip1, Config1.Blips.Size) SetBlipColour (blip1, Config1.Blips.Color) SetBlipAsShortRange(blip1, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(Config1.Blips.Text) EndTextCommandSetBlipName(blip1) end) RegisterNetEvent('renzer_treasure:pickaxe') AddEventHandler('renzer_treasure:pickaxe', function () TriggerEvent('esx_inventoryhud:closeHud') if not pickcaxe then pickcaxe = true local ped = GetPlayerPed(-1) local position = GetEntityCoords(GetPlayerPed(PlayerId()), false) local object = GetClosestObjectOfType(position.x, position.y, position.z, 15.0, GetHashKey(Config.prop), false, false, false) if object ~= 0 then DeleteObject(object) end local x,y,z = table.unpack(GetEntityCoords(ped)) local drillProp = GetHashKey('hei_prop_heist_drill') local boneIndex = GetPedBoneIndex(ped, 28422) RequestModel(drillProp) while not HasModelLoaded(drillProp) do Citizen.Wait(100) end attachedDrill = CreateObject(drillProp, 1.0, 1.0, 1.0, 1, 1, 0) AttachEntityToEntity(attachedDrill, ped, boneIndex, 0.0, 0, 0.0, 0.0, 0.0, 0.0, 1, 1, 0, 0, 2, 1) SetEntityAsMissionEntity(attachedDrill, true, true) else local ped = GetPlayerPed(-1) local position = GetEntityCoords(GetPlayerPed(PlayerId()), false) local object = GetClosestObjectOfType(position.x, position.y, position.z, 15.0, GetHashKey(Config.prop), false, false, false) if object ~= 0 then DeleteObject(object) end local x,y,z = table.unpack(GetEntityCoords(ped)) local prop = CreateObject(GetHashKey(Config.prop), x, y, z + 0.2, true, true, true) local boneIndex = GetPedBoneIndex(ped, 57005) AttachEntityToEntity(prop, ped, boneIndex, 0.16, 0.00, 0.00, 600.0, 20.00, 140.0, true, true, false, true, 1, true) ClearPedTasks(ped) pickcaxe = false DetachEntity(prop, ped, boneIndex, 0.16, 0.00, 0.00, 600.0, 20.00, 140.0, true, true, false, true, 1, true) DeleteObject(prop) end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local playerPed = PlayerPedId() local coords = GetEntityCoords(playerPed) local nearbyObject, nearbyID local x = math.random(1,Config.deleteobject) local ped = GetPlayerPed(-1) for i=1, #StoneLists, 1 do if GetDistanceBetweenCoords(coords, GetEntityCoords(StoneLists[i]), false) < 1.2 then nearbyObject, nearbyID = StoneLists[i], i end end if nearbyObject and IsPedOnFoot(playerPed) then if pickcaxe then DrawTxtmaxez(0.960, 0.600, 1.0,1.0,0.55,"~y~เธเธ” E เน€เธžเธทเนˆเธญเน€เธˆเธฒเธฐ", 255,255,255,255) if IsControlJustReleased(0, Keys['E']) then local animDict = "anim@heists@fleeca_bank@drilling" local animLib = "drill_straight_idle" RequestAnimDict(animDict) while not HasAnimDictLoaded(animDict) do Citizen.Wait(50) end TaskPlayAnim(ped,animDict,animLib,1.0, -1.0, -1, 2, 0, 0, 0, 0) RequestAmbientAudioBank("DLC_HEIST_FLEECA_SOUNDSET", 0) RequestAmbientAudioBank("DLC_MPHEIST\\HEIST_FLEECA_DRILL", 0) RequestAmbientAudioBank("DLC_MPHEIST\\HEIST_FLEECA_DRILL_2", 0) drillSound = GetSoundId() PlaySoundFromEntity(drillSound, "Drill", attachedDrill, "DLC_HEIST_FLEECA_SOUNDSET", 1, 0) local particleDictionary = "scr_fbi5a" local particleName = "scr_bio_grille_cutting" RequestNamedPtfxAsset(particleDictionary) while not HasNamedPtfxAssetLoaded(particleDictionary) do Citizen.Wait(0) end SetPtfxAssetNextCall(particleDictionary) effect = StartParticleFxLoopedOnEntity(particleName, attachedDrill, 0.0, -0.6, 0.0, 0.0, 0.0, 0.0, 2.0, 0, 0, 0) ShakeGameplayCam("ROAD_VIBRATION_SHAKE", 1.0) FreezeEntityPosition(playerPed, true) TriggerEvent("mythic_progbar:client:progress", { name = "unique_action_name", duration = Config.timedoing, label = "เธเธณเธฅเธฑเธ‡เน€เธˆเธฒเธฐ", useWhileDead = false, canCancel = false, controlDisables = { disableMovement = true, disableCarMovement = true, disableMouse = false, disableCombat = true, } }, function(status) if not status then -- Do Something If Event Wasn't Cancelled end end) Citizen.Wait(Config.timedoing) StopSound(drillSound) FreezeEntityPosition(ped, false) StopParticleFxLooped(effect, 0) StopGameplayCamShaking(true) TriggerServerEvent('renzer_treasure:pickedUp') ClearPedTasks(playerPed) if x == 1 then ESX.Game.DeleteObject(nearbyObject) table.remove(StoneLists, nearbyID) Stones = Stones - 1 end FreezeEntityPosition(playerPed, false) ClearPedTasks(playerPed) end else DrawTxtmaxez(0.960, 0.600, 1.0,1.0,0.55,"~r~โš ๏ธ เธ„เธธเธ“เธ•เน‰เธญเธ‡เธ–เธทเธญ ~w~เธชเธงเนˆเธฒเธ™ ~r~เธเนˆเธญเธ™ โš ๏ธ", 255,255,255,255) end end end end) function anim() RequestAnimDict(animDict) while not HasAnimDictLoaded(animDict) do Citizen.Wait(50) end TaskPlayAnim(ped,"anim@heists@fleeca_bank@drilling","drill_straight_idle",1.0, -1.0, -1, 2, 0, 0, 0, 0) end RegisterFontFile('font4thai') fontId = RegisterFontId('font4thai') function DrawTxtmaxez(x,y ,width,height,scale, text, r,g,b,a) SetTextFont(fontId) SetTextProportional(0) SetTextScale(scale, scale) SetTextColour(r, g, b, a) SetTextDropShadow(0, 0, 0, 0,255) SetTextEdge(1, 0, 0, 0, 255) SetTextOutline() SetTextEntry("STRING") AddTextComponentString(text) DrawText(x - width/2, y - height/2 + 0.005) end function deleteobject () local nearbyObject, nearbyID local x = math.random(1,2) if x == 2 then ESX.Game.DeleteObject(nearbyObject) table.remove(StoneLists, nearbyID) Stones = Stones - 1 end end AddEventHandler('onResourceStop', function(resource) if resource == GetCurrentResourceName() then for k, v in pairs(StoneLists) do ESX.Game.DeleteObject(v) end end end)
local ffi = require('ffi') local vida = require('vida') local os = require('os') local bench = require('bench') local fast = vida.compile( vida.interface [[ int func(int a, int b); ]], vida.code [[ EXPORT int func(int a, int b) { return a + b; } ]]) local vector = vida.compile( vida.interface [[ void add(int *, int *, size_t); void mix(int *, int *, size_t, float); void sort(int *, size_t); ]], vida.code [[ #include <stddef.h> EXPORT void add(int *x, int *y, size_t n) { while (n--) *x++ += *y++; } EXPORT void mix(int *x, int *y, size_t n, float alpha) { while (n--) { *x++ += (int)(alpha * (*y++)); } } void quicksort_h(int *list, int m, int n) { int key, i, j, k, tmp; if (m < n) { k = (m + n) / 2; // pivot tmp = list[m]; list[m] = list[k]; list[k] = tmp; key = list[m]; i = m + 1; j = n; while (i <= j) { while((i <= n) && (list[i] <= key)) i++; while((j >= m) && (list[j] > key)) j--; if (i < j) { tmp = list[i]; list[i] = list[j]; list[j] = tmp; } } tmp = list[m]; list[m] = list[j]; list[j] = tmp; quicksort_h(list, m, j - 1); quicksort_h(list, j + 1, n); } } EXPORT void sort(int *list, size_t n) { quicksort_h(list, 0, n - 1); } ]]) assert(8 == fast.func(3, 5)) local n = 10000 local xvec = ffi.new('int[?]', n) local xx = {} local originalxx = {} for i = 0, n - 1 do xvec[i] = math.random(n) if i == 100 then xvec[i] = 999999 end xx[i] = xvec[i] originalxx[i] = xx[i] end local function ms(v) return string.format('%s ms', v * 1000) end local t = 0.5 for i = 0, n - 1 do xx[i] = originalxx[i] end print('luajit sort', ms(bench.smart(t, function () table.sort(xx) end))) assert(xx[n - 1] == 999999) -- spot check output for i = 0, n - 1 do xvec[i] = originalxx[i] end print('vector sort', ms(bench.smart(t, function () vector.sort(xvec, n) end))) assert(xvec[n - 1] == 999999) -- spot check output local n = 10000 local xvec = ffi.new('int[?]', n) local yvec = ffi.new('int[?]', n) local xx = {} local yy = {} for i = 0, n-1 do xvec[i] = i xx[i] = i yvec[i] = i * i yy[i] = i * i end vector.add(xvec, yvec, n) assert(110 == xvec[10]) vector.mix(xvec, yvec, n, 0.5) assert(160 == xvec[10]) print('luajit add (cdata)', ms(bench.smart(t, function () for j = 0, n - 1 do xvec[j] = xvec[j] + yvec[j] end end))) print('luajit add (hash)', ms(bench.smart(t, function () for j = 0, n - 1 do xx[j] = xx[j] + yy[j] end end))) jit.off() print('luajit add (hash nojit)', ms(bench.smart(t, function () for j = 0, n - 1 do xx[j] = xx[j] + yy[j] end end))) jit.on() jit.off() print('luajit add (nojit)', ms(bench.smart(t, function () for j = 0, n - 1 do xvec[j] = xvec[j] + yvec[j] end end))) jit.on() print('vector.add', ms(bench.smart(t, function () vector.add(xvec, yvec, n) end))) print('luajit mix', ms(bench.smart(t, function () local alpha = 0.001 for j = 0, n - 1 do xvec[j] = xvec[j] + alpha * yvec[j] end end))) print('vector.mix', ms(bench.smart(t, function () local alpha = 0.001 vector.mix(xvec, yvec, n, alpha) end)))
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx 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 General Public License for more details. You should have received a copy of the GNU General Public License along with luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-google" googlemodulename = "pbx-google" defaultstatus = "dnd" defaultstatusmessage = "PBX online, may lose messages" m = Map (modulename, translate("Google Accounts"), translate("This is where you set up your Google (Talk and Voice) Accounts, in order to start \ using them for dialing and receiving calls (voice chat and real phone calls). Please \ make at least one voice call using the Google Talk plugin installable through the \ GMail interface, and then log out from your account everywhere. Click \"Add\" \ to add as many accounts as you wish.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) -- Create a field "name" for each account that identifies the account in the backend. commit = false m.uci:foreach(modulename, "gtalk_jabber", function(s1) if s1.username ~= nil then name=string.gsub(s1.username, "%W", "_") if s1.name ~= name then m.uci:set(modulename, s1['.name'], "name", name) commit = true end end end) if commit == true then m.uci:commit(modulename) end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/asterisk restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(TypedSection, "gtalk_jabber", translate("Google Voice/Talk Accounts")) s.anonymous = true s.addremove = true s:option(Value, "username", translate("Email")) pwd = s:option(Value, "secret", translate("Password"), translate("When your password is saved, it disappears from this field and is not displayed \ for your protection. The previously saved password will be changed only when you \ enter a value different from the saved one.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end p = s:option(ListValue, "register", translate("Enable Incoming Calls (set Status below)"), translate("When somebody starts voice chat with your GTalk account or calls the GVoice, \ number (if you have Google Voice), the call will be forwarded to any users \ that are online (registered using a SIP device or softphone) and permitted to \ receive the call. If you have Google Voice, you must go to your GVoice settings and \ forward calls to Google chat in order to actually receive calls made to your \ GVoice number. If you have trouble receiving calls from GVoice, experiment \ with the Call Screening option in your GVoice Settings. Finally, make sure no other \ client is online with this account (browser in gmail, mobile/desktop Google Talk \ App) as it may interfere.")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" p = s:option(ListValue, "make_outgoing_calls", translate("Enable Outgoing Calls"), translate("Use this account to make outgoing calls as configured in the \"Call Routing\" section.")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" st = s:option(ListValue, "status", translate("Google Talk Status")) st:depends("register", "yes") st:value("dnd", translate("Do Not Disturb")) st:value("away", translate("Away")) st:value("available", translate("Available")) st.default = defaultstatus stm = s:option(Value, "statusmessage", translate("Google Talk Status Message"), translate("Avoid using anything but alpha-numeric characters, space, comma, and period.")) stm:depends("register", "yes") stm.default = defaultstatusmessage return m
function dbg.lunaType(c) if type(c)~='userdata' then return nil end local mt= getmetatable(c) if mt==nil then return nil end return mt.luna_class end function dbg.listLunaClasses(line) local usrCnam= string.sub(line, 7) local out2='' local out='' local outp='' for k,v in pairs(__luna)do if type(v)=='table' then local cname=v.luna_class if cname then local _, className=string.rightTokenize(cname,'%.') local nn=string.sub(k, 1, -string.len(className)-1) local namspac=string.gsub(nn,'_', '.') if namspac=='.' then namspac='' end if usrCnam=='' then out=out..namspac.. className..', ' else if namspac..className==usrCnam then local map={__add='+', __mul='*',__div='/', __unm='-', __sub='-'} local lastFn='funcName' for kk,vv in pairs(v) do if type(vv)=='function' then if string.sub(kk,1,13)=='_property_get' then outp=outp .. string.sub(kk,15)..', ' elseif string.sub(kk,1,13)=='_property_set' then --outp=outp .. string.sub(kk,15)..',' else if map[kk] then out2=out2..map[kk]..', ' else out2=out2..kk..', ' end lastFn=kk end end end out2=out2..'\n\n Tip! you can see the function parameter types by typing "'..usrCnam..'.'..lastFn..'()"!' out2=out2..'\n Known bug: property names can be incorrectly displayed. "' end end end end end if outp~='' then print('Properties:\n', outp) end print(out) if out2~='' then print('Member functions:\n', out2) end end function dbg.readLine(cursor) io.write(cursor) util.getch=nil if util.getch then if dbg.readLineInfo==nil then dbg.readLineInfo={""} dbg.readLineInfo.currLine=0 end local function save(f) local lines= dbg.readLineInfo lines[#lines+1]=f lines.currLine=#lines return f end local function goUp() local lines= dbg.readLineInfo lines.currLine=math.max(lines.currLine-1,0) return lines[lines.currLine+1] end local c='' -- getch gives 27 for non-ascii code while true do local code=util.getch() local ch= string.char(code) if ch=='\\' then util.putch(ch) ch=string.char(util.getch()) if ch==']' then print('cont') return 'cont' elseif ch=='[' then print('s') return 's' elseif ch=='k' then ch='' c=goUp() util.putch('\r'..cursor..c) else c=c..'\\' end end if ch=='\n' then util.putch('\n') return save(c) elseif code==127 then util.putch('\r') c=string.sub(c,1,-2) util.putch(cursor..c) else c=c..ch util.putch(ch) end end return '' else return io.read('*line') end end function dbg.traceBack(level) if level==nil then level=1 end while true do local info=debug.getinfo(level) local k=info.name if k==nil then break else print('----------------------------------------------------------') print('Level: ', level) print(info.short_src..":"..info.currentline..":"..k) print('Local variables:') dbg.locals(level) level=level+1 end end end function os.VI_path() if os.isUnix() then -- return "vim" -- use vim in a gnome-terminal return "gvim" else return "gvim" end end function os.vi_check(fn) local L = require "functional.list" local otherVim='vim' local servers=string.tokenize(os.capture(otherVim..' --serverlist 2>&1',true), "\n") local out=L.filter(function (x) return string.upper(fn)==x end,servers) local out_error=L.filter(function (x) return string.find(x,"Unknown option argument")~=nil end,servers) if #out_error>=1 then return nil end return #out>=1 end function os.vi_console_close_all() local L = require "functional.list" local servers=string.tokenize(os.capture('vim --serverlist',true), "\n") local out=L.filter(function (x) return fn~="GVIM" end,servers) for i,v in ipairs(out) do os.execute('vim --servername "'..v..'" --remote-send ":q<CR>"') end end function os.vi_console_cmd(fn, line) local cc if line then cc=' +'..line..' "'..fn..'"' else cc=' "'..fn..'"' end if not os.isUnix() and os.isFileExist("C:/msysgit/msysgit/share/vim/vim73/vim.exe") then return '"C:/msysgit/msysgit/share/vim/vim73/vim.exe" '..cc end return 'vim '..cc end function os.emacs_cmd(fn, line) local cc if line then cc=' +'..line..' "'..fn..'"' else cc=' "'..fn..'"' end --return 'lua ~/.config/mtiler/mstiler.lua launch-gui-app emacs '..cc return 'emacs '..cc end function os.gedit_cmd(fn, line) local cc if line then cc=' +'..line..' "'..fn..'"' else cc=' "'..fn..'"' end return 'gedit '..cc end function os.emacs_client_cmd(fn, line) local cc if line then cc=' +'..line..' "'..fn..'"' else cc=' "'..fn..'"' end return 'emacsclient -n '..cc end function os.emacs_console_cmd(fn, line) local cc if line then cc=' +'..line..' "'..fn..'"' else cc=' "'..fn..'"' end return 'emacs -nw '..cc end function os.vi_readonly_console_cmd(fn, line) local cc if line then cc=' +'..line..' "'..fn..'"' else cc=' "'..fn..'"' end return 'vim -R -M -c ":set nomodifiable" '..cc end function os.vi_line(fn, line) if os.vi_check(fn) then execute(os.vi_console_cmd(fn,line)) return end if not os.launch_vi_server() then print('Please launch gvim first!') return end local VI=os.VI_path()..' --remote-silent' local cmd=VI..' +'..line..' "'..fn..'"' --print(cmd) execute(cmd) end function os.launch_vi_server() local lenvipath=string.len(os.VI_path()) if os.vi_check(string.upper(os.VI_path())) then print("VI server GVIM open") return true end if false then -- recent ubuntu gvim doesn't start up from a terminal. print("launching GVIM server...") if os.isUnix() then if os.VI_path()=="vim" then execute('cd ../..', 'gnome-terminal -e "vim --servername vim"&') -- this line is unused by default. (assumed gnome dependency) else execute('cd ../..', os.VI_path()) end else if os.isFileExist(os.capture('echo %WINDIR%').."\\vim.bat") then execute('cd ..\\..', os.VI_path()) else execute('cd ..\\..', "start "..os.VI_path()) end end for i=1,10 do if os.vi_check(string.upper(os.VI_path())) then print("VI server GVIM open") break else print('.') --os.sleep(1) end end return true end return false end function os.vi(...) os._vi(os.VI_path(), ...) end function os._vi(servername, ...) local VI=os.VI_path() ..' --servername '..servername..' --remote-silent' local VI2=os.VI_path() ..' --servername '..servername..' --remote-send ":n ' local VI3='<CR>"' local targets={...} local otherVim='vim' local vicwd=os.capture(otherVim..' --servername '..servername..' --remote-expr "getcwd()"') if vicwd=="" then if not os.launch_vi_server() then print('Please launch gvim first!') return end -- try one more time vicwd=os.capture(otherVim ..' --servername '..servername..' --remote-expr "getcwd()"') end print('vicwd=',vicwd) local itgt, target for itgt,target2 in ipairs(targets) do -- local target=string.sub(target2,4) local target=target2 if string.find(target, '*') ~=nil or string.find(target, '?')~=nil then if false then -- open each file. too slow local subtgts=os.glob(target) local istgt,subtgt for istgt,subtgt in ipairs(subtgts) do local cmd=VI..' "'..subtgt..'"' if string.find(cmd,'~')==nil then os.execute(cmd) end end elseif string.sub(target, 1,6)=="../../" and string.sub(vicwd, -10)=="taesoo_cmu" then -- fastest method local cmd=VI2..string.sub(target,7)..VI3 print(cmd) if os.isUnix() then os.execute(cmd.."&") else os.execute("start "..cmd) end else local lastSep local newSep=0 local count=0 repeat lastSep=newSep newSep=string.find(target, "/", lastSep+1) count=count+1 until newSep==nil local path=string.sub(target, 0, lastSep-1) local filename if lastSep==0 then filename=string.sub(target,lastSep) else filename=string.sub(target, lastSep+1) end print(filename, path, count) -- execute("cd "..path, 'find . -maxdepth 1 -name "'..filename..'"| xargs '..EMACS) -- if string.find(filename, "*") then -- execute("cd "..path, 'find '..filename..' -maxdepth 1 | xargs '..EMACS) -- else print("cd "..path, VI.." "..filename) if os.isUnix() then execute("cd "..path, "rm -f *.lua~", VI.." "..filename.."&") else execute("cd "..path, "rm -f *.lua~", "rm -f #*#", VI.." "..filename) end -- end end else local cmd=VI..' "'..target..'"' print(cmd) if os.isUnix() then os.execute(cmd.."&") else os.execute(cmd) end end end end function os.emacs_client(fn, line) local cmd=os.emacs_client_cmd(fn,line) print(cmd) local tt=os.capture(cmd.." 2>&1", true) print(tt) if select(1,string.find(tt, 'have you started the server') ) then print('Error detected! launching a new server...') local cmd if line then cmd='emacs +'..line..' "'..fn..'" --eval "(server-start)"&' else cmd='emacs "'..fn..'" --eval "(server-start)"&' end print(cmd) os.execute(cmd) end end function os.emacs(...) local targets={...} local EMACS if os.isUnix() then EMACS="emacs" else EMACS="emacsclient -n" end local itgt, target print("emacs") for itgt,target2 in ipairs(targets) do -- local target=string.sub(target2,4) local target=target2 if string.find(target, '*') ~=nil or string.find(target, '?')~=nil then if false then -- open each file. too slow local subtgts=os.glob(target) local istgt,subtgt for istgt,subtgt in ipairs(subtgts) do local cmd=EMACS..' "'..subtgt..'"' if string.find(cmd,'~')==nil then os.execute(cmd) end end else local lastSep local newSep=0 local count=0 repeat lastSep=newSep newSep=string.find(target, "/", lastSep+1) count=count+1 until newSep==nil local path=string.sub(target, 0, lastSep-1) local filename if lastSep==0 then filename=string.sub(target,lastSep) else filename=string.sub(target, lastSep+1) end print(filename, path, count) -- execute("cd "..path, 'find . -maxdepth 1 -name "'..filename..'"| xargs '..EMACS) -- if string.find(filename, "*") then -- execute("cd "..path, 'find '..filename..' -maxdepth 1 | xargs '..EMACS) -- else execute("cd "..path, "rm -f *.lua~", "rm -f #*#", EMACS.." "..filename) -- end end else os.execute(EMACS..' "'..target..'"') end end end function os.emacs2(target) os.execute('find . -name "'..target..'"| xargs emacsclient -n') end function os.findDotEmacsFolder() local candidates= {"C:\\Documents and Settings\\Administrator\\Application Data", "C:\\Documents and Settings\\sonah\\Application Data", "C:\\usr\\texlive\\HOME", } for i, candidate in ipairs(candidates) do if os.isFileExist(candidate.."\\.emacs") then return candidate end end return "c:\\DotEmacsNotFound" end function dbg.showCode(fn,ln) util.iterateFile(fn, { iterate=function (self, lineno, c) if lineno>ln-5 and lineno<ln+5 then c=string.gsub(c, "\t", " ") if #c > 70 then c=string.sub(c,1,65).."..." end if lineno==ln then print(lineno.."* "..c) else print(lineno.." "..c) end end end } ) end function dbg.console(msg, stackoffset) stackoffset=stackoffset or 0 if(msg) then print (msg) end if dbg._consoleLevel==nil then dbg._consoleLevel=0 else dbg._consoleLevel=dbg._consoleLevel+1 end if fineLog~=nil and rank~=nil then debug.sethook() -- stop all kinds of debugger fineLog("dbg.console called") fineLog(dbg.callstackString(1)) fineLog(util.tostring(dbg.locals())) dbg.callstack0() return end local function at(line, index) return string.sub(line, index, index) end local function handleStatement(statement) local output if string.find(statement, "=") and not string.find(statement, "==") then -- assignment statement output={pcall(loadstring(statement))} else -- function calls or print variables: get results output={pcall(loadstring("return ("..statement..")"))} if output[1]==false and output[2]=="attempt to call a nil value" then -- statement output={pcall(loadstring(statement))} end end if output[1]==false then print("Error! ", output[2]) else if type(output[1])~='boolean' then output[2]=output[1] -- sometimes error code is not returned for unknown reasons. end if type(output[2])=='table' then if getmetatable(output[2]) and getmetatable(output[2]).__tostring then print(output[2]) else printTable(output[2]) end elseif output[2] then dbg.print(unpack(table.isubset(output, 2))) elseif type(output[2])=='boolean' then print('false') end end end local event while true do local cursor="[DEBUG"..dbg._consoleLevel.."] > " line=dbg.readLine(cursor) local cmd=at(line,1) local cmd_arg=tonumber(string.sub(line,2)) if not (string.sub(line,2)=="" or cmd_arg) then if not ( cmd=="r" and at(line,2)==" ") then if not string.isOneOf(cmd, ":", ";") then cmd=nil end end end if cmd=="h" or string.sub(line,1,4)=="help" then --help print('cs[level=3] : print callstack') print('c[level=1] : print source code at a stack level') print(';(lua statement) : eval lua statements. e.g.) ;print(a)') print(':(lua statement) : eval lua statements and exit debug console. e.g.) ;dbg.startCount(10)') print('s[number=1] : proceed n steps') print('r filename [lineno] : run until execution of a line. filename can be a postfix substring. e.g.) r syn.lua 32') print('e[level=2] : show current line (at callstack level 2) in emacs editor') print('v[level=2] : show current line (at callstack level 2) in vi editor') print('c[level=2] : show nearby lines (at callstack level 2) here') print('l[level=0] : print local variables. Results are saved into \'l variable.') print(" e.g) DEBUG]>print('l.self.mVec)") print('clist : list luna classes') print('clist className : list functions in the class') print('cont : exit debug mode') print('lua global variable : Simply typing "a" print the content of a global variable "a".') print('lua local variable : Simply typing "`a" print the content of a local variable "a".') print('lua statement : run it') elseif line=="cont" then break elseif string.sub(line,1,2)=="cs" then dbg.callstack(tonumber(string.sub(line,3)) or 3) elseif line=="clist" or string.sub(line,1,6)=='clist ' then dbg.listLunaClasses(line) elseif cmd=="c" then if cmd_arg==nil then local level=stackoffset while true do local info=debug.getinfo(level) if info then local a=string.sub(info.source, 1,1) if a=='=' or a=='[' then level=level+1 elseif select(1,string.find(info.source, 'mylib_debugger.lua')) then level=level+1 else break end else level=level+1 if level>40 then break end end end cmd_arg=level-stackoffset+1 print('c'..cmd_arg..':') end local level=(cmd_arg or 1)+stackoffset-1 -- -1 means 'excluding dbg.showCode' local info=debug.getinfo(level) if info then local a=string.sub(info.source, 1,1) if a=='=' or a=='[' then print(info.source) else local ln=info.currentline print(string.sub(info.source,2)) dbg.showCode(string.sub(info.source,2),ln) dbg._saveLocals=dbg.locals(level+1,true) end else print('no such level') end elseif cmd=="v" then local info=debug.getinfo((cmd_arg or 1)+stackoffset-1) if info and info.source=="=(tail call)" then info=debug.getinfo((cmd_arg or 1)+stackoffset) end if info then --os.vi_line(string.sub(info.source,2), info.currentline) local fn=string.sub(info.source,2) fn=os.relativeToAbsolutePath(fn) --fn=os.absoluteToRelativePath(fn, os.relativeToAbsolutePath("../..")) --os.luaExecute([[os.vi_line("]]..fn..[[",]]..info.currentline..[[)]]) os.vi_line(fn,info.currentline) end elseif cmd=="e" then local info=debug.getinfo((cmd_arg or 1)+stackoffset-1) if info then --os.emacs_client(os.relativeToAbsolutePath(string.sub(info.source,2)),info.currentline) os.execute(os.gedit_cmd(os.relativeToAbsolutePath(string.sub(info.source,2)),info.currentline)..'&') end elseif cmd==";" then handleStatement(string.sub(line,2)) elseif cmd==":" then handleStatement(string.sub(line,2)) break elseif cmd=="s" or cmd=="'" then local count=cmd_arg or 1 event={"s", count} break elseif cmd=="r" then event={"r", string.sub(line, 3)} break elseif cmd=="l" then local level=(cmd_arg or 1) dbg._saveLocals=dbg.locals(level) else statement=string.gsub(line, '``', 'dbg._saveLocals') statement=string.gsub(line, '`', 'dbg._saveLocals.') handleStatement(statement) end end dbg._consoleLevel=dbg._consoleLevel-1 if event then if event[1]=="s" then return dbg.step(event[2]) elseif event[1]=="r" then return dbg.run(event[2]) end end end function dbg._stepFunc (event, line) dbg._step=dbg._step+1 if dbg._step==dbg._nstep then debug.sethook() local info=debug.getinfo(2) if info then if select(1,string.find (info.source, 'mylib_debugger.lua')) then return dbg.step(1) end print(info.source, line) dbg.showCode(string.sub(info.source,2), line) end return dbg.console() end end function dbg.step(n) dbg._step=0 dbg._nstep=n debug.sethook(dbg._stepFunc, "l") end function dbg.callstack(level) if level==nil then level=1 end while true do local info=debug.getinfo(level) local k=info.name if k==nil then break else print(info.short_src..":"..info.currentline..":"..k) level=level+1 end end end function dbg.callstack0(level) if level==nil then level=1 end while true do local info=debug.getinfo(level) if info==nil then break end local k=info.name if k==nil then printTable(info) level=level+1 else print(info.short_src..":"..info.currentline..":"..k) level=level+1 end end end function dbg.locals(level, noprint) local output={} if level==nil then level=1 end cur=1 while true do if debug.getinfo(level, 'n')==nil then return output end k,v=debug.getlocal(level, cur) if k~=nil then output[k]=v or "(nil)" cur=cur+1 else break end end if not noprint then os.print(output) end return output end function dbg.run(run_str) -- run_str example: a.lua 374 local tbl=string.tokenize(run_str, " ") local filename=tbl[1] local lineno=tonumber(tbl[2]) --print(filename..","..tostring(lineno)) if tonumber(filename)~=nil then lineno=tonumber(filename) filename='' end if filename=='' then local info=debug.getinfo(3) filename=info.source if string.sub(info.source,1,1)=="=" then info=debug.getinfo(4) filename=info.source end end print("stop at "..filename.." +",lineno) local strlen=string.len(filename)*-1 dbg._runFuncParam={filename, strlen, lineno} debug.sethook(dbg._runFunc, "l") end function dbg._runFunc (event, line) local src=debug.getinfo(2).source local param=dbg._runFuncParam if string.sub(src, param[2])==param[1] and (param[3]==nil or line==param[3]) then debug.sethook() print(debug.getinfo(2).source, line) return dbg.console() end end -- outputs counts to trace.txt function dbg.startCount(dbgtime) if dbg.filePtr==nil then if dbgtime then print('Start re-counting until '..dbgtime) else print('Start counting.. ') print('Output will go to trace.txt') print('You can debug a crashing program by re-running the program using dbg.startCount(lastCount)') dbg.filePtr, msg=io.open("trace.txt", "w") if dbg.filePtr==nil then print(msg) return end end dbg._dbgtime=dbgtime dbg._count=0 --debug.sethook(dbg.countHookF, "l") debug.sethook(dbg.countHookF, "c") -- much faster though less accurate else end end function dbg.countHookF(event) local _count=dbg._count local _dbgtime=dbg._dbgtime if _dbgtime then if _count>_dbgtime-100 then local info=debug.getinfo(2) print('coundown', _dbgtime-_count, info.name, info.short_src, info.currentline) if _count==_dbgtime then debug.sethook() dbg.console() end end else local filePtr=dbg.filePtr filePtr:seek("set", 0) filePtr:write(_count) filePtr:flush() end dbg._count=_count+1 end
------------------------------------------------------------------------------- -- -- IMAP widget for Awesome 3.4 -- Copyright (C) 2011 Tuomas Jormola <[email protected]> -- -- Licensed under the terms of GNU General Public License Version 2.0. -- -- Description: -- -- Displays status of IMAP mailboxes by showing the amount of unread mails -- in each configured mailbox. When the mouse cursor is hovering over -- the widget, summary of unread mails in each mailbox is displayed -- (sender and subject). When new unread mails are discovered, -- a notification is displayed with summary of the new messages. -- Also displays an icon indicating whether there are unread messages -- in one of the monitored mailboxes. Clicking the icon launches -- an external application (if configured). -- -- Widget uses Vicious widget framework to gather widget data. -- -- This widget uses imap.lua by David Maus <[email protected]> -- http://github.com/dmj/misc/tree/master/lua/imap.lua/ -- -- Widget tries to use icons from the package gnome-icon-theme -- if available. -- -- -- Configuration: -- -- The load() function expects to get the IMAP server configuration as -- the 1st argument. You can specify as many IMAP server as you wish -- with each polling arbitrary amount of folders. -- -- Format of the configuration is as follows. -- { -- -- User name of the IMAP account, mandatory -- user = 'exampleuser1', -- -- Password of the IMAP account, mandatory -- password = 'examplepassword1', -- -- Host name or IP address of the IMAP server, mandatory -- host = 'mail1.example.com', -- -- Port of the IMAP server. 143 by default if SSL disabled, -- -- 993 if SSL enabled. -- port = 993, -- -- Enable SSL for the IMAP connection. -- -- Note that only IMAPS is supported, not IMAP with STARTTLS. -- ssl = true, -- -- Mailboxes to poll. INBOX is used by default. -- mailboxes = { 'INBOX', 'folder1', 'folder2' }, -- -- Show summary for this many unread mails per mailbox in the summary -- -- popup, default is 5 -- show_mail_coun = 3, -- -- Program that is launched when the user clicks on the widget area. -- -- Empty by default. -- command = 'evolution -c mail', -- -- Don't try to display any icons. Default is false (i.e. display icons). -- no_icon = true, -- -- Poll interval in seconds, 5 minutes by default -- update_interval = 3600, -- -- How long to show notifications in seconds, 10 seconds by default -- notification_delay = 5, -- }, -- -- Another example, minimal configuration using exampleuser2 as user, -- -- examplepassword2 as password, mail2.example.com as IMAP server, -- -- 143 as port, no SSL, polling INBOX, no program is run when clicking -- -- the widget, 5 minutes polling interval, show notifications for 10 -- -- seconds and show 5 unread mails per mailbox in the summary -- { -- user = 'exampleuser2', -- password = 'examplepassword2', -- host = 'mail1.example.com, -- } -- -- -- Theme: -- -- The widget uses following icons and fonts if available in the Awesome theme. -- -- theme.delightful_imap_mail_read - icon shown when mail in a mailbox is read -- theme.delightful_imap_mail_unread - icon shown when unread mail in a mailbox -- theme.delightful_error - icon shown when critical error has occurred -- theme.monospace_font - font for status text and notifications -- ------------------------------------------------------------------------------- local awful_button = require('awful.button') local awful_util = require('awful.util') local beautiful = require('beautiful') local image = require('image') local naughty = require('naughty') local widget = require('widget') local delightful_utils = require('delightful.utils') local vicious = require('vicious') local imap = require('imap') local capi = { mouse = mouse } local pairs = pairs local setmetatable = setmetatable local string = { format = string.format } local table = { insert = table.insert, remove = table.remove, sort = table.sort } local tostring = tostring local type = type module('delightful.widgets.imap') local widgets = {} local icons = {} local icon_files = {} local prev_icons = {} local imap_config = {} local imap_data = {} local notification_data = {} local config_description = { { name = 'user', required = true, validate = function(value) return delightful_utils.config_string(value) end }, { name = 'password', required = true, validate = function(value) return delightful_utils.config_string(value) end }, { name = 'host', required = true, validate = function(value) return delightful_utils.config_string(value) end }, { name = 'ssl', required = true, default = false, validate = function(value) return delightful_utils.config_boolean(value) end }, { name = 'ssl_string', required = true, default = function(config_data) if config_data.ssl then return 'sslv3' else return 'none' end end, validate = function(value) if not value or (value ~= 'sslv3' and value ~= 'none') then return false, 'needs to be either "sslv3" or "none"' else return true end end }, { name = 'port', required = true, default = function(config_data) if config_data.ssl then return 993 else return 143 end end, validate = function(value) return delightful_utils.config_int(value) end }, { name = 'mailboxes', required = true, default = 'INBOX', coerce = function(value) return delightful_utils.coerce_table(value) end, validate = function(value) return delightful_utils.config_table(value) end }, { name = 'show_mail_count', required = true, default = 5, validate = function(value) return delightful_utils.config_int(value) end }, { name = 'command', default = function(config_data) if mailer_cmd then return mailer_cmd end end, validate = function(value) return delightful_utils.config_string(value) end }, { name = 'no_icon', validate = function(value) return delightful_utils.config_boolean(value) end }, { name = 'update_interval', required = true, default = 5 * 60, validate = function(value) return delightful_utils.config_int(value) end }, { name = 'notification_delay', required = true, default = 10, validate = function(value) return delightful_utils.config_int(value) end }, -- User is not supposed to supply configuration of these settings { name = 'font', required = true, default = function(config_data) return beautiful.monospace_font or 'monospace' end, validate = function(value) return delightful_utils.config_string(value) end, }, } local icon_description = { read = { beautiful_name = 'delightful_imap_mail_read', default_icon = function() return 'stock_mail-open' end }, unread = { beautiful_name = 'delightful_imap_mail_unread', default_icon = function() return 'stock_mail-unread' end }, error = { beautiful_name = 'delightful_error', default_icon = function() return 'error' end }, } -- Poll the mailbox function update_data(imap_index) if not imap_data[imap_index] or not imap_data[imap_index].connection or not imap_config[imap_index].mailboxes then return end local connection = imap_data[imap_index].connection imap_data[imap_index].unread_total = 0 imap_data[imap_index].status_string = ' ' for mailbox_index, mailbox in pairs(imap_config[imap_index].mailboxes) do local mailbox_url = string.format('%s/%s', imap_url(imap_index), mailbox) imap_data[imap_index].mailboxes[mailbox_index].messages = nil connection.mailbox = mailbox local total, unread_num, imap_error total, imap_error = connection:total() if total then unread_num, imap_result = connection:unread() if unread_num then imap_data[imap_index].mailboxes[mailbox_index].total = total imap_data[imap_index].mailboxes[mailbox_index].unread = unread_num imap_data[imap_index].unread_total = imap_data[imap_index].unread_total + unread_num if unread_num > 0 then local unread_messages imap_error, unread_messages = connection:fetch(false, true, false) if unread_messages then local unread_message_ids = {} for unread_message_id in pairs(unread_messages) do table.insert(unread_message_ids, unread_message_id) end table.sort(unread_message_ids) imap_data[imap_index].mailboxes[mailbox_index].messages = {} for unread_message_index, unread_message_id in pairs(awful_util.table.reverse(unread_message_ids)) do imap_data[imap_index].mailboxes[mailbox_index].messages[unread_message_index] = unread_messages[unread_message_id] imap_data[imap_index].mailboxes[mailbox_index].messages[unread_message_index].uid = unread_message_id end if not imap_data[imap_index].mailboxes[mailbox_index].latest_message or imap_data[imap_index].mailboxes[mailbox_index].latest_message ~= imap_data[imap_index].mailboxes[mailbox_index].messages[1].uid then local n = 1 while imap_data[imap_index].mailboxes[mailbox_index].latest_message and imap_data[imap_index].mailboxes[mailbox_index].messages[n] and imap_data[imap_index].mailboxes[mailbox_index].messages[n].uid ~= imap_data[imap_index].mailboxes[mailbox_index].latest_message do if not notification_data[imap_index] then notification_data[imap_index] = {} end if not notification_data[imap_index][mailbox_index] then notification_data[imap_index][mailbox_index] = {} end table.insert(notification_data[imap_index][mailbox_index], imap_data[imap_index].mailboxes[mailbox_index].messages[n]) n = n + 1 end imap_data[imap_index].mailboxes[mailbox_index].latest_message = imap_data[imap_index].mailboxes[mailbox_index].messages[1].uid imap_data[imap_index].mailboxes[mailbox_index].error_string = nil end else imap_data[imap_index].mailboxes[mailbox_index].error_string = string.format('Failed to fetch unread messages in %s: %s', mailbox_url, imap_error) end end else imap_data[imap_index].mailboxes[mailbox_index].error_string = string.format('Failed to check the number of unread messages in %s: %s', mailbox_url, imap_error) end else imap_data[imap_index].mailboxes[mailbox_index].error_string = string.format('Failed to check the total number of messages in %s: %s', mailbox_url, imap_error) end local mailbox_status = '-' if imap_data[imap_index].mailboxes[mailbox_index].error_string then mailbox_status = string.format('<span color="red">%s</span>', mailbox_status); elseif unread_num then mailbox_status = tostring(unread_num) end imap_data[imap_index].status_string = string.format('%s%s', imap_data[imap_index].status_string, mailbox_status); if mailbox_index < #imap_config[imap_index].mailboxes then imap_data[imap_index].status_string = string.format('%s ', imap_data[imap_index].status_string); end end end -- Update widget icon based on the IMAP status data function update_icon(imap_index) if not icon_files.read or not icon_files.unread or not icon_files.error then return end if not imap_index or not icons[imap_index] or not imap_data[imap_index] then return end if not imap_data[imap_index].unread_total and not imap_data[imap_index].error_string then return end local icon_file if imap_data[imap_index].unread_total then icon_file = icon_files.read if imap_data[imap_index].unread_total > 0 then icon_file = icon_files.unread end end if imap_data[imap_index].error_string then icon_file = icon_files.error end if icon_file and (not prev_icons[imap_index] or prev_icons[imap_index] ~= icon_file) then prev_icons[imap_index] = icon_file icons[imap_index].image = image(icon_file) end end -- Text for the hover notification function summary_text(imap_index) local text = '' if not imap_index or not imap_data[imap_index] then return text end if imap_data[imap_index].error_string then text = imap_data[imap_index].error_string else for mailbox_index, mailbox in pairs(imap_data[imap_index].mailboxes) do text = string.format('%s<span font_style="italic">%s</span>', text, mailbox.name) if mailbox.error_string then text = string.format('%s\n <span color="red">%s</span>\n', text, mailbox.error_string ) else text = string.format('%s, <span font_weight="bold">%d</span> unread, <span font_weight="bold">%d</span> total\n', text, mailbox.unread, mailbox.total ) if mailbox.messages then for message_count, message in pairs(mailbox.messages) do text = string.format('%s %s <span font_weight="bold">%s</span>\n', text, pad_message_detail(message.from), pad_message_detail(message.subject) ) if message_count >= imap_config[imap_index].show_mail_count then total_message_count = #mailbox.messages if(total_message_count > message_count) then text = string.format('%s ... and <span font_weight="bold">%d</span> more\n', text, total_message_count - message_count ) end break end end end end text = string.format('%s\n', text) end end return text:gsub('\n*$', '') end -- Notification of new messages function show_notifications(imap_index) if not imap_index or not notification_data[imap_index] or not imap_data[imap_index] or not imap_data[imap_index].mailboxes then return end local text = string.format('<span font_weight="bold">%s</span>\n', imap_url(imap_index)) for mailbox_index, notifications in pairs(notification_data[imap_index]) do local mailbox_name = imap_data[imap_index].mailboxes[mailbox_index].name text = string.format('%s<span font_style="italic">%s</span>, <span font_weight="bold">%d</span> new\n', text, mailbox_name, #notifications) while notifications[1] do local message = table.remove(notifications, 1) text = string.format('%s %s <span font_weight="bold">%s</span>\n', text, pad_message_detail(message.from), pad_message_detail(message.subject) ) end if mailbox_index < #notification_data[imap_index] then text = string.format('%s\n', text) end end notification_data[imap_index] = nil naughty.notify({ text = text, icon = icon_files.unread, font = imap_config[imap_index].font or 'monospace', timeout = imap_config[imap_index].notification_delay, screen = capi.mouse.screen }) end -- Configuration handler function handle_config(user_config) local empty_config = delightful_utils.get_empty_config(config_description) if not user_config or #user_config == 0 then table.insert(imap_data, { error_string = 'No IMAP configuration' }) table.insert(imap_config, empty_config) return end for imap_index, user_config_data in pairs(user_config) do imap_data[imap_index] = {} local config_data = delightful_utils.normalize_config(user_config_data, config_description) local validation_errors = delightful_utils.validate_config(config_data, config_description) if validation_errors then imap_data[imap_index].error_string = string.format('Configuration errors:\n%s', delightful_utils.format_validation_errors(validation_errors)) imap_config[imap_index] = empty_config return end imap_config[imap_index] = config_data -- check that connection to the IMAP server works local imap_error local connection = imap.new(imap_config[imap_index].host, imap_config[imap_index].port, imap_config[imap_index].ssl_string ) _, imap_error = connection:connect() if imap_error then imap_data[imap_index].error_string = string.format('Failed to connect to %s: %s', imap_url(imap_config[imap_index]), imap_error) return end _, imap_error = connection:login(imap_config[imap_index].user, imap_config[imap_index].password) if imap_error then imap_data[imap_index].error_string = string.format('Failed to login to %s as user %s: %s', imap_url(imap_config[imap_index]), imap_config[imap_index].user, imap_error) return end imap_data[imap_index].connection = connection imap_data[imap_index].mailboxes = {} for mailbox_index, mailbox_name in pairs(imap_config[imap_index].mailboxes) do imap_data[imap_index].mailboxes[mailbox_index] = { name = mailbox_name } end end end -- Initalization function load(self, config) handle_config(config) icon_files = delightful_utils.find_icon_files(icon_description) for imap_index, data in pairs(imap_data) do local icon if not imap_config[imap_index].no_icon and icon_files.read and icon_files.unread and icon_files.error then icon = widget({ type = 'imagebox', name = 'imap_' .. imap_index }) end local popup_enter = function() local popup_title if data.error_string then popup_title = 'Error' else popup_title = imap_url(imap_index) end data.popup = naughty.notify({ title = popup_title, text = summary_text(imap_index), font = imap_config[imap_index].font or 'monospace', timeout = imap_config[imap_index].notification_delay, screen = capi.mouse.screen }) end local popup_leave = function() naughty.destroy(data.popup) end local widget = widget({ type = 'textbox'}) widget:add_signal('mouse::enter', popup_enter) widget:add_signal('mouse::leave', popup_leave) if icon then icon:add_signal('mouse::enter', popup_enter) icon:add_signal('mouse::leave', popup_leave) end if imap_config[imap_index].command then local buttons = awful_button({}, 1, function() awful_util.spawn(imap_config[imap_index].command, true) end) widget:buttons(buttons) if icon then icon:buttons(buttons) end end widgets[imap_index] = widget icons[imap_index] = icon vicious.register(widget, self, '$1', imap_config[imap_index].update_interval, imap_index) end return widgets, icons end -- Vicious worker function function vicious_worker(format, imap_index) update_data(imap_index) update_icon(imap_index) show_notifications(imap_index) local status local error_status = '<span color="red">' if icons[imap_index] then error_status = string.format('%s ', error_status); end error_status = string.format('%s!</span>', error_status); if not imap_data[imap_index] then status = error_status delightful_utils.print_error('imap', string.format('No imap_data[%d]', imap_index)) else if imap_data[imap_index].error_string then status = '<span color="red"> !</span>'; delightful_utils.print_error('imap', imap_data[imap_index].error_string) elseif imap_data[imap_index].status_string then status = imap_data[imap_index].status_string else imap_data[imap_index].error_string = string.format('No imap_data[%s][status_string] or imap_data[%s][error_string]', imap_index, imap_index) status = '<span color="red"> !</span>'; delightful_utils.print_error('imap', imap_data[imap_index].error_string) end end if imap_data[imap_index].mailboxes then for _, mailbox in pairs(imap_data[imap_index].mailboxes) do if mailbox.error_string then delightful_utils.print_error('imap', mailbox.error_string) end end end return status end -- Helpers function imap_url(data) if type(data) == 'number' then data = imap_config[data] end if not data then return end if not data.host or not data.port or not data.ssl then return end local url = 'imap' if data.ssl then url = string.format('%ss', url) end url = string.format('%s://%s', url, data.host) if (data.ssl and data.port ~= 993) or (not data.ssl and data.port ~= 143) then url = string.format('%s:%s', url, data.port); end return url end function pad_message_detail(line) return delightful_utils.pad_string_with_spaces(line, 48) end setmetatable(_M, { __call = function(_, ...) return vicious_worker(...) end })
-- ======= Copyright (c) 2003-2016, Unknown Worlds Entertainment, Inc. All rights reserved. ======= -- -- lua/TeamInfo.lua -- -- TeamInfo is used to sync information about a team to clients. -- A client on team 1 or 2 will only receive team info regarding their -- own team while a client on the kSpectatorIndex team will receive both -- teams info. -- -- Created by Brian Cronin ([email protected]) -- -- ========= For more information, visit us at http://www.unknownworlds.com ===================== Script.Load("lua/TeamMixin.lua") class 'TeamInfo' (Entity) TeamInfo.kMapName = "TeamInfo" TeamInfo.kTechTreeUpdateInterval = 1 -- max 100 tres/min, max 1000 minute game; should be enough kMaxTotalTeamResources = 100000 kMaxTotalPersonalResources = 100000 local networkVars = { teamResources = "float (0 to " .. kMaxTeamResources .. " by 0.1 [ 4 ])", totalTeamResources = "float (0 to " .. kMaxTotalTeamResources .. " by 1 [ 1 ])", personalResources = "float (0 to " .. kMaxTotalPersonalResources .. " by 0.1) [ 4 ]", numResourceTowers = "integer (0 to 99)", numCapturedResPoints = "integer (0 to 99)", latestResearchId = "integer", numCapturedTechPoint = "integer (0 to 99)", lastCommPingTime = "time", lastCommPingPosition = "vector", lastCommIsBot = "boolean", techActiveMask = "integer", techOwnedMask = "integer", playerCount = "integer (0 to " .. kMaxPlayers - 1 .. ")", spawnQueueTotal = "integer (0 to 64)", --max val should be ref'd from somewhere supplyUsed = "integer (0 to " .. 10 * kSupplyPerTechpoint .. ")", kills = "integer (0 to 9999)" } AddMixinNetworkVars(TeamMixin, networkVars) -- Relevant techs must be ordered with children techs coming after their parents TeamInfo.kRelevantTechIdsMarine = { kTechId.ShotgunTech, --kTechId.HeavyMachineGunTech, kTechId.MinesTech, kTechId.WelderTech, kTechId.GrenadeTech, kTechId.AdvancedArmory, kTechId.AdvancedArmoryUpgrade, kTechId.AdvancedWeaponry, kTechId.Weapons1, kTechId.Weapons2, kTechId.Weapons3, kTechId.Armor1, kTechId.Armor2, kTechId.Armor3, kTechId.PrototypeLab, kTechId.JetpackTech, kTechId.ExosuitTech, kTechId.DualMinigunTech, kTechId.ARCRoboticsFactory, kTechId.UpgradeRoboticsFactory, kTechId.MACEMPTech, kTechId.MACSpeedTech, kTechId.Observatory, kTechId.PhaseTech, kTechId.AdvancedMarineSupport, } TeamInfo.kRelevantTechIdsAlien = { kTechId.GorgeTunnelTech, kTechId.CragHive, kTechId.UpgradeToCragHive, kTechId.Shell, kTechId.TwoShells, kTechId.ThreeShells, kTechId.ShadeHive, kTechId.UpgradeToShadeHive, kTechId.Veil, kTechId.TwoVeils, kTechId.ThreeVeils, kTechId.ShiftHive, kTechId.UpgradeToShiftHive, kTechId.Spur, kTechId.TwoSpurs, kTechId.ThreeSpurs, kTechId.ResearchBioMassOne, kTechId.ResearchBioMassTwo, kTechId.ResearchBioMassThree, kTechId.Leap, kTechId.Xenocide, kTechId.BileBomb, kTechId.WebTech, kTechId.Umbra, kTechId.Spores, kTechId.MetabolizeEnergy, kTechId.MetabolizeHealth, kTechId.Stab, kTechId.Charge, kTechId.BoneShield, kTechId.Stomp, } local function CreateRelevantIdMaskMarine() local t = {} for i, techId in ipairs(TeamInfo.kRelevantTechIdsMarine) do local s = EnumToString(kTechId, techId) t[i] = s end TeamInfo.kRelevantIdMaskMarine = CreateBitMask(t) end local function CreateRelevantIdMaskAlien() local t = {} for i,techId in ipairs(TeamInfo.kRelevantTechIdsAlien) do local s = EnumToString(kTechId, techId) t[i] = s end TeamInfo.kRelevantIdMaskAlien = CreateBitMask(t) end function TeamInfo:OnCreate() Entity.OnCreate(self) CreateRelevantIdMaskMarine() CreateRelevantIdMaskAlien() if Server then self:SetUpdates(true, kRealTimeUpdateRate) self:Reset() end InitMixin(self, TeamMixin) end if Server then function TeamInfo:Reset() self.teamResources = 0 self.personalResources = 0 self.numResourceTowers = 0 self.latestResearchId = 0 self.researchDisplayTime = 0 self.lastTechPriority = 0 self.lastCommPingTime = 0 self.lastCommPingPosition = Vector(0,0,0) self.lastCommIsBot = false self.lastCommLoginTime = 0 self.totalTeamResources = 0 self.techActiveMask = 0 self.techOwnedMask = 0 self.playerCount = 0 self.spawnQueueTotal = 0 self.workerCount = 0 self.kills = 0 self.supplyUsed = 0 end end if Client then function TeamInfo:OnInitialized() Entity.OnInitialized(self) -- Hook up some callbacks for the GUI system. -- (These respect relevancy because they will only receive updates for TeamInfo that are -- relevant to the current player, eg both if player is spectating.) -- Notify GUI system when a team's resources change. self:AddFieldWatcher("teamResources", function(self2) local teamNumber = self2:GetTeamNumber() local eventName = string.format("OnTeam%dResourcesChanged", teamNumber) GetGlobalEventDispatcher():FireEvent(eventName, self2.teamResources) return true -- preserve field watcher end) -- Notify GUI system when a team's RT-count changes. self:AddFieldWatcher("numResourceTowers", function(self2) local teamNumber = self2:GetTeamNumber() local eventName = string.format("OnTeam%dResourceTowerCountChanged", teamNumber) GetGlobalEventDispatcher():FireEvent(eventName, self2.numResourceTowers) return true -- preserve field watcher end) -- Notify GUI system when a team's consumed supply changes. self:AddFieldWatcher("supplyUsed", function(self2) local teamNumber = self2:GetTeamNumber() local eventName = string.format("OnTeam%dSupplyUsedChanged", teamNumber) GetGlobalEventDispatcher():FireEvent(eventName, self2.supplyUsed) return true -- preserve field watcher end) -- Notify GUI system when a team's count of respawning players changes. self:AddFieldWatcher("spawnQueueTotal", function(self2) local teamNumber = self2:GetTeamNumber() local eventName = string.format("OnTeam%dSpawnQueueTotalChanged", teamNumber) GetGlobalEventDispatcher():FireEvent(eventName, self2.spawnQueueTotal) return true -- preserve field watcher end) -- Fire an event signifying that a new TeamInfo has just been initialized. GetGlobalEventDispatcher():FireEvent("OnTeamInfoInitialized", self) end end function TeamInfo:GetSpawnQueueTotal() return self.spawnQueueTotal end function TeamInfo:UpdateInfo() if self.team then self:SetTeamNumber(self.team:GetTeamNumber()) self.teamResources = self.team:GetTeamResources() self.playerCount = Clamp(self.team:GetNumPlayers(), 0, 31) self.totalTeamResources = self.team:GetTotalTeamResources() self.personalResources = 0 for index, player in ipairs(self.team:GetPlayers()) do self.personalResources = self.personalResources + player:GetResources() end local rtCount = 0 local rtActiveCount = 0 local rts = GetEntitiesForTeam("ResourceTower", self:GetTeamNumber()) for index, rt in ipairs(rts) do if rt:GetIsAlive() then rtCount = rtCount + 1 if rt:GetIsCollecting() then rtActiveCount = rtActiveCount + 1 end end end self.numCapturedResPoints = rtCount self.numResourceTowers = rtActiveCount self.kills = self.team:GetKills() if Server then if self.lastTechTreeUpdate == nil or (Shared.GetTime() > (self.lastTechTreeUpdate + TeamInfo.kTechTreeUpdateInterval)) then if not GetGamerules():GetGameStarted() then self.techActiveMask = 0 self.techOwnedMask = 0 else self:UpdateTechTreeInfo(self.team:GetTechTree()) end end if self.latestResearchId ~= 0 and self.researchDisplayTime < Shared.GetTime() then self.latestResearchId = 0 self.researchDisplayTime = 0 self.lastTechPriority = 0 end local team = self:GetTeam() self.numCapturedTechPoint = team:GetNumCapturedTechPoints() self.lastCommPingTime = team:GetCommanderPingTime() self.lastCommPingPosition = team:GetCommanderPingPosition() or Vector(0,0,0) self.supplyUsed = team:GetSupplyUsed() self.spawnQueueTotal = team:GetTotalInRespawnQueue() end end end function TeamInfo:GetRelevantTech() if self:GetTeamType() == kMarineTeamType then return TeamInfo.kRelevantIdMaskMarine, TeamInfo.kRelevantTechIdsMarine else return TeamInfo.kRelevantIdMaskAlien, TeamInfo.kRelevantTechIdsAlien end end function TeamInfo:GetSupplyUsed() return self.supplyUsed end function TeamInfo:GetNumWorkers() return self.workerCount end function TeamInfo:GetPingTime() return self.lastCommPingTime end function TeamInfo:GetPingPosition() return self.lastCommPingPosition end function TeamInfo:GetLastCommIsBot() return self.lastCommIsBot end function TeamInfo:SetWatchTeam(team) self.team = team self:SetTeamNumber(team:GetTeamNumber()) self:UpdateInfo() self:UpdateRelevancy() end function TeamInfo:GetNumCapturedResPoints() return self.numCapturedResPoints end function TeamInfo:OnCommanderLogin( commanderPlayer, forced ) self.lastCommIsBot = commanderPlayer:GetIsVirtual() if forced or GetGamerules():GetGameState() > kGameState.PreGame then if self.lastCommLoginTime == 0 then commanderPlayer:SetResources(0) end self.lastCommLoginTime = Shared.GetTime() end end function TeamInfo:GetTeamResources() return self.teamResources end function TeamInfo:GetPersonalResources() return self.personalResources end function TeamInfo:GetNumResourceTowers() return self.numResourceTowers end function TeamInfo:GetKills() return self.kills end function TeamInfo:UpdateRelevancy() self:SetRelevancyDistance(Math.infinity) local mask = 0 if self:GetTeamNumber() == kTeam1Index then mask = kRelevantToTeam1 elseif self:GetTeamNumber() == kTeam2Index then mask = kRelevantToTeam2 end self:SetExcludeRelevancyMask(mask) end function TeamInfo:OnUpdate(deltaTime) self:UpdateInfo() end function TeamInfo:SetLatestResearchedTech(researchId, displayTime, techPriority) if techPriority >= self.lastTechPriority then self.latestResearchId = researchId self.researchDisplayTime = displayTime self.lastTechPriority = techPriority end end function TeamInfo:UpdateTechTreeInfo(techTree) if not techTree then return end local relevantIdMask, relevantTechIds = self:GetRelevantTech() for i,techId in ipairs(relevantTechIds) do local techNode = techTree:GetTechNode(techId) if techNode and relevantIdMask then self:UpdateBitmasks(techId, techNode) end end self.lastTechTreeUpdate = Shared.GetTime() end function TeamInfo:GetNumCapturedTechPoints() return self.numCapturedTechPoint end function TeamInfo:GetLatestResearchedTech() return self.latestResearchId end function TeamInfo:GetTotalTeamResources() return self.totalTeamResources end function TeamInfo:GetTeamTechTreeInfo() return self.techActiveMask, self.techOwnedMask end --[[ A - Active O - Owned ----- A O | ----- 0 0 | None 1 0 | Researching 0 1 | Lost 1 1 | Researched -----]] function TeamInfo:UpdateBitmasks(techId, techNode) local relevantIdMask, relevantTechIds = self:GetRelevantTech() local techIdString = EnumToString(kTechId, techId) local mask = relevantIdMask[techIdString] -- Tech researching or researched if (techNode:GetResearching() and not techNode:GetResearched()) or techNode:GetHasTech() then self.techActiveMask = bit.bor(self.techActiveMask, mask) else self.techActiveMask = bit.band(self.techActiveMask, bit.bnot(mask)) end -- Tech has been owned at some point if techNode:GetHasTech() then self.techOwnedMask = bit.bor(self.techOwnedMask, mask) end -- Hide prerequisite techs when this tech has been researched if techNode:GetResearched() or (techNode:GetIsSpecial() and techNode:GetHasTech()) then local preq1 = techNode:GetPrereq1() local preq2 = techNode:GetPrereq2() if preq1 ~= nil then local msk = relevantIdMask[EnumToString(kTechId, preq1)] if msk then self.techActiveMask = bit.band(self.techActiveMask, bit.bnot(msk)) self.techOwnedMask = bit.band(self.techOwnedMask, bit.bnot(msk)) end end if preq2 ~= nil then local msk = relevantIdMask[EnumToString(kTechId, preq2)] if msk then self.techActiveMask = bit.band(self.techActiveMask, bit.bnot(msk)) self.techOwnedMask = bit.band(self.techOwnedMask, bit.bnot(msk)) end end end end function TeamInfo:GetPlayerCount() return self.playerCount end Shared.LinkClassToMap("TeamInfo", TeamInfo.kMapName, networkVars)
loader.LoadModel("matBall.obj") --here model for materials showcase is loaded loader.LoadModel("cube.obj") --here model for signs is loaded loader.LoadModel("capsule.obj") --here model for signs is loaded
--Minetest --Copyright (C) 2013 sapier -- --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.1 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. mm_texture = {} -------------------------------------------------------------------------------- function mm_texture.init() mm_texture.defaulttexturedir = core.get_texturepath() .. DIR_DELIM .. "base" .. DIR_DELIM .. "pack" .. DIR_DELIM mm_texture.basetexturedir = mm_texture.defaulttexturedir mm_texture.texturepack = core.setting_get("texture_path") mm_texture.gameid = nil end -------------------------------------------------------------------------------- function mm_texture.update(tab,gamedetails) if tab ~= "singleplayer" then mm_texture.reset() return end if gamedetails == nil then return end mm_texture.update_game(gamedetails) end -------------------------------------------------------------------------------- function mm_texture.reset() mm_texture.gameid = nil local have_bg = false local have_overlay = mm_texture.set_generic("overlay") if not have_overlay then have_bg = mm_texture.set_generic("background") end mm_texture.clear("header") mm_texture.clear("footer") core.set_clouds(false) mm_texture.set_generic("footer") mm_texture.set_generic("header") if not have_bg then if core.setting_getbool("menu_clouds") then core.set_clouds(true) else mm_texture.set_dirt_bg() end end end -------------------------------------------------------------------------------- function mm_texture.update_game(gamedetails) if mm_texture.gameid == gamedetails.id then return end local have_bg = false local have_overlay = mm_texture.set_game("overlay",gamedetails) if not have_overlay then have_bg = mm_texture.set_game("background",gamedetails) end mm_texture.clear("header") mm_texture.clear("footer") core.set_clouds(false) if not have_bg then if core.setting_getbool("menu_clouds") then core.set_clouds(true) else mm_texture.set_dirt_bg() end end mm_texture.set_game("footer",gamedetails) mm_texture.set_game("header",gamedetails) mm_texture.gameid = gamedetails.id end -------------------------------------------------------------------------------- function mm_texture.clear(identifier) core.set_background(identifier,"") end -------------------------------------------------------------------------------- function mm_texture.set_generic(identifier) --try texture pack first if mm_texture.texturepack ~= nil then local path = mm_texture.texturepack .. DIR_DELIM .."menu_" .. identifier .. ".png" if core.set_background(identifier,path) then return true end end if mm_texture.defaulttexturedir ~= nil then local path = mm_texture.defaulttexturedir .. DIR_DELIM .."menu_" .. identifier .. ".png" if core.set_background(identifier,path) then return true end end return false end -------------------------------------------------------------------------------- function mm_texture.set_game(identifier, gamedetails) if gamedetails == nil then return false end if mm_texture.texturepack ~= nil then local path = mm_texture.texturepack .. DIR_DELIM .. gamedetails.id .. "_menu_" .. identifier .. ".png" if core.set_background(identifier, path) then return true end end -- Find out how many randomized textures the subgame provides local n = 0 local filename local menu_files = core.get_dir_list(gamedetails.path .. DIR_DELIM .. "menu", false) for i = 1, #menu_files do filename = identifier .. "." .. i .. ".png" if table.indexof(menu_files, filename) == -1 then n = i - 1 break end end -- Select random texture, 0 means standard texture n = math.random(0, n) if n == 0 then filename = identifier .. ".png" else filename = identifier .. "." .. n .. ".png" end local path = gamedetails.path .. DIR_DELIM .. "menu" .. DIR_DELIM .. filename if core.set_background(identifier, path) then return true end return false end function mm_texture.set_dirt_bg() if mm_texture.texturepack ~= nil then local path = mm_texture.texturepack .. DIR_DELIM .."default_dirt.png" if core.set_background("background", path, true, 128) then return true end end --use base pack local minimalpath = defaulttexturedir .. "dirt_bg.png" core.set_background("background", minimalpath, true, 128) end
function elektraOpen(config, errorKey) return 0 end function elektraGet(returned, parentKey) return -1 end function elektraSet(returned, parentKey) return -1 end function elektraError(returned, parentKey) return -1 end function elektraClose(errorKey) return 0 end
----------------------------------- -- Area: Toraimarai Canal -- Mob: Scavenger Crab ----------------------------------- require("scripts/globals/regimes") ----------------------------------- function onMobDeath(mob, player, isKiller) tpz.regime.checkRegime(player, mob, 621, 1, tpz.regime.type.GROUNDS) end
setenv("TACC_A_DIR", "/unknown/apps/a/1.0")
local ECS = require "ECS" local skynet = require "skynet" local skill_cfg = require "game.config.scene.config_skill" local math_random = math.random local FightHelper = {} function FightHelper:Init( sceneMgr ) self.sceneMgr = sceneMgr self.entityMgr = sceneMgr.entityMgr end local randomAddOrMinus = function ( ) local isAdd = math_random(1,2)==1 return isAdd and 1 or -1 end --่Žทๅ–ๅฏๆ”ปๅ‡ป็š„ๅๆ ‡ function FightHelper:GetAssailablePos( curPos, targetPos, minDistance, maxDistance ) local xAddOrMinus = randomAddOrMinus() local xRandomDis = math_random(0, (maxDistance-minDistance)) local pos_x = targetPos.x + minDistance*xAddOrMinus + xRandomDis*xAddOrMinus local pos_y = targetPos.y local zAddOrMinus = randomAddOrMinus() local zRandomDis = math_random(0, (maxDistance-minDistance)) local pos_z = targetPos.z + minDistance*zAddOrMinus + zRandomDis*zAddOrMinus local newPos = {x=pos_x, y=pos_y, z=pos_z} return newPos end function FightHelper:IsSkillInCD( entity, skillID ) local hasCD = self.entityMgr:HasComponent(entity, "UMO.CD") if hasCD then local cdData = self.entityMgr:GetComponentData(entity, "UMO.CD") local cdEndTime = cdData[skillID] return cdEndTime and Time.timeMS <= cdEndTime end return false end function FightHelper:GetSkillCD( skillID, lv ) lv = lv or 1 local cfg = skill_cfg[skillID] if cfg and cfg.detail[lv] then return cfg.detail[lv].cd end return 0 end function FightHelper:ApplySkillCD( entity, skillID, lv ) local hasCD = self.entityMgr:HasComponent(entity, "UMO.CD") local endTime = 0 if hasCD then local cdData = self.entityMgr:GetComponentData(entity, "UMO.CD") local cd = self:GetSkillCD(skillID, lv) endTime = Time.timeMS + cd cdData[skillID] = endTime end return endTime end function FightHelper:IsLive( entity ) if entity and self.entityMgr:Exists(entity) and self.entityMgr:HasComponent(entity, "UMO.HP") then local hpData = self.entityMgr:GetComponentData(entity, "UMO.HP") return hpData.cur > 0 end return false end function FightHelper:ChangeHP( entity, hp, offsetValue, attacker ) if hp.cur <= 0 then return end hp.cur = hp.cur - offsetValue if hp.cur <= 0 then hp.cur = 0 hp.killedBy = attacker hp.deathTime = Time.time end local uid = self.entityMgr:GetComponentData(entity, "UMO.UID") if hp.cur <= 0 then --enter dead state if self.entityMgr:HasComponent(entity, "UMO.MonsterAI") then self.sceneMgr.monsterMgr:TriggerState(uid, "DeadState") local killer = self.sceneMgr:GetEntity(hp.killedBy) if self.entityMgr:HasComponent(killer, "UMO.MsgAgent") then local agent = self.entityMgr:GetComponentData(killer, "UMO.MsgAgent") local roleID = self.entityMgr:GetComponentData(killer, "UMO.TypeID") local monsterID = self.entityMgr:GetComponentData(entity, "UMO.TypeID") skynet.send(agent, "lua", "execute", "Task", "KillMonster", roleID, monsterID, 1) end end end end function FightHelper:ChangeSpeed( entity, victim_uid, caster_uid, bodName, isSet, speed ) if not entity then return end local isExist = self.entityMgr:Exists(entity) if not isExist then return end local speedData = self.entityMgr:GetComponentData(entity, "UMO.MoveSpeed") speedData:ChangeSpeed(bodName, isSet, speed) local buffEvent = { key = SceneConst.InfoKey.Speed, value = string.format("%s,%s,%s,%s", bodName, isSet and 1 or 0, speed and math.floor(speed) or 0, caster_uid), } self.sceneMgr.eventMgr:AddSceneEvent(victim_uid, buffEvent) end function FightHelper:ChangeTargetPos( entity, pos ) local speed = self.entityMgr:GetComponentData(entity, "UMO.MoveSpeed") if speed.curSpeed <= 0 then return end self.entityMgr:SetComponentData(entity, "UMO.TargetPos", pos) local uid = self.entityMgr:GetComponentData(entity, "UMO.UID") local change_target_pos_event_info = {key=SceneConst.InfoKey.TargetPos, value=math.floor(pos.x)..","..math.floor(pos.z), time=Time.timeMS} self.sceneMgr.eventMgr:AddSceneEvent(uid, change_target_pos_event_info) end return FightHelper
--------------------------------------------------------------------------------------------------- -- Issue: https://github.com/smartdevicelink/sdl_core/issues/2129 --------------------------------------------------------------------------------------------------- -- Description: -- In case: -- 1) Mobile app is audio/video source -- 2) Mobile app is deactivated -- 3) One of the event below is received from HMI within 'BC.OnEventChanged' (isActive = true) notification: -- DEACTIVATE_HMI, AUDIO_SOURCE -- 4) The same event notification (isActive = false) is received -- SDL must: -- 1) Send OnHMIStatus notification with 'audioStreamingState' = NOT_AUDIBLE and 'videoStreamingState' = NOT_STREAMABLE -- 2) Restore original state of mobile app -- Particular value depends on app's 'appHMIType' and described in 'testCases' table below --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/MobileProjection/Phase2/common') local runner = require('user_modules/script_runner') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false --[[ Local Variables ]] local onHMIStatusData = {} local testCases = { [001] = { t = "NAVIGATION", m = true, e = "DEACTIVATE_HMI" }, [002] = { t = "NAVIGATION", m = false, e = "DEACTIVATE_HMI" }, [003] = { t = "PROJECTION", m = true, e = "DEACTIVATE_HMI" }, [004] = { t = "PROJECTION", m = false, e = "DEACTIVATE_HMI" }, [005] = { t = "COMMUNICATION", m = true, e = "DEACTIVATE_HMI" }, [006] = { t = "COMMUNICATION", m = false, e = "DEACTIVATE_HMI" }, [007] = { t = "MEDIA", m = true, e = "DEACTIVATE_HMI" }, [008] = { t = "MEDIA", m = false, e = "DEACTIVATE_HMI" }, [009] = { t = "DEFAULT", m = true, e = "DEACTIVATE_HMI" }, [010] = { t = "DEFAULT", m = false, e = "DEACTIVATE_HMI" }, [011] = { t = "NAVIGATION", m = true, e = "AUDIO_SOURCE" }, [012] = { t = "NAVIGATION", m = false, e = "AUDIO_SOURCE" }, [013] = { t = "PROJECTION", m = true, e = "AUDIO_SOURCE" }, [014] = { t = "PROJECTION", m = false, e = "AUDIO_SOURCE" }, [015] = { t = "COMMUNICATION", m = true, e = "AUDIO_SOURCE" }, [016] = { t = "COMMUNICATION", m = false, e = "AUDIO_SOURCE" }, [017] = { t = "MEDIA", m = true, e = "AUDIO_SOURCE" }, [018] = { t = "MEDIA", m = false, e = "AUDIO_SOURCE" }, [019] = { t = "DEFAULT", m = true, e = "AUDIO_SOURCE" }, [020] = { t = "DEFAULT", m = false, e = "AUDIO_SOURCE" }, } --[[ Local Functions ]] local function sendEvent(pTC, pEvent, pIsActive) local count = 1 if onHMIStatusData.hmiL == "BACKGROUND" then count = 0 end local status = common.cloneTable(onHMIStatusData) if pIsActive == true then status.hmiL = "BACKGROUND" status.aSS = "NOT_AUDIBLE" status.vSS = "NOT_STREAMABLE" end common.getHMIConnection():SendNotification("BasicCommunication.OnEventChanged", { eventName = pEvent, isActive = pIsActive }) common.getMobileSession():ExpectNotification("OnHMIStatus", { hmiLevel = status.hmiL }) :ValidIf(function(_, data) return common.checkAudioSS(pTC, "App1", status.aSS, data.payload.audioStreamingState) end) :ValidIf(function(_, data) return common.checkVideoSS(pTC, "App1", status.vSS, data.payload.videoStreamingState) end) :Times(count) common.wait(500) end local function deactivateApp() common.getHMIConnection():SendNotification("BasicCommunication.OnAppDeactivated", { appID = common.getHMIAppId() }) common.getMobileSession():ExpectNotification("OnHMIStatus") :Do(function(_, data) onHMIStatusData.hmiL = data.payload.hmiLevel onHMIStatusData.aSS = data.payload.audioStreamingState onHMIStatusData.vSS = data.payload.videoStreamingState end) end --[[ Scenario ]] for n, tc in common.spairs(testCases) do runner.Title("TC[" .. string.format("%03d", n) .. "]: " .. "[hmiType:" .. tc.t .. ", isMedia:" .. tostring(tc.m) .. ", event:" .. tc.e .. "]") runner.Step("Clean environment", common.preconditions) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Step("Set App Config", common.setAppConfig, { 1, tc.t, tc.m }) runner.Step("Register App", common.registerApp) runner.Step("Activate App", common.activateApp) runner.Step("Deactivate App", deactivateApp) runner.Step("Send event from HMI isActive: true", sendEvent, { n, tc.e, true }) runner.Step("Send event from HMI isActive: false", sendEvent, { n, tc.e, false }) runner.Step("Clean sessions", common.cleanSessions) runner.Step("Stop SDL", common.postconditions) end runner.Step("Print failed TCs", common.printFailedTCs)
local function ChangeUser(msg) local text = msg.content_.text_ if ChatType == 'sp' or ChatType == 'gp' then if text then tdcli_function({ID = "GetUser",user_id_ = msg.sender_user_id_},function(arg,result) if result.id_ then local Alli = DevAli:get("IrAqTEAM:User"..result.id_) if not result.username_ then if Alli then Dev_Ali(msg.chat_id_, msg.id_, 1, "ุญุฐู ู…ุนุฑูู‡ ุฎู…ุทูˆ ุจุณุฑุนู‡ุŒ ๐Ÿ˜น๐Ÿ’” \nู‡ุฐุง ู…ุนุฑูู‡ @"..Alli.."", 1, 'html') DevAli:del("IrAqTEAM:User"..result.id_) end end if result.username_ then if Alli and Alli ~= result.username_ then local Ali_text = { 'ู…ุนุฑููƒ ุงู„ุฌุฏูŠุฏ ุนุดุฑู‡ ุจุฑุจุน ู…ุญุฏ ูŠุงุฎุฐู‡๐Ÿ˜น๐Ÿ’”', "ู‡ุงู‡ุง ุบูŠุฑุช ู…ุนุฑููƒ ู†ุดุฑูˆูƒ ุจู‚ู†ุงุฉ ูุถุงูŠุญ๐Ÿ˜น๐Ÿ’”๐Ÿ’ญ", "ู…ุนุฑููƒ ุงู„ุฌุฏูŠุฏ ุญู„ูˆ ู…ู†ูŠู† ุฎุงู…ุทู‡ุŸ!๐Ÿคคโ™ฅ๏ธ", "ู…ุนุฑููƒ ุงู„ู‚ุฏูŠู… @"..result.username_.." ุถู…ู‡ ุจู‚ู†ุงุฉ ู„ุงูŠู†ุจุนุตุŒ ๐Ÿ˜นโ™ฅ๏ธ", } Allis = math.random(#Ali_text) Dev_Ali(msg.chat_id_, msg.id_, 1, Ali_text[Allis], 1, 'html') end DevAli:set("IrAqTEAM:User"..result.id_, result.username_) end end end,nil) end end end return { IrAq = ChangeUser }
colour_style = {["off_color"] = "cfc", ["on_color"] = "cfc", ["line_color"] = "000", ["line_width"] = "2"}; line_style = {["off_color"] = "fff", ["on_color"] = "fff", ["line_color"] = "000", ["line_width"] = "2"}; text_style = {["font_size"] = "16"} numb = {} out = {} xm = {} ym = {} xt = {} yt = {} total = 12 max = math.floor(total/4) numb[1] = 1+math.random(max) numb[2] = numb[1] + math.random(3*max - numb[1]) numb[3] = total - numb[1] - numb[2] if (numb[3] < 2) then numb[2] = math.floor(numb[2]/2) numb[3] = total - numb[1] - numb[2] end factor = 8 + math.random(92) for i = 1,3 do out[i] = numb[i] * factor end total = total * factor mycanvas = function() w = 5 ow = 10 v = 50 ov = 15 wy = 100 oc = 150 ocy = 120 ind = -1 for i = 1,3 do ind = ind + numb[i] if (ind == 0) then xm[i] = 0 ym[i] = -wy+ow xt[i] = xm[i]-2*ow yt[i] = ym[i]+v end if (ind == 1) then xm[i] = wy/2-ow/5 ym[i] = -wy+2*ow xt[i] = 0 yt[i] = ym[i]+ov end if (ind == 2) then xm[i] = wy-ov ym[i] = -wy/2 xt[i] = xm[i]-v yt[i] = ym[i]-ov end if (ind == 3) then xm[i] = wy ym[i] = 0 xt[i] = xm[i]-v yt[i] = ym[i]-2*ow end if (ind == 4) then xm[i] = wy-ov ym[i] = wy/2-w xt[i] = xm[i]-ov yt[i] = 0 end if (ind == 5) then xm[i] = wy/2-ow/5 ym[i] = wy-2*ow xt[i] = xm[i]+ov yt[i] = ym[i]-v end if (ind == 6) then xm[i] = 0 ym[i] = wy-ow xt[i] = xm[i]+2*ow yt[i] = ym[i]-v end if (ind == 7) then xm[i] = -wy/2+ow/5-2 ym[i] = wy-2*ow xt[i] = 0 yt[i] = ym[i]-2*ov end if (ind == 8) then xm[i] = -wy+ov ym[i] = wy/2-w xt[i] = xm[i]+v yt[i] = ym[i]+ov end if (ind == 9) then xm[i] = -wy ym[i] = 0 xt[i] = xm[i]+v yt[i] = ym[i]+2*ow end if (ind == 10) then xm[i] = -wy+ov ym[i] = -wy/2+w xt[i] = xm[i]+v yt[i] = 0 end if (ind == 11) then xm[i] = -wy/2+ow/5-2 ym[i] = -wy+2*ow xt[i] = xm[i]-ov yt[i] = ym[i]+v end end lib.start_canvas(300, 250, "center") lib.add_circle (oc, ocy, wy-w, colour_style, true, false ) corr = math.floor(wy/4) ch = math.random(3) for i = 1,3 do lib.add_straight_path(oc, ocy, {{xm[i], ym[i]}}, line_style, false, false) x = oc + xt[i] y = ocy + yt[i] if (i == ch) then lib.add_text(x, y, tostring(out[i]), text_style, false, false) else lib.add_input(x-ov, y-ov, 50, 30, lib.check_number(out[i],30)) end end lib.end_canvas() end
--# selene: allow(unused_variable) ---@diagnostic disable: unused-local -- Switch focus with a transient per-application keyboard shortcut ---@class hs.hints local M = {} hs.hints = M -- A fully specified family-face name, preferrably the PostScript name, such as Helvetica-BoldOblique or Times-Roman. (The Font Book app displays PostScript names of fonts in the Font Info panel.) -- The default value is the system font M.fontName = nil -- The size of font that should be used. A value of 0.0 will use the default size. M.fontSize = nil -- This controls the set of characters that will be used for window hints. They must be characters found in hs.keycodes.map -- The default is the letters A-Z. Note that if `hs.hints.style` is set to "vimperator", this variable will be ignored. M.hintChars = nil -- Opacity of the application icon. Default is 0.95. M.iconAlpha = nil -- If there are less than or equal to this many windows on screen their titles will be shown in the hints. -- The default is 4. Setting to 0 will disable this feature. M.showTitleThresh = nil -- If this is set to "vimperator", every window hint starts with the first character -- of the parent application's title M.style = nil -- If the title is longer than maxSize, the string is truncated, -1 to disable, valid value is >= 6 M.titleMaxSize = nil -- Displays a keyboard hint for switching focus to each window -- -- Parameters: -- * windows - An optional table containing some `hs.window` objects. If this value is nil, all windows will be hinted -- * callback - An optional function that will be called when a window has been selected by the user. The function will be called with a single argument containing the `hs.window` object of the window chosen by the user -- * allowNonStandard - An optional boolean. If true, all windows will be included, not just standard windows -- -- Returns: -- * None -- -- Notes: -- * If there are more windows open than there are characters available in hs.hints.hintChars, multiple characters will be used -- * If hints.style is set to "vimperator", every window hint is prefixed with the first character of the parent application's name -- * To display hints only for the currently focused application, try something like: -- * `hs.hints.windowHints(hs.window.focusedWindow():application():allWindows())` function M.windowHints(windows, callback, allowNonStandard, ...) end
----------------------------------------------- -- weapon.lua -- Represents a generic weapon a player can wield or pick up -- I think there should be only 2 types of weapons: ---- the only action that should play once is the animation for ing your weapon -- Created by NimbusBP1729 ----------------------------------------------- local sound = require 'vendor/TEsound' local anim8 = require 'vendor/anim8' local game = require 'game' local collision = require 'hawk/collision' local utils = require 'utils' local gamestate = require 'vendor/gamestate' local camera = require 'camera' local app = require 'app' local Weapon = {} Weapon.__index = Weapon Weapon.isWeapon = true function Weapon.new(node, collider, plyr, weaponItem) local weapon = {} setmetatable(weapon, Weapon) weapon.name = node.name weapon.type = node.type weapon.props = utils.require( 'nodes/weapons/' .. weapon.name ) weapon.item = weaponItem -- Checks if for plyr and if plyr is a player weapon.player = (plyr and plyr.isPlayer) and plyr or nil weapon.quantity = node.properties.quantity or weapon.props.quantity or 1 weapon.foreground = node.properties.foreground == 'true' weapon.position = {x = node.x, y = node.y} weapon.velocity={} weapon.velocity.x = node.properties.velocityX or 0 weapon.velocity.y = node.properties.velocityY or 0 --position that the hand should be placed with respect to any frame weapon.hand_x = weapon.props.hand_x weapon.hand_y = weapon.props.hand_y --setting up the sheet local colAmt = weapon.props.frameAmt if node.properties.sprite then weapon.image = love.graphics.newImage(node.properties.sprite) end weapon.sheet = love.graphics.newImage('images/weapons/'..weapon.name..'.png') weapon.sheetWidth = weapon.sheet:getWidth() weapon.sheetHeight = weapon.sheet:getHeight() weapon.frameWidth = weapon.sheetWidth/colAmt weapon.frameHeight = weapon.sheetHeight-15 weapon.width = weapon.props.width or 10 weapon.height = weapon.props.height or 10 weapon.dropWidth = weapon.props.dropWidth weapon.dropHeight = weapon.props.dropHeight weapon.bbox_width = weapon.props.bbox_width weapon.bbox_height = weapon.props.bbox_height weapon.bbox_offset_x = weapon.props.bbox_offset_x weapon.bbox_offset_y = weapon.props.bbox_offset_y weapon.magical = weapon.props.magical or false weapon.wield_rate = weapon.props.animations.wield[3] local g = anim8.newGrid(weapon.frameWidth, weapon.frameHeight, weapon.sheetWidth, weapon.sheetHeight) weapon.defaultAnimation = anim8.newAnimation( weapon.props.animations.default[1], g(unpack(weapon.props.animations.default[2])), weapon.props.animations.default[3]) weapon.wieldAnimation = anim8.newAnimation( weapon.props.animations.wield[1], g(unpack(weapon.props.animations.wield[2])), weapon.props.animations.wield[3]) if weapon.magical then weapon.projectile = node.properties.projectile weapon.chargeUpTime = 0 weapon.charged = false weapon.defaultChargedAnimation = anim8.newAnimation( weapon.props.animations.defaultCharged[1], g(unpack(weapon.props.animations.defaultCharged[2])), weapon.props.animations.defaultCharged[3]) weapon.wieldChargedAnimation = anim8.newAnimation( weapon.props.animations.wieldCharged[1], g(unpack(weapon.props.animations.wieldCharged[2])), weapon.props.animations.wieldCharged[3]) weapon.cameraShake = weapon.props.cameraShake or false weapon.camera = { tx = 0, ty = 0, sx = 1, sy = 1, } end weapon.animation = weapon.defaultAnimation weapon.damage = node.properties.damage or weapon.props.damage or 1 -- Damage that does not affect all enemies ie. stab, fire weapon.special_damage = weapon.props.special_damage or {} weapon.knockback = node.properties.knockback or weapon.props.knockback or 10 weapon.dead = false --create the bounding box weapon:initializeBoundingBox(collider) -- Represents direction of the weapon when no longer in the players inventory weapon.direction = node.properties.direction or 'right' weapon.flipY = node.properties.flipY or 'false' --audio clip when weapon is put away weapon.unuseAudioClip = node.properties.unuseAudioClip or weapon.props.unuseAudioClip or 'sword_sheathed' --audio clip when weapon hits something weapon.hitAudioClip = node.properties.hitAudioClip or weapon.props.hitAudioClip or nil --audio clip when weapon swing through air weapon.swingAudioClip = node.properties.swingAudioClip or weapon.props.swingAudioClip or nil weapon.action = weapon.props.action or 'wieldaction' weapon.dropping = false weapon.dropped = false if weapon.player and weapon.props.trigger then weapon.db = app.gamesaves:active() local trigger = weapon.db:get( weapon.name .. '-trigger', false) if not trigger then weapon.props.trigger(weapon) weapon.db:set( weapon.name .. '-trigger', true) end end return weapon end --- -- Draws the weapon to the screen -- @return nil function Weapon:draw() if self.dead then return end local scalex = 1 if self.player then if self.player.character.direction=='left' then scalex = -1 self.direction = 'left' else self.direction = 'right' end elseif self.direction == 'left' then scalex = -1 end local scaley = 1 local offsetY = 0 if self.flipY == 'true' then scaley = -1 offsetY = self.boxHeight or 0 end -- Flipping an image moves it, this adjust for that image flip offset local offsetX = 0 if not self.player and self.direction == 'left' then offsetX = self.boxWidth or 0 end if self.image then love.graphics.draw(self.image, self.position.x + offsetX, self.position.y + offsetY, 0, scalex, scaley) return end local animation = self.animation if not animation then return end animation:draw(self.sheet, math.floor(self.position.x) + offsetX, self.position.y + offsetY, 0, scalex, scaley) end --- -- Called when the weapon begins colliding with another node -- @return nil function Weapon:collide(node, dt, mtv_x, mtv_y) if not node or self.dead or (self.player and not self.player.wielding) or self.dropped then return end if node.isPlayer then return end if self.dropping and (node.isFloor or node.floorspace or node.isPlatform) then self.dropping = false end if node.hurt and self.player then local knockback = self.player.character.direction == 'right' and self.knockback or -self.knockback node:hurt(self.damage, self.special_damage, knockback) self.collider:setGhost(self.bb) end if self.hitAudioClip and node.hurt then sound.playSfx(self.hitAudioClip) end end function Weapon:initializeBoundingBox(collider) self.boxTopLeft = {x = self.position.x, y = self.position.y} self.boxWidth = self.bbox_width self.boxHeight = self.bbox_height --update the collider using the bounding box self.bb = collider:addRectangle(self.boxTopLeft.x,self.boxTopLeft.y,self.boxWidth,self.boxHeight) self.bb.node = self self.collider = collider if self.player then self.collider:setGhost(self.bb) else self.collider:setSolid(self.bb) end end --- -- Called when the weapon is returned to the inventory function Weapon:deselect() self.dead = true self.collider:remove(self.bb) self.containerLevel:removeNode(self) self.player.wielding = false self.player.currently_held = nil local state = self.player.isClimbing and 'climbing' or 'default' self.player:setSpriteStates(state) sound.playSfx(self.unuseAudioClip) end --default update method --overload this in the specific weapon if this isn't well-suited for your weapon function Weapon:update(dt, player, map) if self.dead then return end --the weapon is in the level unclaimed if not self.player then if self.dropping then -- Need to add an offset for dropping local nx, ny = collision.move(map, self, self.position.x + self.bbox_offset_x[1], self.position.y, self.dropWidth, self.dropHeight, self.velocity.x * dt, self.velocity.y * dt) self.position.x = nx - self.bbox_offset_x[1] self.position.y = ny self.velocity = {x = self.velocity.x, y = self.velocity.y + game.gravity*dt} local offset_x = 0 if self.bbox_offset_x then offset_x = self.bbox_offset_x[1] end if self.bb then self.bb:moveTo(self.position.x + offset_x + self.dropWidth / 2, self.position.y + self.dropHeight / 2) end end -- Item has finished dropping in the level if not self.dropping and self.dropped and not self.saved then self.containerLevel:saveAddedNode(self) self.saved = true end else --the weapon is being used by a player local player = self.player local plyrOffset = player.width/2 if not self.position or not self.position.x or not player.position or not player.position.x then return end local framePos = (player.wielding) and self.animation.position or 1 if player.character.direction == "right" then self.position.x = math.floor(player.position.x) + (plyrOffset-self.hand_x) +player.offset_hand_left[1] - player.character.bbox.x self.position.y = math.floor(player.position.y) + (-self.hand_y) + player.offset_hand_left[2] - player.character.bbox.y if self.bb then self.bb:moveTo(self.position.x + (self.bbox_offset_x[framePos] or 0) + self.bbox_width/2, self.position.y + (self.bbox_offset_y[framePos] or 0) + self.bbox_height/2) end else self.position.x = math.floor(player.position.x) + (plyrOffset+self.hand_x) +player.offset_hand_right[1] - player.character.bbox.x self.position.y = math.floor(player.position.y) + (-self.hand_y) + player.offset_hand_right[2] - player.character.bbox.y if self.bb then self.bb:moveTo(self.position.x - (self.bbox_offset_x[framePos] or 0) - self.bbox_width/2, self.position.y + (self.bbox_offset_y[framePos] or 0) + self.bbox_height/2) end end if player.offset_hand_right[1] == 0 or player.offset_hand_left[1] == 0 then --print(string.format("Need hand offset for %dx%d", player.frame[1], player.frame[2])) end if self.magical then if not self.charged then self.chargeUpTime = self.chargeUpTime + dt if self.chargeUpTime >= 10 then self.chargeUpTime = 0 self.charged = true end else self.animation = self.defaultChargedAnimation end end if player.wielding and self.animation and self.animation.status == "finished" then if self.bb then self.collider:setGhost(self.bb) end player.wielding = false self.animation = self.defaultAnimation end end if self.animation then self.animation:update(dt) end local shake = 0 local current = gamestate.currentState() if self.shake and current.trackPlayer == false then shake = (math.random() * 4) - 2 camera:setPosition(self.camera.tx + shake, self.camera.ty + shake) end if self.props and self.props.update then self.props.update(self, dt, player, map) end end function Weapon:keypressed( button, player) if self.player then return end if button == 'INTERACT' then --the following invokes the constructor of the specific item's class local Item = require 'items/item' local itemNode = utils.require ('items/weapons/'..self.name) local item = Item.new(itemNode, self.quantity) local callback = function() if self.bb then self.collider:remove(self.bb) end self.containerLevel:saveRemovedNode(self) self.containerLevel:removeNode(self) self.dead = true if not player.currently_held then item:select(player) end end player.inventory:addItem(item, true, callback) end end --handles a weapon being activated function Weapon:wield() if self.props.wield then self.props.wield(self) end self.collider:setSolid(self.bb) self.player.wielding = true if self.animation then self.animation = self.wieldAnimation self.animation:gotoFrame(1) self.animation:resume() end self.player.character.state = self.action self.player.character:animation():gotoFrame(1) self.player.character:animation():resume() if self.swingAudioClip then sound.playSfx( self.swingAudioClip ) end end -- handles weapon being dropped in the real world function Weapon:drop(player) self.collider:remove(self.bb) self.bb = self.collider:addRectangle(self.position.x,self.position.y,self.dropWidth,self.dropHeight) self.bb.node = self self.collider:setSolid(self.bb) -- need to offset self.position.x = self.position.x - self.bbox_offset_x[1] if player.footprint then self:floorspace_drop(player) return end self.dropping = true self.dropped = true end function Weapon:throwProjectile( weapon ) if self.props.throwProjectile then self.props.throwProjectile(self) end end function Weapon:weaponShake( weapon ) if self.props.weaponShake then self.props.weaponShake(self) end end -- handle weapon being dropped in a floorspace function Weapon:floorspace_drop(player) self.position.y = player.footprint.y - self.dropHeight if self.bbox_offset_x then offset_x = self.bbox_offset_x[1] end self.bb:moveTo(self.position.x + offset_x + self.dropWidth / 2, self.position.y + self.dropHeight / 2) self.containerLevel:saveAddedNode(self) end function Weapon:floor_pushback() if not self.dropping then return end local offset_x = 0 self.dropping = false if self.bbox_offset_x then offset_x = self.bbox_offset_x[1] end if self.bb then self.bb:moveTo(self.position.x + offset_x + self.dropWidth / 2, self.position.y + self.dropHeight / 2) end self.velocity.y = 0 end return Weapon
id = 'V-38588' severity = 'medium' weight = 10.0 title = 'The system must not permit interactive boot.' description = 'Using interactive boot, the console user could disable auditing, firewalls, or other services, weakening system security.' fixtext = [==[To disable the ability for users to perform interactive startups, edit the file "/etc/sysconfig/init". Add or correct the line: PROMPT=no The "PROMPT" option allows the console user to perform an interactive system startup, in which it is possible to select the set of services which are started on boot.]==] checktext = [==[To check whether interactive boot is disabled, run the following command: $ grep PROMPT /etc/sysconfig/init If interactive boot is disabled, the output will show: PROMPT=no If it does not, this is a finding.]==] function test() end function fix() end
--!A cross-platform build utility based on Lua -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file io.lua -- -- define module local io = io or {} local _file = _file or {} local _filelock = _filelock or {} -- load modules local path = require("base/path") local table = require("base/table") local string = require("base/string") local todisplay = require("base/todisplay") -- save metatable and builtin functions io._file = _file io._filelock = _filelock io._stdfile = io._stdfile or io.stdfile -- new a file function _file.new(filepath, cdata, isstdfile) local file = table.inherit(_file) file._PATH = isstdfile and filepath or path.absolute(filepath) file._FILE = cdata setmetatable(file, _file) return file end -- get the file name function _file:name() if not self._NAME then self._NAME = path.filename(self:path()) end return self._NAME end -- get the file path function _file:path() return self._PATH end -- close file function _file:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- close file ok, errors = io.file_close(self:cdata()) if ok then self._FILE = nil end return ok, errors end -- tostring(file) function _file:__tostring() local str = self:path() if #str > 16 then str = ".." .. str:sub(#str - 16, #str) end return "<file: " .. str .. ">" end -- todisplay(file) function _file:__todisplay() local size = _file.size(self) local filepath = _file.path(self) if not size then return string.format("file${reset} %s", todisplay(filepath)) end local unit = "B" if size >= 1000 then size = size / 1024 unit = "KiB" end if size >= 1000 then size = size / 1024 unit = "MiB" end if size >= 1000 then size = size / 1024 unit = "GiB" end return string.format("file${reset}(${color.dump.number}%.3f%s${reset}) %s", size, unit, todisplay(filepath)) end -- gc(file) function _file:__gc() if self:cdata() and io.file_close(self:cdata()) then -- remove ref to notify gc that it should be freed self._FILE = nil end end -- get file length function _file:__len() return _file.size(self) end -- get cdata function _file:cdata() return self._FILE end -- get file rawfd function _file:rawfd() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get file rawfd local result, errors = io.file_rawfd(self:cdata()) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- get file size function _file:size() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- get file size local result, errors = io.file_size(self:cdata()) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- read data from file -- -- @param fmt the reading format -- @param opt the options -- - continuation (concat string with the given continuation characters) -- function _file:read(fmt, opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- read file opt = opt or {} local result, errors = io.file_read(self:cdata(), fmt, opt.continuation) if errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- write data to file function _file:write(...) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- write file ok, errors = io.file_write(self:cdata(), ...) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- seek offset at file function _file:seek(whence, offset) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- seek file local result, errors = io.file_seek(self:cdata(), whence, offset) if not result and errors then errors = string.format("%s: %s", self, errors) end return result, errors end -- flush data to file function _file:flush() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- flush file ok, errors = io.file_flush(self:cdata()) if not ok and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- this file is a tty? function _file:isatty() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return nil, errors end -- is a tty? ok, errors = io.file_isatty(self:cdata()) if ok == nil and errors then errors = string.format("%s: %s", self, errors) end return ok, errors end -- ensure the file is opened function _file:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- read all lines from file function _file:lines(opt) opt = opt or {} return function() local l = _file.read(self, "l", opt) if not l and opt.close_on_finished then _file.close(self) end return l end end -- print file function _file:print(...) return _file.write(self, string.format(...), "\n") end -- printf file function _file:printf(...) return _file.write(self, string.format(...)) end -- save object function _file:save(object, opt) local str, errors = string.serialize(object, opt) if errors then return false, errors else return _file.write(self, str) end end -- load object function _file:load() local data, err = _file.read(self, "*all") if err then return nil, err end if data and type(data) == "string" then return data:deserialize() end end -- new an filelock function _filelock.new(lockpath, lock) local filelock = table.inherit(_filelock) filelock._PATH = path.absolute(lockpath) filelock._LOCK = lock filelock._LOCKED_NUM = 0 setmetatable(filelock, _filelock) return filelock end -- get the filelock name function _filelock:name() if not self._NAME then self._NAME = path.filename(self:path()) end return self._NAME end -- get the filelock path function _filelock:path() return self._PATH end -- get the cdata function _filelock:cdata() return self._LOCK end -- is locked? function _filelock:islocked() return self._LOCKED_NUM > 0 end -- lock file -- -- @param opt the argument option, {shared = true} -- -- @return ok, errors -- function _filelock:lock(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- lock it if self._LOCKED_NUM > 0 or io.filelock_lock(self:cdata(), opt) then self._LOCKED_NUM = self._LOCKED_NUM + 1 return true else return false, string.format("%s: lock failed!", self) end end -- try to lock file -- -- @param opt the argument option, {shared = true} -- -- @return ok, errors -- function _filelock:trylock(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- try lock it if self._LOCKED_NUM > 0 or io.filelock_trylock(self:cdata(), opt) then self._LOCKED_NUM = self._LOCKED_NUM + 1 return true else return false, string.format("%s: trylock failed!", self) end end -- unlock file function _filelock:unlock(opt) -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- unlock it if self._LOCKED_NUM > 1 or (self._LOCKED_NUM > 0 and io.filelock_unlock(self:cdata())) then if self._LOCKED_NUM > 0 then self._LOCKED_NUM = self._LOCKED_NUM - 1 else self._LOCKED_NUM = 0 end return true else return false, string.format("%s: unlock failed!", self) end end -- close filelock function _filelock:close() -- ensure opened local ok, errors = self:_ensure_opened() if not ok then return false, errors end -- close it ok = io.filelock_close(self:cdata()) if ok then self._LOCK = nil self._LOCKED_NUM = 0 end return ok end -- ensure the file is opened function _filelock:_ensure_opened() if not self:cdata() then return false, string.format("%s: has been closed!", self) end return true end -- tostring(filelock) function _filelock:__tostring() local str = _filelock.path(self) if #str > 16 then str = ".." .. str:sub(#str - 16, #str) end return "<filelock: " .. str .. ">" end -- todisplay(filelock) function _filelock:__todisplay() local str = _filelock.path(self) return "filelock${reset} " .. todisplay(str) end -- gc(filelock) function _filelock:__gc() if self:cdata() and io.filelock_close(self:cdata()) then self._LOCK = nil self._LOCKED_NUM = 0 end end -- read all lines from file function io.lines(filepath, opt) -- close on finished opt = opt or {} if opt.close_on_finished == nil then opt.close_on_finished = true end -- open file local file = io.open(filepath, "r", opt) if not file then return function() return nil end end return file:lines(opt) end -- read all data from file function io.readfile(filepath, opt) opt = opt or {} -- open file local file, errors = io.open(filepath, "r", opt) if not file then return nil, errors end -- read all local data, err = file:read("*all", opt) -- exit file file:close() -- ok? return data, err end function io.read(fmt, opt) return io.stdin:read(fmt, opt) end function io.write(...) return io.stdout:write(...) end function io.print(...) return io.stdout:print(...) end function io.printf(...) return io.stdout:printf(...) end function io.flush() return io.stdout:flush() end -- write data to file function io.writefile(filepath, data, opt) -- init option opt = opt or {} -- open file local file, errors = io.open(filepath, "w", opt) if not file then return false, errors end -- write all file:write(data) -- exit file file:close() -- ok? return true end -- isatty function io.isatty(file) file = file or io.stdout return file:isatty() end -- get std file, /dev/stdin, /dev/stdout, /dev/stderr function io.stdfile(filepath) local file = nil if filepath == "/dev/stdin" then file = io._stdfile(1) elseif filepath == "/dev/stdout" then file = io._stdfile(2) elseif filepath == "/dev/stderr" then file = io._stdfile(3) end if file then return _file.new(filepath, file, true) else return nil, string.format("failed to get std file: %s", filepath) end end -- open file -- -- @param filepath the file path -- @param mode the open mode, e.g. 'r', 'rb', 'w+', 'a+', .. -- @param opt the options -- - encoding, e.g. utf8, utf16, utf16le, utf16be .. -- function io.open(filepath, mode, opt) -- check assert(filepath) -- init option and mode opt = opt or {} mode = mode or "r" -- open it local file = io.file_open(filepath, mode .. (opt.encoding or "")) if file then return _file.new(filepath, file) else return nil, string.format("cannot open file: %s, %s", filepath, os.strerror()) end end -- open a filelock function io.openlock(filepath) -- check assert(filepath) -- open it local lock = io.filelock_open(filepath) if lock then return _filelock.new(filepath, lock) else return nil, string.format("cannot open lock: %s, %s", filepath, os.strerror()) end end -- close file function io.close(file) return (file or io.stdout):close() end -- save object the the given filepath function io.save(filepath, object, opt) -- check assert(filepath and object) -- init option opt = opt or {} -- open the file local file, err = io.open(filepath, "wb", opt) if err then -- error return false, err end -- save object to file local ok, errors = file:save(object, opt) -- close file file:close() if not ok then -- error return false, string.format("save %s failed, %s!", filepath, errors) end -- ok return true end -- load object from the given file function io.load(filepath, opt) -- check assert(filepath) -- init option opt = opt or {} -- open the file local file, err = io.open(filepath, "rb", opt) if err then -- error return nil, err end -- load object local result, errors = file:load() -- close file file:close() -- ok? return result, errors end -- gsub the given file and return replaced data function io.gsub(filepath, pattern, replace, opt) -- init option opt = opt or {} -- read all data from file local data, errors = io.readfile(filepath, opt) if not data then return nil, 0, errors end -- replace it local count = 0 if type(data) == "string" then data, count = data:gsub(pattern, replace) else return nil, 0, string.format("data is not string!") end -- replace ok? if count ~= 0 then -- write all data to file local ok, errors = io.writefile(filepath, data, opt) if not ok then return nil, 0, errors end end -- ok return data, count end -- cat the given file function io.cat(filepath, linecount, opt) -- init option opt = opt or {} -- open file local file = io.open(filepath, "r", opt) if file then -- show file local count = 1 for line in file:lines(opt) do -- show line io.write(line, "\n") -- end? if linecount and count >= linecount then break end -- update the line count count = count + 1 end -- exit file file:close() end end -- tail the given file function io.tail(filepath, linecount, opt) -- init option opt = opt or {} -- all? if linecount < 0 then return io.cat(filepath, opt) end -- open file local file = io.open(filepath, "r", opt) if file then -- read lines local lines = {} for line in file:lines(opt) do table.insert(lines, line) end -- tail lines local tails = {} if #lines ~= 0 then local count = 1 for index = #lines, 1, -1 do -- show line table.insert(tails, lines[index]) -- end? if linecount and count >= linecount then break end -- update the line count count = count + 1 end end -- show tails if #tails ~= 0 then for index = #tails, 1, -1 do -- show tail io.print(tails[index]) end end -- exit file file:close() end end -- lazy loading stdfile io.stdin = nil io.stdout = nil io.stderr = nil setmetatable(io, { __index = function (tbl, key) local val = rawget(tbl, key) if val == nil and (key == "stdin" or key == "stdout" or key == "stderr") then val = io.stdfile("/dev/" .. key) if val ~= nil then rawset(tbl, key, val) end end return val end}) -- return module return io
-- --------------------------------------------- -- ts.lua 2017/08/09 -- Copyright (c) 2017 Toshi Nagata -- released under the MIT open source license. -- --------------------------------------------- local ffi = require "ffi" local bit = require "bit" local util = require "util" local ctl = require "ctl" libts = ffi.load("libts-0.0.so.0") ffi.cdef[[ struct tsdev; struct tsdev *ts_open(const char *dev_name, int nonblock); struct ts_sample { int x, y; unsigned int pressure; struct timeval tv; }; int ts_read(struct tsdev *dev, struct ts_sample *samp, int nr); int ts_config(struct tsdev *ts); int ts_close(struct tsdev *ts); ]] local ts = {} function ts.init() local name = ffi.new("char[256]") local EVIOCGNAME = function (len) return ctl.IOR(0x45, 0x06, len) end -- 0x45 = 'E' local devname for i = 0, 9 do local dname = string.format("/dev/input/event%d", i) local fd = ffi.C.open(dname, ctl.O_RDONLY) if fd >= 0 then if ffi.C.ioctl(fd, EVIOCGNAME(256), name) >= 0 then if string.match(ffi.string(name), "[Tt]ouchscreen") then ffi.C.close(fd) devname = dname break end end ffi.C.close(fd) end end if devname == nil then return false end local tsdev = libts.ts_open(devname, 1) if tsdev == nil then return false end if libts.ts_config(tsdev) ~= 0 then libts.ts_close(tsdev) return false end ts.dev = tsdev return true end function ts.read() if ts.dev == nil then if not ts.init() then error "Cannot setup touchscreen device" end end local samp = ffi.new("struct ts_sample[1]") if libts.ts_read(ts.dev, samp, 1) == 1 then return samp[0].x, samp[0].y, samp[0].pressure else return nil end end return ts
structure.library_project("coconut-pulp-primitive")
local fzy = require("ctrlspace.fzy_lua") local function ctrlspace_filter(candidates, query, max) local results = {} for _, n in ipairs(candidates) do if fzy.has_match(query, n.text) then n.score = fzy.score(query, n.text) table.insert(results, n) end end table.sort(results, function(x, y) if x.score < y.score then return true elseif x.score > y.score then return false else return x.index < y.index end end) local start = 1 if max < #results then start = #results - max end local top = {} for i=start, #results do local r = results[i] r.positions = fzy.positions(query, r.text) table.insert(top, r) end return top end local fn = vim.fn local api = vim.api local files = {} local buffers = { api = {} } local bookmarks = {} local tabs = {} local drawer = {} local search = {} local ui = {} local util = {} local db = {} local roots = {} local modes = { all = {} ; slots = {} } local workspaces = {} local M = { util = util, modes = modes, files = files, buffers = buffers, tabs = tabs, drawer = drawer, search = search, bookmarks = bookmarks, ui = ui, db = db, roots = roots, workspaces = workspaces, } local files_cache = nil function files.clear () files = nil end function modes.slot(name) modes.slots.name = nil return name end function modes.new(name, slot, data) local instance = { name = name, data = data, slot = slot.name, } if modes.all[name] then error("mode " .. name .. " already exists") end modes.all[name] = instance end function modes.init() local submode = function(name, data) local slot = modes.slot(name) return modes.new(name, slot, data) end submode("NextTab", {}) submode("Search", { Letters = {}, NewSearchPerformed = 0, Restored = 0, HistoryIndex = -1 }) submode("Help", {}) submode("Nop", {}) local slot = modes.slot("list") modes.new("Buffer", slot, { SubMode = "single" }) modes.new("File", slot, {}) modes.new("Tab", slot, {}) modes.new("Workspace", slot, { Active = { Name = "", Digest = "", Root = "" }, LastActive = "", LastBrowsed = 0 }) modes.new("Bookmark", slot, { Active = {} }) end function modes.enable(mode) modes.slots[mode.slot] = mode end function modes.disable(slot) modes.slots[slot] = nil end local item = {} function item.create(index, text, indicators) if index == 0 then error("index must not be 0") end return { index = index, text = text, indicators = indicators, } end local function buffer_name(bufnr) local name = fn.fnamemodify(fn.bufname(bufnr), ":.") if name == "" then return "[" .. bufnr .. "*No Name]" else return name end end -- introduce customization for this eventually local function glob_cmd() return "rg --color=never --files --sort path" end function files.collect () if files_cache then return files_cache end local output = fn["ctrlspace#util#system"](glob_cmd()) local res = {} local i = 1 for s in string.gmatch(output, "[^\r\n]+") do local text = fn.fnamemodify(s, ":.") local m = item.create(i, text, "") table.insert(res, m) i = i + 1 end files_cache = res return files_cache end local getbufvar = fn.getbufvar -- TODO use this helper consistently local function exe(cmds) for _, cmd in ipairs(cmds) do vim.cmd('silent! ' .. cmd) end end function ui.input(prompt, default, compl) local config = fn["ctrlspace#context#Configuration"]() prompt = config.Symbols.CS .. " " .. prompt fn.inputsave() local answer if compl then answer = fn.input(prompt, default, compl) elseif default then answer = fn.input(prompt, default) else answer = fn.input(prompt) end fn.inputrestore() exe({"redraw!"}) return answer end function ui.confirmed(msg) return ui.input(msg .. " (yN): ") == "y" end local function plugin_buffer(buf) return getbufvar(buf, "&ft") == "ctrlspace" end local function managed_buf(buf) return fn.buflisted(buf) and not plugin_buffer(buf) end function files.load_file_or_buffer(file) local listed = fn.buflisted(file) == 1 if listed then exe({"b " .. fn.bufnr(file)}) else exe({"e " .. fn.fnameescape(file)}) end end function files.load_file(commands) local file = drawer.selected_file_path() file = fn.fnamemodify(file, ":p") drawer.kill(true) exe(commands) M.files.load_file_or_buffer(file) end local function assert_drawer_off() local pbuf = drawer.buffer() if pbuf ~= -1 then error("plugin buffer exists\n" .. debug.traceback()) end end local function is_ctrlspace_buffer() return vim.bo.filetype == "ctrlspace" end local function assert_drawer_on() if not is_ctrlspace_buffer() then error("the current buffer isn't ctrlspace\n" .. debug.traceback()) end end function files.edit() assert_drawer_on() local path = fn.fnamemodify(drawer.selected_file_path(), ":p:h") local file = ui.input("Edit a new file: ", path .. '/', "file") if not file or string.len(file) == 0 then return end file = fn.expand(file) file = fn.fnamemodify(file, ":p") drawer.kill(true) exe({"e " .. fn.fnameescape(file)}) end function files.edit_dir() assert_drawer_on() local path = fn.fnamemodify(drawer.selected_file_path(), ":p:h") drawer.kill(true) exe({"e " .. fn.fnameescape(path)}) end function buffers.add_current() local current = fn.bufnr('%') if not managed_buf(current) then return end vim.b.CtrlSpaceJumpCounter = fn["ctrlspace#jumps#IncrementJumpCounter"]() if not vim.t.CtrlSpaceList then vim.t.CtrlSpaceList = {} end local tmp = vim.t.CtrlSpaceList tmp[tostring(current)] = true vim.t.CtrlSpaceList = tmp end -- TODO sort local function all_buffers() local res = {} for _, buf in pairs(api.nvim_list_bufs()) do if managed_buf(buf) then res[buf] = true end end return res end local function buffer_modified(bufnr) return getbufvar(bufnr, "&modified") == 1 end function buffers.unsaved() local res = {} for b, _ in ipairs(all_buffers()) do if buffer_modified(b) and managed_buf(b) then table.insert(res, b) end end return res end local function raw_buffers_in_tab(tabnr) return fn.gettabvar(tabnr, "CtrlSpaceList", {}) end local function buffers_in_tab(tabnr) local res = {} for key, _ in pairs(raw_buffers_in_tab(tabnr)) do res[tonumber(key)] = true end return res end -- TODO this should exist in the tabs module -- TODO sort buffers.in_tab = function (tabnr) local res = {} local t = raw_buffers_in_tab(tabnr) for k, _ in pairs(t) do table.insert(res, tonumber(k)) end return res end -- local function find_buffer_visible_in_tabs(bufnr) -- local res = {} -- for tabnr=1,fn.tabpagenr("$") do -- local tab_buffers = fn.tabpagebuflist(tabnr) -- for _, b in ipairs(tab_buffers) do -- if b == bufnr then -- res[tabnr] = true -- end -- end -- end -- return res -- end -- returns a table keyed by the tabs containing the buffer. the values of the -- table are a boolean that tells if the buffer is actualyl being displayed local function find_buffer_in_tabs(bufnr) local res = {} for tabnr=1,fn.tabpagenr("$") do local in_tab_list = buffers_in_tab(tabnr)[bufnr] if in_tab_list then local visible_buffers = fn.tabpagebuflist(tabnr) local visible = false for _, b in ipairs(visible_buffers) do if b == bufnr then visible = true end end res[tabnr] = visible end end return res end function buffers.remove(bufnr) bufnr = tonumber(bufnr) local in_tabs = find_buffer_in_tabs(bufnr) for tabnr, _ in ipairs(in_tabs) do tabs.remove_buffers(tabnr, {bufnr}) end end -- you must restore the view after calling this function local function forget_buffer_in_tab(tabnr, bufnr) assert_drawer_off() local curtab = fn.tabpagenr() if curtab ~= tabnr then exe({"tabn " .. tabnr}) end local winnr = fn.bufwinnr(bufnr) local new_buf = nil while winnr ~= -1 do exe({winnr .. "wincmd w"}) -- this ensures that we create at most one new buffer per forget local next_buf = new_buf or tabs.next_buf(tabnr, bufnr) if next_buf then exe({"b! " .. next_buf}) else exe({"enew"}) new_buf = fn.bufnr() end winnr = fn.bufwinnr(bufnr) end tabs.remove_buffers(tabnr, {bufnr}) end local function forget_buffer_in_all_tabs(bufnr) local curtab = fn.tabpagenr() local in_tabs = find_buffer_in_tabs(bufnr) for t, _ in pairs(in_tabs) do forget_buffer_in_tab(t, bufnr) end exe({"tabn " .. curtab}) end local function with_restore_drawer(f) assert_drawer_on() local curln = fn.line(".") drawer.kill(false) f() assert_drawer_off() drawer.restore() drawer.move_selection_and_remember(curln) end local function with_maybe_restore_drawer(f) if is_ctrlspace_buffer() then with_restore_drawer(f) else f() end end function files.load_many_files(pre, post) assert_drawer_on() local file = fn.fnamemodify(drawer.selected_file_path(), ":p") with_restore_drawer(function () drawer.go_start_window() exe(pre) M.files.load_file_or_buffer(file) exe({"normal! zb"}) exe(post) end) end local function delete_buffer(bufnr) local modified = buffer_modified(bufnr) if modified and not ui.confirmed( "The buffer contains unsaved changes. Proceed anyway?") then return end with_restore_drawer(function () forget_buffer_in_all_tabs(bufnr) -- why aren't we using wipeout like elsewhere? exe({"bdelete! " .. bufnr}) end) end function buffers.delete () local bufnr = drawer.last_selected_index() delete_buffer(bufnr) end local function detach_buffer(bufnr) local modified = buffer_modified(bufnr) if modified and not ui.confirmed( "The buffer contains unsaved changes. Proceed anyway?") then return end with_restore_drawer(function () local curtab = fn.tabpagenr() forget_buffer_in_tab(curtab, bufnr) end) end function buffers.detach() local bufnr = drawer.last_selected_index() detach_buffer(bufnr) end function buffers.close_buffer() local bufnr = drawer.last_selected_index() local found_tabs = tabs.buffer_present_count(bufnr) if found_tabs > 1 then buffers.detach() else buffers.delete() end end function buffers.api.in_tab(tabnr) local res = {} for k, _ in pairs(raw_buffers_in_tab(tabnr)) do res[tostring(k)] = buffer_name(k) end return res end function buffers.in_all_tabs () local res = {} for tabnr=1,fn.tabpagenr("$") do for _, b in ipairs(buffers.in_tab(tabnr)) do res[b] = true end end return res end function buffers.all () local res = {} for buf, _ in pairs(all_buffers()) do table.insert(res, buf) end return res end local function foreign_buffers() local bufs = {} for _, i in ipairs(buffers.all()) do bufs[i] = true end for tabnr=1,fn.tabpagenr("$") do for _, b in ipairs(buffers.in_tab(tabnr)) do bufs[b] = nil end end return bufs end function buffers.foreign () local bufs = foreign_buffers() local res = {} for i, _ in pairs(bufs) do table.insert(res, i) end return res end local function delete_buffers (bufs) for b, _ in pairs(bufs) do vim.cmd('exe "bwipeout" ' .. b) end tabs.forget_buffers(bufs) end function buffers.visible () local res = {} for tabnr=1,fn.tabpagenr("$") do for _, b in ipairs(fn.tabpagebuflist(tabnr)) do if managed_buf(b) then res[b] = true end end end return res end function buffers.unnamed () local res = {} for _, b in ipairs(buffers.all()) do if managed_buf(b) and fn.bufexists(b) and (not getbufvar(b, "&buftype") or fn.filereadable(fn.bufname(b))) then res[b] = true end end return res end buffers.delete_hidden_noname = function () with_maybe_restore_drawer(function () local bufs = all_buffers() for u, _ in pairs(buffers.unnamed()) do bufs[u] = nil end for u, _ in pairs(buffers.visible()) do bufs[u] = nil end delete_buffers(bufs) end) end buffers.delete_foreign = function () with_maybe_restore_drawer(function () delete_buffers(foreign_buffers()) end) end tabs.buffer_present_count = function (buf) local res = 0 local b = tostring(buf) for tabnr=1,fn.tabpagenr("$") do local btabs = raw_buffers_in_tab(tabnr) if btabs[b] then res = res + 1 end end return res end local function number_of_buffers_in_tab(tabnr) local bufs = 0 for _, _ in pairs(buffers_in_tab(tabnr)) do bufs = bufs + 1 end return bufs end function tabs.next_buf(tabnr, buf) local bufs = buffers_in_tab(tabnr) local next = nil local prev = nil for candidate, _ in pairs(bufs) do if candidate > buf then if next then if candidate - buf < next - buf then next = candidate end else next = candidate end elseif candidate < buf then if prev then if candidate < prev then prev = candidate end else prev = candidate end end end return (next or prev) end function tabs.buffers_number(tabnr) local config = fn["ctrlspace#context#Configuration"]() local count = number_of_buffers_in_tab(tabnr) local superscripts = {"โฐ", "ยน", "ยฒ", "ยณ", "โด", "โต", "โถ", "โท", "โธ", "โน"} if config.UseUnicode == 1 then count = tostring(count) local res = {} for i = 1, #count do local char = tonumber(string.sub(count, i, i)) local super_char = superscripts[char - 1] table.insert(res, super_char) end return table.concat(res, "") else return tostring(count) end end function tabs.modified(tabnr) for b, _ in pairs(buffers_in_tab(tabnr)) do if buffer_modified(b) then return true end end return false end function tabs.remove_buffers(tabnr, bufs) local bufs_in_tab = raw_buffers_in_tab(tabnr) local modified = false for _, key_int in ipairs(bufs) do local key = tostring(key_int) if bufs_in_tab[key] then modified = true bufs_in_tab[key] = nil end end if modified then fn.settabvar(tabnr, "CtrlSpaceList", bufs_in_tab) end end tabs.forget_buffers = function (bufs) for tabnr=1,fn.tabpagenr("$") do tabs.remove_buffers(tabnr, bufs) end end tabs.add_buffer = function (tabnr, buf) local btabs = raw_buffers_in_tab(tabnr) local key = tostring(buf) if btabs[key] then return end btabs[key] = true fn.settabvar(tabnr, "CtrlSpaceList", btabs) end function drawer.buffer() for _, buf in pairs(api.nvim_list_bufs()) do if plugin_buffer(buf) then return buf end end return -1 end function buffers.load(pre) local nr = drawer.last_selected_index() drawer.kill(true) exe(pre) exe({"b " .. nr}) end function buffers.load_keep(pre, post) local nr = drawer.last_selected_index() with_restore_drawer(function () -- fn["ctrlspace#window#GoToStartWindow"]() exe(pre) exe({"b " .. nr}) vim.cmd("normal! zb") exe(post) end) end function drawer.go_to_buffer_or_file(direction) local start = fn.tabpagenr() local limit = fn.tabpagenr("$") local target_tab, target_buffer local modes = fn["ctrlspace#modes#Modes"]() local found if modes.File.Enabled == 1 then local file = drawer.selected_file_path() file = fn.fnamemodify(file, ":p") found = function(bufnr) return file == fn.fnamemodify(fn.bufname(bufnr), ":p") end elseif modes.Buffer.Enabled == 1 then local nr = drawer.last_selected_index() found = function(bufnr) return bufnr == nr end end for i=0, limit-1 do local j = start + (i * direction) if j > limit then j = j - limit end if j <= 0 then j = limit + j end for bufnr, _ in pairs(buffers_in_tab(j)) do if found(bufnr) then target_tab = j target_buffer = bufnr goto found end end end ::found:: if target_tab and target_buffer then with_restore_drawer(function () exe({"normal! " .. target_tab .. "gt"}) -- TODO restore cursor to the selected buffer end) end end local function help_filler() return string.rep(" ", vim.o.columns) .. "\n" end local function bookmark_items() local config = fn["ctrlspace#context#Configuration"]() local bookmarks = fn['ctrlspace#bookmarks#Bookmarks']() local active = fn['ctrlspace#bookmarks#FindActiveBookmark']() local res = {} for i, bm in ipairs(bookmarks) do local indicators = "" if active and bm.Directory == active.Directory then indicators = config.Symbols.IA end table.insert(res, item.create(i, bm.Name, indicators)) end return res end local function workspace_items (clv) local workspaces = fn["ctrlspace#workspaces#Workspaces"]() local active = fn["ctrlspace#workspaces#ActiveWorkspace"]() local config = fn["ctrlspace#context#Configuration"]() local res = {} for i, ws in ipairs(workspaces) do local indicators = "" if active and ws == active.Name and active.Status ~= 0 then if active.Status == 2 then indicators = indicators .. config.Symbols.IM end elseif ws == clv.Data.LastActive then indicators = indicators .. config.Symbols.IV end table.insert(item.create(i, ws, indicators)) end return res end local function tab_items() local config = fn["ctrlspace#context#Configuration"]() local current_tab = fn.tabpagenr() local res = {} for tabnr=1,fn.tabpagenr("$") do local indicators = "" local tab_buffer_number = fn["ctrlspace#api#TabBuffersNumber"](tabnr) local title = fn["ctrlspace#api#TabTitle"](tabnr) if fn["ctrlspace#api#TabModified"](tabnr) ~= 1 then indicators = indicators .. config.Symbols.IM end if tabnr == current_tab then indicators = indicators .. config.Symbols.IA end local name = tabnr .. " " .. tab_buffer_number .. " " .. title table.insert(res, item.create(tabnr, name, indicators)) end return res end local function buffer_items(clv) local res = {} local bufs local submode = clv.Data.SubMode local config = fn["ctrlspace#context#Configuration"]() if submode == "single" then bufs = buffers_in_tab(fn.tabpagenr()) elseif submode == "all" then bufs = all_buffers() elseif submode == "visible" then bufs = {} for buf, _ in raw_buffers_in_tab(fn.tabeagenr()) do if fn.bufwinnr(buf) ~= -1 then bufs[buf] = true end end else error("invalid mode " .. submode) end for bufnr, _ in pairs(bufs) do local name = buffer_name(bufnr) local modified = buffer_modified(bufnr) local winnr = fn.bufwinnr(bufnr) local indicators = "" if modified then indicators = indicators .. config.Symbols.IM end if winnr == vim.t.CtrlSpaceStartWindow then indicators = indicators .. config.Symbols.IA elseif winnr ~= -1 then indicators = indicators .. config.Symbols.IV end table.insert(res, item.create(bufnr, name, indicators)) end return res end local function content_source() local clv = fn["ctrlspace#modes#CurrentListView"]() if clv.Name == "Buffer" then return buffer_items(clv) elseif clv.Name == "File" then -- TODO why doesn't this work? -- return M.files.collect() return M.files.collect() elseif clv.Name == "Tab" then return tab_items() elseif clv.Name == "Workspace" then return workspace_items(clv) elseif clv.Name == "Bookmark" then return bookmark_items() else error("unknown list view: " .. clv.Name) end end local function render_candidates(items) local config = fn["ctrlspace#context#Configuration"]() local modes = fn["ctrlspace#modes#Modes"]() local sizes = fn["ctrlspace#context#SymbolSizes"]() local item_space if modes.File.Enabled == 1 then item_space = 5 elseif modes.Bookmark.Enabled == 1 then item_space = 5 + sizes.IAV else item_space = 5 + sizes.IAV + sizes.IM end local res = {} local columns = vim.o.columns for _, i in ipairs(items) do local line = i.text local len = string.len(line) if len + item_space > columns then line = config.Symbols.Dots .. string.sub(line, line - columns + item_space + sizes.Dots) end if i.indicators ~= "" then line = line .. " " .. i.indicators end line = " " .. line table.insert(res, line) end return res end local search_state = { query = nil, activated = false, } function drawer.content () local absolute_max = 500 local candidates = content_source() local modes = fn["ctrlspace#modes#Modes"]() local query = search_state.query or "" if query == "" then if #candidates > absolute_max then candidates = { unpack(candidates, 1, absolute_max) } end else local max if search_state.activated then max = drawer.max_height() else max = absolute_max end candidates = ctrlspace_filter(candidates, query, max) end return candidates end local function save_tab_config() vim.t.CtrlSpaceStartWindow = fn.winnr() vim.t.CtrlSpaceWinrestcmd = fn.winrestcmd() vim.t.CtrlSpaceActivebuf = fn.bufnr("") end function drawer.show() save_tab_config() exe({ "noautocmd botright pedit CtrlSpace", "noautocmd wincmd P" }) end local function drawer_display(items) vim.cmd('setlocal modifiable') local buf = drawer.buffer() if #items > 0 then local line = 0 local text = render_candidates(items) api.nvim_buf_set_lines(buf, 0, -1, true, text) for _, i in ipairs(items) do if i.positions then for _, hl in ipairs(i.positions) do api.nvim_buf_add_highlight(0, -1, "CtrlSpaceSearch", line, hl + 1, hl + 2) end end line = line + 1 end else api.nvim_buf_set_lines(buf, 0, -1, true, {" List empty"}) vim.cmd("normal! GkJ") vim.cmd("normal! 0") -- vim.cmd([[ -- let modes = ctrlspace#modes#Modes() -- call modes.Nop.Enable() -- ]]) end vim.cmd('setlocal nomodifiable') end drawer.insert_content = function () local config = fn["ctrlspace#context#Configuration"]() local modes = fn["ctrlspace#modes#Modes"]() exe({'resize ' .. config.Height}) if modes.Help.Enabled == 1 then fn["ctrlspace#help#DisplayHelp"](help_filler()) fn["ctrlspace#util#SetStatusline"]() return end local items = drawer.content() -- for backwards compat vim.b.items = items vim.b.size = #items if #items > config.Height then local max_height = drawer.max_height() local size if #items < max_height then size = #items else size = max_height end exe({'resize ' .. size}) end drawer_display(items) fn["ctrlspace#util#SetStatusline"]() fn["ctrlspace#window#setActiveLine"]() vim.cmd("normal! zb") end function drawer.refresh () local last_line = fn.line("$") vim.cmd('setlocal modifiable') api.nvim_buf_set_lines(0, 0, last_line, 0, {}) vim.cmd('setlocal nomodifiable') drawer.insert_content() end function drawer.setup_buffer () vim.cmd([[ setlocal noswapfile setlocal buftype=nofile setlocal bufhidden=delete setlocal nobuflisted setlocal nomodifiable setlocal nowrap setlocal nonumber setlocal norelativenumber setlocal nocursorcolumn setlocal nocursorline setlocal nospell setlocal nolist setlocal cc= setlocal filetype=ctrlspace setlocal foldmethod=manual augroup CtrlSpaceLeave au! au BufLeave <buffer> call ctrlspace#window#Kill(1) augroup END ]]) local root = fn["ctrlspace#roots#CurrentProjectRoot"]() if root then exe({"lcd " .. fn.fnameescape(root)}) end local config = fn["ctrlspace#context#Configuration"]() if not config.UseMouseAndArrowsInTerm and not fn.has("gui_running") then vim.cmd([[ " Block unnecessary escape sequences! noremap <silent><buffer><esc>[ :call ctrlspace#keys#MarkKeyEscSequence()<CR> let b:mouseSave = &mouse set mouse= ]]) end for _, k in ipairs(fn["ctrlspace#keys#KeyNames"]()) do local key = k if string.len(k) > 1 then key = "<" .. k .. ">" end if k == '"' then k = '\\' .. k end exe( {"nnoremap <silent><buffer> " .. key .. ' :call ctrlspace#keys#Keypressed("' .. k .. '")<CR>'}) end end function drawer.max_height() local config = fn["ctrlspace#context#Configuration"]() local config_max = config.MaxHeight if config_max <= 0 then config_max = nil end return config_max or vim.o.lines / 3 end function drawer.go_to_window() local nr = drawer.last_selected_index() local win = fn.bufwinnr(nr) if win == -1 then return false end exe({win .. "wincmd w"}) drawer.kill(true) return true end function drawer.restore() exe({"pclose"}) assert_drawer_off() drawer.show() drawer.setup_buffer() drawer.insert_content() end local function reset_window() roots.try_find() vim.cmd([[ call s:modes.Help.Disable() call s:modes.Nop.Disable() call s:modes.Search.Disable() call s:modes.NextTab.Disable() call s:modes.Buffer.Enable() call s:modes.Buffer.SetData("SubMode", "single") call s:modes.Search.SetData("NewSearchPerformed", 0) call s:modes.Search.SetData("Restored", 0) call s:modes.Search.SetData("Letters", []) call s:modes.Search.SetData("HistoryIndex", -1) call s:modes.Workspace.SetData("LastBrowsed", 0) call s:modes.Bookmark.SetData("Active", ctrlspace#bookmarks#FindActiveBookmark()) call s:modes.Search.RemoveData("LastSearchedDirectory") set guicursor+=n:block-CtrlSpaceSelected-blinkon0 call ctrlspace#util#HandleVimSettings("start") ]]) end function drawer.toggle(internal) if not internal then reset_window() end local pbuf = drawer.buffer() if pbuf ~= -1 then if fn.winnr(pbuf) == -1 then drawer.kill(false) if not internal then save_tab_config() end end elseif not internal then exe({"pclose"}) save_tab_config() end drawer.show() drawer.setup_buffer() drawer.insert_content() end function drawer.last_selected_index() local pbuf = drawer.buffer() if pbuf == -1 then error("ctrlspace plugin buffer does not exist") end local items = api.nvim_buf_get_var(pbuf, "items") if not items then error("no items loaded") end local idx if fn.bufnr() == pbuf then idx = fn.line(".") else idx = fn.getbufinfo(pbuf)[0].lnum end return items[idx].index end function drawer.go_start_window() exe({vim.t.CtrlSpaceStartWindow .. "wincmd w"}) if fn.winrestcmd() == vim.t.CtrlSpaceWinrestcmd then return end exe({vim.t.CtrlSpaceWinrestcmd}) if fn.winrestcmd() ~= vim.t.CtrlSpaceWinrestcmd then exe("wincmd =") end end function tabs.set_label(tabnr, label, auto) api.nvim_tabpage_set_var(tabnr, "CtrlSpaceLabel", label) api.nvim_tabpage_set_var(tabnr, "CtrlSpaceAutotab", auto) end function tabs.remove_label(tabnr) tabs.set_label(tabnr, "", 0) return true end function tabs.rename(tabnr) assert_drawer_on() local old_name = fn.gettabvar(tabnr, "CtrlSpaceLabel", nil) if not old_name or old_name == vim.NIL then old_name = "" end local new_label = ui.input("Label for tab " .. tabnr .. ": ", old_name, nil) if not new_label or new_label == "" then return false end tabs.set_label(tabnr, new_label, 0) return true end function tabs.ask_rename_selected() assert_drawer_on() local l = fn.line(".") local tabnr = drawer.last_selected_index() if not tabs.rename(tabnr) then return end drawer.refresh() drawer.move_selection_and_remember(l) end function tabs.remove_label_selected() assert_drawer_on() local l = fn.line(".") local tabnr = drawer.last_selected_index() tabs.remove_label(tabnr) drawer.refresh() drawer.move_selection_and_remember(l) end function tabs.new_label() assert_drawer_on() local l = fn.line(".") local tabnr = drawer.last_selected_index() local old_name = fn.gettabvar(tabnr, "CtrlSpaceLabel", nil) if not old_name or old_name == vim.NIL then old_name = "" end local new_label = ui.input("Label for tab " .. tabnr .. ": ", old_name, nil) if not new_label or new_label == "" then return end tabs.set_label(tabnr, new_label, 0) drawer.refresh() drawer.move_selection_and_remember(l) end function tabs.close() -- we don't close the last tab if fn.tabpagenr("$") == 1 then vim.cmd('echoerr "unable to delete last buffer"') return end local auto_tab = vim.t.CtrlSpaceAutotab if auto_tab and auto_tab ~= 0 then return end local label = vim.t.CtrlSpaceLabel -- why are we only confirming with named tabs? if label and string.len(label) > 0 then local bufs = buffers_in_tab(fn.tabpagenr()) local count = 0 for _, _ in pairs(bufs) do count = count + 1 end local prompt = "Close tab named '" .. label .. "' with " .. count .. " buffers?" if not ui.confirmed(prompt) then return end end with_restore_drawer(function () exe({"tabclose"}) buffers.delete_hidden_noname() buffers.delete_foreign() end) end function tabs.collect_unsaved() local unsaved = buffers.unsaved() if #unsaved == 0 then vim.cmd('echomsg "there are no unsaved buffers"') return end drawer.toggle(0) exe({'tabnew'}) local tab = fn.tabpagenr() tabs.set_label(tab, "Unsaved Buffers", 1) for _, b in ipairs(unsaved) do vim.cmd("silent! :b " .. b) end drawer.restore() end function tabs.collect_foreign() local foreign = buffers.foreign() if #foreign == 0 then vim.cmd("echoerr 'There are no foreign buffers'") end drawer.toggle(0) exe({'tabnew'}) local tab = fn.tabepagenr() tabs.set_label(tab, "Foreign Buffers", 1) exe(foreign) -- TODO what attaches these buffers to the new tab? Is there a BufEnter -- autocmd firing? for fb, _ in ipairs(foreign) do exe({":b " .. fb}) end drawer.restore() end function tabs.move(key) local nr = drawer.last_selected_index() with_restore_drawer(function() exe({"normal! " .. nr .. "gt"}) fn["ctrlspace#keys#tab#MoveHelper"](key) vim.cmd[[ let modes = ctrlspace#modes#Modes() call modes.Tab.Enable() ]] end) end function drawer.selected_file_path() local modes = fn["ctrlspace#modes#Modes"]() if modes.File.Enabled == 1 then local idx = drawer.last_selected_index() return M.files.collect()[idx].text elseif modes.Buffer.Enabled == 1 then local idx = drawer.last_selected_index() return fn.resolve(fn.bufname(idx)) else error("selected_file_path doesn't work in this mode") end end function drawer.kill(final) assert_drawer_on() if vim.b.updatetime_save then vim.o.updatetime = vim.b.updatetime_save end if vim.b.timeoutlen_save then vim.o.timeoutlen = vim.b.timeoutlen_save end if vim.b.mouse_save then vim.o.mouse = vim.b.mouse_save end exe({"bwipeout"}) if final then fn["ctrlspace#util#HandleVimSettings"]("stop") local modes = fn["ctrlspace#modes#Modes"]() if modes.Search.Data.Restored == 1 then fn["ctrlspace#search#AppendToSearchHistory"]() end drawer.go_start_window() exe({"set guicursor-=n:block-CtrlSpaceSelected-blinkon0"}) end end local function goto_line(l) if vim.b.size < 1 then return end if l < 1 then goto_line(vim.b.size - l) elseif l > vim.b.size then goto_line(l - vim.b.size) else fn.cursor(l, 1) end end function drawer.move_selection(where) local line = fn.line(".") local delta if where == "up" then delta = -1 elseif where == "down" then delta = 1 elseif where == "pgup" then delta = -fn.winheight("0") elseif where == "pgdown" then delta = fn.winheight("0") elseif where == "half_pgup" then delta = -math.floor(fn.winheight("0") / 2) elseif where == "half_pgdown" then delta = math.floor(fn.winheight("0") / 2) else delta = -line + where end local newpos = line + delta newpos = math.min(newpos, fn.line("$")) newpos = math.max(newpos, 1) goto_line(newpos) end function drawer.move_selection_and_remember(where) assert_drawer_on() if vim.b.size < 1 then return end if not vim.b.lastline then vim.b.lastline = 0 end drawer.move_selection(where) vim.b.lastline = fn.line(".") end function ui.confirm_if_modified() local unsaved = #buffers.unsaved() if #unsaved == 0 then return true else return ui.confirmed(#unsaved .. " buffers are unsaved. Proceed anyway?") end end function tabs.copy_or_move_selected_buffer(tabnr, copy_or_move) local bufnr = drawer.last_selected_index() if copy_or_move == "move" then detach_buffer(bufnr) end tabs.add_buffer(tabnr, bufnr) drawer.kill(false) exe({"normal! " .. tabnr .. "gt"}) drawer.restore() local bname = fn.bufname(bufnr) for i in ipairs(vim.b.items) do if fn.bufname(i.index) == bname then -- TODO this is all suspicious and wrong. We just need to move the cursor to where -- the buffer we inserted exists -- drawer.move_selection_and_remember(i + 1) exe({"b " .. i.index}) break end end end function util.chdir(dir) dir = fn.fnameescape(dir) local tab = fn.tabpagenr() local win = fn.winnr() exe({"cd " .. dir}) for tabnr=1, fn.tabpagenr("$") do exe({"noautocmd tabnext " .. tabnr}) if fn.haslocaldir() then exe({"lcd " .. dir}) end end exe({ "noautocmd tabnext " .. tab, "noautocmd " .. win .. "wincmd w" }) end function util.normalize_dir(dir) dir = fn.resolve(fn.expand(dir)) local is_slash = function (d) local last = string.sub(d, -1) return last == '\\' or last == '/' end while is_slash(dir) do dir = string.sub(dir, 1, -2) end return dir end function util.project_local_file(name) local config = fn["ctrlspace#context#Configuration"]() local root = fn["ctrlspace#roots#CurrentProjectRoot"]() if root ~= "" then root = root .. "/" end for _, marker in ipairs(config.ProjectRootMarkers) do local candidate = root .. marker if fn.isdirectory(candidate) then return candidate .. "/" .. name end end return root .. "." .. name end function bookmarks.add_new(dir) dir = ui.input("Add directroy to bookmarks: ", dir, "dir") if not dir or string.len(dir) == 0 then return end dir = util.normalize_dir(dir) if fn.isdirectory(dir) == 0 then print(string.format("Directory '%s' is invalid", dir)) return end local bms = fn['ctrlspace#bookmarks#Bookmarks']() for _, bm in ipairs(bms) do if bm.Directory == dir then print(string.format( "Directory '%s' is already bookmarked under the name '%s'", dir, bm.Name)) return end end local name = ui.input("New bookmark name: ", fn.fnamemodify(dir, ":t")) if not name or string.len(name) == 0 then return end fn['ctrlspace#bookmarks#AddToBookmarks'](dir, name) print(string.format("Directory '%s' has been bookmarked under the name '%s'", dir, name)) drawer.refresh() end function search.ask() search_state.activated = true search_state.query = fn.input("CtrlSpace> ", search_state.query or "") search_state.activated = false drawer.refresh() end function search.on_cmd_enter() end function search.on_cmdline_change() if not search_state.activated then return end search_state.query = fn.getcmdline() drawer.refresh() exe({"redraw!"}) end local db_dir = fn.stdpath("cache") .. "/ctrlspace" local db_dir_init = false local db_latest = nil local function db_file() if not db_dir_init then fn.mkdir(db_dir, "p") db_dir_init = true end return db_dir .. "/bookmarks_and_roots.json" end local function db_empty() return { bookmarks = {}, roots = {}, } end local function db_load() local file = db_file() if fn.filereadable(file) then return fn.json_decode(fn.readfile(file)) else return db_empty() end end local function db_save(new_db) if not new_db then error("database must not be nil") end local file = db_file() fn.writefile({fn.json_encode(new_db)}, file) db_latest = new_db end function db.add_bookmark(bm) local data = db.latest() table.insert(data.bookmarks, bm) db_save(data) end function db.remove_boomark(idx) local data = db.latest() table.remove(data, idx) db_save(data) end function db.add_root(root) local data = db.latest() data.roots[root] = true db_save(data) end function db.remove_root(root) local data = db.latest() data.roots[root] = nil db_save(data) end function db.latest() if not db_latest then db_latest = db_load() end return db_latest end function roots.add(dir) if not dir or dir == "" then dir = fn.getcwd() end dir = util.normalize_dir(fn.fnamemodify(dir, ":p")) if fn.isdirectory(dir) == 0 then print(string.format("Invalid directory '%s'", dir)) return end local all_roots = db.latest().roots if all_roots[dir] then print(string.format("Directory '%s' is already a root", dir)) return end db.add_root(dir) print(string.format("Directory '%s' is added as a project root", dir)) end function roots.remove(dir) if not dir or dir == "" then dir = fn.getcwd() end dir = util.normalize_dir(fn.fnamemodify(dir, ":p")) local all_roots = db.latest().roots if not all_roots[dir] then print(string.format("Directory '%s' is not a root", dir)) return end db.remove_root(dir) end local function find_roots(dir, markers, all_roots) if all_roots[dir] then return dir end for _, marker in ipairs(markers) do local candidate = dir .. "/" .. marker if fn.filereadable(candidate) == 1 or fn.isdirectory(candidate) then return dir end end local parent = fn.fnamemodify(dir, ":p:h:h") if parent == dir then return nil else return find_roots(parent, markers, all_roots) end end local root = nil function roots.find_current() local dir = fn.fnamemodify(".", ":p") local config = fn["ctrlspace#context#Configuration"]() local all_roots = db.latest().roots return find_roots(dir, config.ProjectRootMarkers, all_roots) end function roots.set(dir) root = dir end function roots.current() return root end function roots.ask_if_unset() if root then return true end root = roots.find_current() if root then return true end local prompt_root = fn.input("No project root found. Set the project root:", fn.fnamemodify(".", ":p:h"), "dir") if prompt_root and prompt_root ~= "" then root = util.normalize_dir(prompt_root) files.clear() db.add_root(prompt_root) return true else print("Cannot continue with the project root unset") return false end end function roots.try_find() local r = roots.find_current() if r then root = r end end local function empty_workspaces() return { workspaces = {} } end local unnamed_ws = "<unnamed>" local workspace_db = empty_workspaces() function workspaces.delete(name) if not ui.confirmed("Delete workspace '" .. name .. "'?") then return end end local function workspace_file() return util.project_local_file("cs_workspaces.json") end local function workspaces_set_names() end local function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end local function workspaces_save() local data = deepcopy(workspace_db) if data.workspaces[""] then data.workspaces[unnamed_ws] = data.workspaces[""] end local file = workspace_file() fn.writefile({fn.json_encode(data)}, file) end local function workspaces_set_active_name(name) end function workspaces.save(name) if not roots.ask_if_unset() then return false end local current_root = roots.current() if name == "" then local modes = fn["ctrlspace#modes#Modes"]() local active = modes.Workspace.Data.Active if active.Name ~= "" and active.Root == current_root then name = active.Name else print("No workspace to save") return false end end fn['ctrlspace#util#HandleVimSettings']("start") local cwd_save = fn.fnamemodify(".", ":p:h") local ssop_save = vim.o.ssop local restore = function() exe({ "cd " .. fn.fnameescape(cwd_save), "set ssop=" .. ssop_save, }) fn['ctrlspace#util#HandleVimSettings']("stop") end exe({ "set ssop=winsize,tabpages,buffers,sesdir", "cd " .. fn.fnameescape(current_root) }) local filename = workspace_file() local tab_data = {} for tabnr=1,fn.tabpagenr("$") do local data = { label = fn.gettabvar(tabnr, "CtrlSpaceLabel"), autotab = fn.gettabvar(tabnr, "CtrlSpaceAutotab", 0), } local readable_buffers = {} for bufnr, _ in pairs(buffers_in_tab(tabnr)) do local bufname = fn.bufname(bufnr) if fn.filereadable(bufname) == 1 then table.insert(readable_buffers, bufname) end end data.bufs = readable_buffers table.insert(tab_data, data) end local temp_session_file = "CS_SESSION" exe({"mksession! " .. temp_session_file}) if fn.filereadable(temp_session_file) == 0 then restore() print(string.format("Workspace '%s' cannot be saved", name)) return false end local tab_index = 0 local commands = {} for _, cmd in ipairs(fn.readfile(temp_session_file)) do if string.match(cmd, "^lcd ") then goto continue end local file = string.match(cmd, "^badd%s%d+(%w+)$") if file and fn.filereadable(file) == 1 then table.insert(commands, cmd) goto continue end if cmd == "tabnext" then table.insert(commands, cmd) end local data = tab_data[tab_index] for _, b in ipairs(data.bufs) do table.insert(commands, 'edit ' .. fn.fnameescape(b)) end if data.label and data.label ~= "" then local label = fn.substitute(data.label, "'", "''", "g") local c = string.format("let t:CtrlSpaceLabel = '%s'", label) table.insert(commands, c) end if data.autotab and data.autotab ~= "" then local c = string.format("let t:CtrlSpaceAutotab = %s", data.autotab) table.insert(commands, c) end tab_index = tab_index + 1 ::continue:: end fn.delete(temp_session_file) -- TODO restore right after saving session file? restore() local workspace = { commands = commands, name = name, } local current_db = db.latest() current_db.workspaces[name] = workspace workspaces_save() workspaces_set_active_name(name) -- TODO why do we need this reload? workspaces_set_names() print(string.format("Workspace '%s' has been saved.", name)) return true end return M
object_tangible_veteran_reward_frn_vet_tusken_raider_toy = object_tangible_veteran_reward_shared_frn_vet_tusken_raider_toy:new { } ObjectTemplates:addTemplate(object_tangible_veteran_reward_frn_vet_tusken_raider_toy, "object/tangible/veteran_reward/frn_vet_tusken_raider_toy.iff")
local persistent_mt = { mt_store = { } } function persistent_mt.init(module, module_name, module_metatable) fail_if_missing(module) fail_if_missing(module_name) fail_if_missing(module_metatable) assert(persistent_mt.mt_store[module_name] == nil) persistent_mt.mt_store[module_name] = module_metatable module_metatable.__src = module_name end function persistent_mt.bless(instance, module_metatable) fail_if_missing(instance) fail_if_missing(module_metatable) local src = module_metatable.__src if src == nil then error("Must call init before bless") end local mt = persistent_mt.mt_store[src] if mt == nil then error() end if mt ~= module_metatable then error() end setmetatable(instance, module_metatable) instance.__src = src end function persistent_mt.rebless(instance) fail_if_missing(instance) local src = instance.__src if src == nil then error("Instance was not previously blessed") end local module = require(src) local mt = persistent_mt.mt_store[src] if mt == nil then error("Must call init before bless") end setmetatable(instance, mt) end function persistent_mt.was_blessed(instance) fail_if_missing(instance) end return persistent_mt
local Class = require("facto.class") local Event = require("facto.event") local AbstractExchanger = require("facto.exchanger.abstractexchanger") local CargoWagonExchanger = Class.extend({}, AbstractExchanger) -- @section property members -- @property string The type of this concrete exchanger which will be used for registration in exchanger factory. CargoWagonExchanger.type = "cargo-wagon-exchanger" -- @property boolean if true, the first container will act as source. CargoWagonExchanger.is_output = true -- @property uint the count limit will be exchanged in one turn for each type. CargoWagonExchanger.exchange_count_each_type = 50*8 -- @property uint only applied when has no configured requests. CargoWagonExchanger.request_stack_size_multiply = 8 -- @section metatable members --- Initialization for exchanger. function CargoWagonExchanger:initialize() self.factoobj1 = self.carriage.factoobj if self.autoconnect then self.connected = true end end --- Build exchanger. -- @tparam LuaPosition position exchanger position -- @tparam table tiles a reference table for caching tiles -- @tparam table lazycalls a reference table for caching closures -- @tparam closure addedcall function CargoWagonExchanger:build(position, tiles, lazycalls, addedcall) local name if self.is_output then name = "logistic-chest-requester" else name = "logistic-chest-passive-provider" end lazycalls[#lazycalls+1] = function() local factoobj = self.carriage:getTrainSurface().create_entity({ name = name, position = position, force = 'neutral', create_build_effect_smoke = false }) factoobj.destructible = false factoobj.minable = false self.factoobj2 = factoobj addedcall() end end --- Get the source facto object, since source or destination roles could be swapped. -- @treturn factoobject function CargoWagonExchanger:getSourceFactoobj() if self.is_output then return self.factoobj1 else return self.factoobj2 end end --- Get the source, such as inventory of wagon or fluidbox of a tank. -- @treturn factoobject function CargoWagonExchanger:getSource() if self.is_output then return self.factoobj1.get_inventory(defines.inventory.cargo_wagon) else return self.factoobj2.get_inventory(defines.inventory.chest) end end --- Get the destination facto object, since source or destination roles could be swapped. -- @treturn factoobject function CargoWagonExchanger:getDestinationFactoobj() if self.is_output then return self.factoobj2 else return self.factoobj1 end end --- Get the destination, such as inventory of wagon or fluidbox of a tank. -- @treturn factoobject function CargoWagonExchanger:getDestination() if self.is_output then return self.factoobj2.get_inventory(defines.inventory.chest) else return self.factoobj1.get_inventory(defines.inventory.cargo_wagon) end end --- Check whether facto object is valid for access. -- @treturn boolean function CargoWagonExchanger:isValid() if not self.factoobj1 or not self.factoobj1.valid or not self.factoobj2 or not self.factoobj2.valid then return false end return true end function CargoWagonExchanger:canExchange() return not (not self:isValid() or not self.connected or self:isSourceEmpty() or self:isDestinationFull()) end --- Exchange items between wagon inventory and chests inside. function CargoWagonExchanger:exchange() if not self:isValid() or not self.connected then return end self:exchangeTypeBalanced() end --- Build request stacks by source. -- If destination has no requests, and request buffer chest is checked. -- @treturn table function CargoWagonExchanger:buildRequestStackBySource() local prototypes = game.item_prototypes local source = self:getSource() local request_stacks = {} for name, count in pairs(source.get_contents()) do local default_request_count = prototypes[name].stack_size * self.request_stack_size_multiply if count < default_request_count then default_request_count = count end request_stacks[name] = default_request_count end return request_stacks end --- Get request stacks from request slots if there has one. -- @treturn table function CargoWagonExchanger:getRequestStacks(factoobj) local requst_stacks = {} for i = 1, factoobj.request_slot_count, 1 do local stack = factoobj.get_request_slot(i) if stack then requst_stacks[stack.name] = stack.count end end return requst_stacks end --- Build request stacks. -- 1. If destination has requests, using request slots -- 2. If destination has no requests but request buffers is checked, build request stacks by source -- 3. If does not support request slots, build request stacks by source -- @treturn table function CargoWagonExchanger:buildRequestStack() local requst_stacks local destination_factoobj = self:getDestinationFactoobj() if destination_factoobj.request_slot_count > 0 and destination_factoobj.request_from_buffers then requst_stacks = self:getRequestStacks(destination_factoobj) if next(requst_stacks) == nil then requst_stacks = self:buildRequestStackBySource() end elseif destination_factoobj.request_slot_count == 0 then requst_stacks = self:buildRequestStackBySource() end return requst_stacks or {} end --- Exchange items with different types balanced. -- In one turn, each type of items will be transfered to destination, but a little bit more time consuming. function CargoWagonExchanger:exchangeTypeBalanced() local requst_stacks = self:buildRequestStack() local source = self:getSource() local destination = self:getDestination() local type_count = table_size(requst_stacks) if type_count == 0 then return end local cycle_count_each_type = math.floor(self.exchange_count_each_type / type_count) local source_stacks = source.get_contents() local destination_stacks = destination.get_contents() for name, request_count in pairs(requst_stacks) do destination_stacks[name] = destination_stacks[name] or 0 source_stacks[name] = source_stacks[name] or 0 if destination_stacks[name] ~= "full" then local destination_count = destination_stacks[name] local source_count = source_stacks[name] if request_count > destination_count and source_count > 0 then local exchange_count = request_count - destination_count if exchange_count > source_count then exchange_count = source_count end if exchange_count > cycle_count_each_type then exchange_count = cycle_count_each_type end local inserted_count = destination.insert({ name = name, count = exchange_count }) --- full of this type if exchange_count > inserted_count then destination_stacks[name] = "full" else destination_stacks[name] = destination_stacks[name] + inserted_count end if inserted_count > 0 then local removed_count = source.remove({ name = name, count = inserted_count }) source_stacks[name] = source_stacks[name] - removed_count end end end end end --- Exchange items type by type. -- @fixme codes not ready to excute. -- This may cause only type of items to be transfered to destination in one turn. function CargoWagonExchanger:exchangeTypeByType() local requst_stacks = self:buildRequestStack() local source = self.factoobj1.get_inventory(defines.inventory.cargo_wagon) local destination = self.factoobj2.get_inventory(defines.inventory.chest) local cached = {} for name, request_count in pairs(requst_stacks) do local destination_count = destination.get_item_count(name) local source_count = source.get_item_count(name) if request_count > destination_count and source_count > 0 and cached[name] == nil then local exchange_count = request_count - destination_count if exchange_count > source_count then exchange_count = source_count end local inserted_count = destination.insert({ name = name, count = exchange_count }) if inserted_count > 0 then source.remove({ name = name, count = inserted_count }) end cached[name] = true end end end -- @export return CargoWagonExchanger
local fn = require 'fn' local handler = require 'tulip.handler' local tcheck = require 'tcheck' local xerror = require 'tulip.xerror' local xtable = require 'tulip.xtable' local function match(routes, path) local _, _, _, route = fn.any(function(_, route) return string.find(path, route.pattern) end, ipairs(routes)) if route then return route, table.pack(string.match(path, route.pattern)) end return nil end local function notfound(_, res) res:write{ status = 404, body = handler.HTTPSTATUS[404], content_type = 'text/plain', } end local Mux = {__name = 'tulip.pkg.routes.Mux'} Mux.__index = Mux function Mux:handle(req, res) local method = req.method local path = req.url.path local route, pathargs local routes = self.bymethod[method] if routes then route, pathargs = match(routes, path) end -- if no route did match, check if it's a HEAD and if so -- search in GET if not route and method == 'HEAD' then routes = self.bymethod['GET'] if routes then route, pathargs = match(routes, path) end end if route then req.pathargs = pathargs req.routeargs = xtable.merge(req.routeargs or {}, route, function(_, _, k) return k ~= 'method' and k ~= 'pattern' and k ~= 'middleware' and k ~= 'handler' end) handler.chain_middleware(route.middleware, req, res) return end -- trigger either the no_such_method or the not_found -- handler, if specified. if self.routes.no_such_method then -- look for matches with other methods local methods = {} for m, rs in pairs(self.bymethod) do if m == method then goto continue end if match(rs, path) then table.insert(methods, m) end ::continue:: end if #methods > 0 then return self.routes.no_such_method(req, res, methods) end end local nf = self.routes.not_found or notfound return nf(req, res) end -- Creates a new request multiplexer that dispatches using the provided -- routes table. That table holds the route patterns in the array part, -- where each route is a table with the following fields: -- * method (string): the http method to match against -- * pattern (string): the Lua pattern that the path part of the request -- must match. -- * middleware (array): list of middleware functions to call. -- -- Any other field of the matching route will be stored on the request -- under routeargs. -- -- The table should not be modified after the call. -- -- The middleware handlers receive the request and response instances as -- arguments as well as a next function to call the next middleware. -- The pattern does not have to be anchored, and if it -- contains any captures, those are provided on the request object in the -- pathargs field, as an array of values. -- -- The routes table can also have the following non-array fields: -- * no_such_method (function): handler to call if no route matches the -- request, but only due to the http method. The not_found handler is -- called if this field is not set. In addition to the usual arguments, -- a 3rd table argument is passed, which is the array of http methods -- supported for this path. -- * not_found (function): handler to call if no route matches the request. -- The default not found handler is called if this field is not set, which -- returns 404 with a plain text body. -- -- If the request is a HEAD and there is no route found, the Mux tries to -- find and call a match for a GET and the same path before giving up. function Mux.new(routes) tcheck('table', routes) local o = {routes = routes} setmetatable(o, Mux) -- index by method o.bymethod = fn.reduce(function(c, i, route) if (route.method or '') == '' then xerror.throw('method missing at routes[%d]', i) elseif (route.pattern or '') == '' then xerror.throw('pattern missing at routes[%d]', i) elseif (not route.middleware) or (#route.middleware == 0) then xerror.throw('handler missing at routes[%d]', i) end local t = c[route.method] or {} table.insert(t, route) c[route.method] = t return c end, {}, ipairs(routes)) return o end return Mux
--types/winuser: winuser types and macros from multiple headers --Written by Cosmin Apreutesei. Public Domain. setfenv(1, require'winapi') --constants IMAGE_BITMAP = 0 IMAGE_ICON = 1 IMAGE_CURSOR = 2 IMAGE_ENHMETAFILE = 3 DLGC_WANTARROWS = 0x0001 -- Control wants arrow keys DLGC_WANTTAB = 0x0002 -- Control wants tab keys DLGC_WANTALLKEYS = 0x0004 -- Control wants all keys DLGC_WANTMESSAGE = 0x0004 -- Pass message to control DLGC_HASSETSEL = 0x0008 -- Understands EM_SETSEL message DLGC_DEFPUSHBUTTON = 0x0010 -- Default pushbutton DLGC_UNDEFPUSHBUTTON= 0x0020 -- Non-default pushbutton DLGC_RADIOBUTTON = 0x0040 -- Radio button DLGC_WANTCHARS = 0x0080 -- Want WM_CHAR messages DLGC_STATIC = 0x0100 -- Static item: don't include DLGC_BUTTON = 0x2000 -- Button item: can be checked --macros function MAKELONG(lo,hi) return bit.bor(bit.band(lo, 0xffff), bit.lshift(bit.band(hi, 0xffff), 16)) end MAKEWPARAM = MAKELONG MAKELPARAM = MAKELONG MAKELRESULT = MAKELONG function MAKEINTRESOURCE(i) if type(i) == 'number' then return ffi.cast('LPWSTR', ffi.cast('WORD', i)) end return i end function IS_INTRESOURCE(i) error'NYI' --((((ULONG_PTR)(_r)) >> 16) == 0) end --types SIZE = types.SIZE POINT = types.POINT RECT = types.RECT local function struct_tostring(fields) return function(t) local s = fields[1]..'{'..t[fields[2]] for i=3,#fields do s = s..','..t[fields[i]] end return s..'}' end end ffi.metatype('SIZE', {__tostring = struct_tostring{'SIZE','w','h'}}) ffi.metatype('POINT', {__tostring = struct_tostring{'POINT','x','y'}}) --NOTE: there's no __newindex for virtual fields because Lua's --assignment order in multiple assignment is undefined (and even --if it were defined, it would be significant which is a bug nest). ffi.metatype('RECT', { __tostring = struct_tostring{'RECT','x1','y1','x2','y2'}, __index = function(r,k) if k == 'w' then return r.x2 - r.x1 end if k == 'h' then return r.y2 - r.y1 end end, })
local lockzoom = false local swayingsmall = false local swayinglarge = false local swayingbigger = false local swayingbiggest = false local swayingbiggest2 = false local gfAscend = false local gfBack = false local background = nil function update (elapsed) local currentBeat = (songPos / 1000)*(bpm/60) hudX = getHudX() hudY = getHudY() gfA = getActorAlpha('girlfriend') if lockzoom then setCamZoom(1) end if shakenote then for i=0,7 do setActorX(_G['defaultStrum'..i..'X'] + 3 * math.sin((currentBeat * 10 + i*0.25) * math.pi), i) setActorY(_G['defaultStrum'..i..'Y'] + 3 * math.cos((currentBeat * 10 + i*0.25) * math.pi) + 10, i) end end if shakehud then for i=0,7 do setHudPosition(5 * math.sin((currentBeat * 5 + i*0.25) * math.pi), 5 * math.cos((currentBeat * 5 + i*0.25) * math.pi)) setCamPosition(-5 * math.sin((currentBeat * 5 + i*0.25) * math.pi), -5 * math.cos((currentBeat * 5 + i*0.25) * math.pi)) end end if sustainshake then for i=0,7 do setHudPosition(1 * math.sin((currentBeat * 1 + i*0.25) * math.pi), 1 * math.cos((currentBeat * 1 + i*0.25) * math.pi)) end end if finalshake then for i=0,7 do setHudPosition(8 * math.sin((currentBeat * 15 + i*0.25) * math.pi), 8 * math.cos((currentBeat * 15 + i*0.25) * math.pi)) setCamPosition(8 * math.sin((currentBeat * 15 + i*0.25) * math.pi), 8 * math.cos((currentBeat * 15 + i*0.25) * math.pi)) end end if slowsway then camHudAngle = 2 * math.sin((currentBeat)) end if sway then camHudAngle = 8 * math.sin((currentBeat)) end if fastsway then camHudAngle = 12 * math.sin((currentBeat)) end if hudup then setHudPosition(0, hudY - 1) end if huddown then setHudPosition(0, hudY + 1) end if swayingsmall then for i=0,7 do setActorX(_G['defaultStrum'..i..'X'] + 25 * math.sin((currentBeat + i*0)), i) setActorY(_G['defaultStrum'..i..'Y'] + 25,i) end end if swayinglarge then for i=0,3 do setActorX(_G['defaultStrum'..i..'X'] + 300 * math.sin((currentBeat + i*0)) + 350, i) setActorY(_G['defaultStrum'..i..'Y'] + 64 * math.cos((currentBeat + i*5) * math.pi) + 10,i) end for i=4,7 do setActorX(_G['defaultStrum'..i..'X'] - 300 * math.sin((currentBeat + i*0)) - 275, i) setActorY(_G['defaultStrum'..i..'Y'] - 64 * math.cos((currentBeat + i*5) * math.pi) + 10,i) end end if swayingbigger then for i=0,7 do setActorX(_G['defaultStrum'..i..'X'] + 32 * math.sin((currentBeat + i*0) * math.pi), i) setActorY(_G['defaultStrum'..i..'Y'] + 10 * math.cos((currentBeat + i*5) * math.pi) + 10 ,i) end end if swayingbiggest then for i=0,3 do setActorX(_G['defaultStrum'..i..'X'] + 300 * math.sin((currentBeat + i*0)) + 350, i) setActorY(_G['defaultStrum'..i..'Y'] + 64 * math.cos((currentBeat + i*5) * math.pi) + 10,i) end for i=4,7 do setActorX(_G['defaultStrum'..i..'X'] - 300 * math.sin((currentBeat + i*0)) - 275, i) setActorY(_G['defaultStrum'..i..'Y'] - 64 * math.cos((currentBeat + i*5) * math.pi) + 10,i) end end if swayingbiggest2 then for i=0,3 do setActorX(_G['defaultStrum'..i..'X'] - 300 * math.sin(currentBeat) + 350, i) setActorY(_G['defaultStrum'..i..'Y'] + 64 * math.cos((currentBeat + i*5) * math.pi) + 10,i) end for i=4,7 do setActorX(_G['defaultStrum'..i..'X'] + 300 * math.sin(currentBeat) - 275, i) setActorY(_G['defaultStrum'..i..'Y'] - 64 * math.cos((currentBeat + i*5) * math.pi) + 10,i) end end end function beatHit (beat) local currentBeat = (songPos / 1000)*(bpm/60) for i=4,7 do setActorX(_G['defaultStrum'..i..'X'] - 250 * math.sin((currentBeat + i*0)) - 225, i) setActorY(_G['defaultStrum'..i..'Y'] - 15 * math.cos((currentBeat + i*5) * math.pi) + 10,i) camHudAngle = 4 * math.sin((currentBeat)) end end function stepHit (step) if curStep >= 0 then showOnlyStrums = true for i=0,3 do tweenFadeIn(i,0,0.6) end end end
-- -- Created by IntelliJ IDEA. -- User: sdcuike -- Date: 2015/12/29 -- Time: 22:46 -- To change this template use File | Settings | File Templates. -- --[[ Lua is a dynamically typed language. There are no type definitions in the language; each value carries its own type. There are eight basic types in Lua: nil, boolean, number, string, userdata, function, thread, and table. The type function gives the type name of any given value: --]] print(type("Hello world")) --string print(type(10.4*3)) -- number print(type(print)) -- function print(type(type)) -- function print(type(true)) -- boolean print(type(nil)) -- nil print(type(type(x))) -- string --[[The last line will result in โ€œstringโ€ no matter the value of X, because the result of type is always a string. --]] print("Variables have no predefined types; any variable can contain values of any type:") print(type(a)) -- nil a = 10 print(type(a)) -- number a = "a string" print(type(a)) -- string a = print -- yes,this is valid --[[ Notice the last two lines: functions are first-class values in Lua; so, we can manipulate them like any other value. (We will see more about this facility in Chapter 6.) --]] a(type(a)) -- function a= "hello" print(#a) print("Coercions") print("10" + 1) -- 11 print("10 + 1") print(10 .. 100) print("If you need to convert a string to a number explicitly, you can use the function tonumber, which returns nil if the string does not denote a proper number") n = tonumber("100") if n == nil then error("is not a valid number") else print(n) end --2.5 Tables print("2.5 Tables") a = {} k = "x" a[k] = 10 print(a["x"]) a[20] = "great" k = 20 print(a[k])
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by flori. --- DateTime: 01/11/2020 20:58 --- local LibAtlas = LibStub:NewLibrary("LibAtlas", 1) if not LibAtlas then return end local debug = 0 local pairs = pairs local Atlas = {} function LibAtlas:RegisterAtlas(name, path, spriteSheet) if Atlas[name] then return end Atlas[name] = { Path = path, Sprites = spriteSheet, } if debug == 1 then Atlas[name].OnUse = false end end function LibAtlas:GetAtlas(key) --check if string is name or path if Atlas[key] then if debug == 1 then Atlas[key].OnUse = true end return Atlas[key] end for k,v in pairs (Atlas) do if v.Path == key then if debug == 1 then v.OnUse = true end return v end end return nil end function LibAtlas:GetPath(key) if Atlas[key] then if debug == 1 then Atlas[key].OnUse = true end return Atlas[key].Path end end function LibAtlas:GetSheet(key) local atlas = self:GetAtlas(key) if atlas == nil then return nil end return atlas.Sprites end function LibAtlas:GetTexCoord(key, spriteName) local atlas = self:GetAtlas(key) if atlas == nil then return nil end local width = atlas.Sprites.width local height = atlas.Sprites.height local l, r, t, b = unpack(atlas.Sprites[spriteName]) return l/width, r/width, t/height, b/height end function LibAtlas:GetSpriteData(key, spriteName) local atlas = self:GetAtlas(key) if atlas == nil then return nil end return atlas.Sprites[spriteName] or nil end function LibAtlas:GetDebugInfo() if debug ~= 1 then return end local redcolor = "FFFF2200" print("----- DEBUG LIBATLAS -----") for k,v in pairs(Atlas) do if k.OnUse == false then print ("|c"..redcolor..v.Path.."is never used |r") else print(v.Path) end for n,s in pairs(v.Sprites) do local l,r,t,b = unpack(s) print ("\t"..n.."("..l..", "..r..", "..t..", "..b..")") end end end
--Time all SET sec = 217.49171447754 day = 16 mon = 2 year = 2019 --End of SampleText
------------------------------------------------------------------------------- -- ElvUI Chat Tweaks By Crackpotx (US, Lightbringer) -- Based on functionality provided by Prat and/or Chatter ------------------------------------------------------------------------------- local Module = ElvUI_ChatTweaks:NewModule("Custom Named Chat Filters", "AceConsole-3.0") local L = LibStub("AceLocale-3.0"):GetLocale("ElvUI_ChatTweaks", false) Module.name = L["Custom Named Chat Filters"] Module.namespace = string.gsub(Module.name, " ", "") local UnitName = _G["UnitName"] local ChatFrame_AddMessageEventFilter = _G["ChatFrame_AddMessageEventFilter"] local ChatFrame_RemoveMessageEventFilter = _G["ChatFrame_RemoveMessageEventFilter"] local channels = {"party", "guild", "officer", "raid", "say", "yell"} local db, options local defaults = { global = { mode = "HIDE", color = {r = 0.45, g = 0.45, b = 0.45}, filters = { "^[aA]nal (.+)$", "[aA]nal", "Thunderfury", }, party = true, guild = true, officer = false, raid = true, instance_chat = true, say = true, yell = true, }, } local function UCWords(link) return link:lower():gsub("(%w+)", function(first) return first:gsub("^%l", upper) end) end local function NamedFilters(self, event, message, author, ...) if not message or #db.filters == 0 or author == UnitName("player") then return end for _, value in ipairs(db.filters) do if Module.debug then print(message) end if message:match(value) then if db.mode == "COLOR" then local color = ("%02x%02x%02x"):format(db.color.r * 255, db.color.g * 255, db.color.b * 255) return false, ("|cff%s%s|r"):format(color, message), author, ... else return true end end end end function Module:PopulateFilters(filters) db.filters = {} for _, value in pairs(filters) do if value ~= "" and value ~= nil then db.filters[#db.filters + 1] = value end end end function Module:FiltersToString() local trigs = "" for i = 1, #db.filters do if db.filters[i]:trim() ~= "" then trigs = trigs .. db.filters[i] .. "\n" end end return trigs end function Module:SetEventFilters() for _, info in ipairs(channels) do if db[info] then ChatFrame_AddMessageEventFilter(("CHAT_MSG_%s"):format(info:upper()), NamedFilters) else ChatFrame_RemoveMessageEventFilter(("CHAT_MSG_%s"):format(info:upper()), NamedFilters) end end end function Module:OnInitialize() self.db = ElvUI_ChatTweaks.db:RegisterNamespace(Module.namespace, defaults) db = self.db.global self.debug = ElvUI_ChatTweaks.db.global.debugging self:SetEventFilters() end function Module:Info() return L["This module is for named channels only. Allows you to filter certain words or phrases using Lua's pattern matching. For an item, achievement, spell, etc. just use the name of the item, don't try to link it.\n\nFor more information see this addon's Curse page."] end function Module:GetOptions() if not options then options = { mode = { type = "select", order = 13, name = L["Filtering Mode"], desc = L["How to filter any matches."], values = { ["COLOR"] = L["Colorize"], ["HIDE"] = L["Remove"], }, get = function() return db.mode end, set = function(_, value) db.mode = value end }, color = { type = "color", order = 14, name = L["Filter Color"], desc = L["Color to change the filtered message to.\n\n|cffff0000Only works when Filtering Mode is set to |cff00ff00Colorize|r."], get = function() return db.color.r, db.color.g, db.color.b end, set = function(_, r, g, b) db.color.r = r db.color.g = g db.color.b = b end }, filters = { type = "input", order = 15, multiline = true, width = "double", name = L["Filters"], desc = L["Custom chat filters."], get = function() return Module:FiltersToString() end, set = function(_, value) local trigList = {strsplit("\n", value:trim())} Module:PopulateFilters(trigList) end }, channels = { type = "group", order = 100, name = L["Channels"], get = function(info) return db[info[#info]] end, set = function(info, value) db[info[#info]] = value; Module:SetEventFilters(); end, guiInline = true, args = { party = { type = "toggle", order = 1, name = CHAT_MSG_PARTY, }, guild = { type = "toggle", order = 2, name = CHAT_MSG_GUILD, }, officer = { type = "toggle", order = 3, name = CHAT_MSG_OFFICER, }, raid = { type = "toggle", order = 4, name = CHAT_MSG_RAID, }, instance_chat = { type = "toggle", order = 5, name = INSTANCE_CHAT, }, say = { type = "toggle", order = 7, name = CHAT_MSG_SAY, }, yell = { type = "toggle", order = 8, name = CHAT_MSG_YELL, }, }, }, } end return options end
function gcd(a,b) return a == 0 and b or gcd(b % a, a) end do local function coerce(a, b) if type(a) == "number" then return rational(a, 1), b end if type(b) == "number" then return a, rational(b, 1) end return a, b end rational = setmetatable({ __add = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.den + a.den * b.num, a.den * b.den) end, __sub = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.den - a.den * b.num, a.den * b.den) end, __mul = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.num, a.den * b.den) end, __div = function(a, b) local a, b = coerce(a, b) return rational(a.num * b.den, a.den * b.num) end, __pow = function(a, b) if type(a) == "number" then return a ^ (b.num / b.den) end return rational(a.num ^ b, a.den ^ b) --runs into a problem if these aren't integers end, __concat = function(a, b) if getmetatable(a) == rational then return a.num .. "/" .. a.den .. b end return a .. b.num .. "/" .. b.den end, __unm = function(a) return rational(-a.num, -a.den) end}, { __call = function(z, a, b) return setmetatable({num = a / gcd(a, b),den = b / gcd(a, b)}, z) end} ) end print(rational(2, 3) + rational(3, 5) - rational(1, 10) .. "") --> 7/6 print((rational(4, 5) * rational(5, 9)) ^ rational(1, 2) .. "") --> 2/3 print(rational(45, 60) / rational(5, 2) .. "") --> 3/10 print(5 + rational(1, 3) .. "") --> 16/3 function findperfs(n) local ret = {} for i = 1, n do sum = rational(1, i) for fac = 2, i^.5 do if i % fac == 0 then sum = sum + rational(1, fac) + rational(fac, i) end end if sum.den == sum.num then ret[#ret + 1] = i end end return table.concat(ret, '\n') end print(findperfs(2^19))
local handler = require("handler") local computations = require("computations") -- pretends that the system is doing an IO operation for 0.3 seconds computations.slow(0.3) handler.writeStatus(200) handler.writeBody("from LUA!")
local M = {} M.throttle_leading = function(fn, ms) local timer = vim.loop.new_timer() local running = false return function(...) if running then return end timer:start(ms, 0, function() running = false end) running = true fn(...) end end M.debounce_trailing = function(fn, ms) local timer = vim.loop.new_timer() return function(...) local argv = { ... } local argc = select('#', ...) timer:start(ms, 0, function() fn(unpack(argv, 1, argc)) end) end end return M
local uv = require('luv') local tap = require('util/tap') tap.test("test uv.new_work", function() print('Please be patient, the test cost a lots of time') local count = 1000 -- for memleaks dected local step = 0 local worker = nil -- after work, in loop thread local callback = function(n, r, id, s) assert(n * n == r) if (step < count) then uv.queue_work(worker, n, s) step = step + 1 if (step % 100 == 0) then print(string.format('run %d%%', math.floor(step * 100 / count))) end end end -- work, in threadpool local work = function(n, s) local uv = require('luv') local threadId = uv.thread_self() uv.sleep(1) return n, n * n, tostring(threadId), s end worker = uv.new_work(work, callback) local longString = string.rep('-', 4096) local list = { 2, 4, 6, -2, -11, 2, 4, 6, -2, -11 } for _, value in ipairs(list) do uv.queue_work(worker, value, longString) end end) tap.run()
--[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์„ [Amount]๋งŒํผ [Modifier]ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Modifier.TrgModifier @param.Amount.Number @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์„ [Amount]๋งŒํผ [Modifier]ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Modifier.TrgModifier @param.Amount.Number ]================================] function SetTech(Tech, Player, Modifier, Amount) --ํ…Œํฌ/Tech,TrgPlayer,TrgModifier,Number/[Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์„ [Amount]๋งŒํผ [Modifier]ํ•ฉ๋‹ˆ๋‹ค. Tech = ParseTechdata(Tech) Player = ParsePlayer(Player) Modifier = ParseModifier(Modifier) offset = TechOffset(Tech, Player) if IsNumber(offset) then Mod = offset % 4 ROffset = offset - Mod if Mod == 0 then Mask = "0xFF" elseif Mod == 1 then Mask = "0xFF00" elseif Mod == 2 then Mask = "0xFF0000" elseif Mod == 3 then Mask = "0xFF000000" end if IsNumber(Amount) then rstr = string.format("SetMemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Modifier, Amount * math.pow(256, Mod), Mask) else rstr = string.format("MemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Modifier, Amount .. " * " .. math.pow(256, Mod), Mask) end else if Modifier == 7 then rstr = string.format("bwrite(%s, %s)", offset, Amount) elseif Modifier == 8 then rstr = string.format("bwrite(%s, bread(%s) + %s)", offset, offset, Amount) elseif Modifier == 9 then rstr = string.format("bwrite(%s, bread(%s) - %s)", offset, offset, Amount) end end echo(rstr) end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์ด [Comparison] [Amount]์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Comparison.TrgComparison @param.Amount.Number @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์ด [Comparison] [Amount]์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Comparison.TrgComparison @param.Amount.Number ]================================] function CurrentTech(Tech, Player, Comparison, Amount) --ํ…Œํฌ/Tech,TrgPlayer,TrgComparison,Number/[Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์ด [Comparison] [Amount]์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. Tech = ParseTechdata(Tech) Player = ParsePlayer(Player) Comparison = ParseComparison(Comparison) offset = TechOffset(Tech, Player) if IsNumber(offset) then Mod = offset % 4 ROffset = offset - Mod if Mod == 0 then Mask = "0xFF" elseif Mod == 1 then Mask = "0xFF00" elseif Mod == 2 then Mask = "0xFF0000" elseif Mod == 3 then Mask = "0xFF000000" end if IsNumber(Amount) then rstr = string.format("MemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Comparison, Amount * math.pow(256, Mod), Mask) else rstr = string.format("MemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Comparison, Amount .. " * " .. math.pow(256, Mod), Mask) end else if Comparison == 0 then rstr = string.format("bread(%s) >= %s", offset, Amount) elseif Comparison == 1 then rstr = string.format("bread(%s) <= %s", offset, Amount) elseif Comparison == 10 then rstr = string.format("bread(%s) == %s", offset, Amount) end end echo(rstr) end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer ]================================] function GetTech(Tech, Player) --ํ…Œํฌ/Tech,TrgPlayer/[Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. Tech = ParseTechdata(Tech) Player = ParsePlayer(Player) offset = TechOffset(Tech, Player) if IsNumber(offset) then rstr = string.format("bread(0x%X)", offset) else rstr = string.format("bread(%s)", offset) end echo(rstr) end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer ]================================] function TechOffset(Tech, Player) --ํ…Œํฌ/Tech,TrgPlayer/[Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. --์ผ๋ฐ˜/58D2B0 0 ~ 45 --์ผ๋ฐ˜/58F32C 46 Tech = ParseTechdata(Tech) + 0 Player = ParsePlayer(Player) Size = 0 if Tech <= 23 then offset = 0x58CF44 Size = 24 else offset = 0x58F140 Size = 20 end if IsNumber(Player) then offset = offset + Player * Size + Tech return offset else offset = string.format("0x%X + %s * %s + %s", offset, Player, Tech) return offset end end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์„ [Amount]๋งŒํผ [Modifier]ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Modifier.TrgModifier @param.Amount.Number @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์„ [Amount]๋งŒํผ [Modifier]ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Modifier.TrgModifier @param.Amount.Number ]================================] function SetTechMax(Tech, Player, Modifier, Amount) --ํ…Œํฌ/Tech,TrgPlayer,TrgModifier,Number/[Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์„ [Amount]๋งŒํผ [Modifier]ํ•ฉ๋‹ˆ๋‹ค. Tech = ParseTechdata(Tech) Player = ParsePlayer(Player) Modifier = ParseModifier(Modifier) offset = TechOffsetMax(Tech, Player) if IsNumber(offset) then Mod = offset % 4 ROffset = offset - Mod if Mod == 0 then Mask = "0xFF" elseif Mod == 1 then Mask = "0xFF00" elseif Mod == 2 then Mask = "0xFF0000" elseif Mod == 3 then Mask = "0xFF000000" end if IsNumber(Amount) then rstr = string.format("SetMemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Modifier, Amount * math.pow(256, Mod), Mask) else rstr = string.format("MemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Modifier, Amount .. " * " .. math.pow(256, Mod), Mask) end else if Modifier == 7 then rstr = string.format("bwrite(%s, %s)", offset, Amount) elseif Modifier == 8 then rstr = string.format("bwrite(%s, bread(%s) + %s)", offset, offset, Amount) elseif Modifier == 9 then rstr = string.format("bwrite(%s, bread(%s) - %s)", offset, offset, Amount) end end echo(rstr) end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์ด [Comparison] [Amount]์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Comparison.TrgComparison @param.Amount.Number @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์ด [Comparison] [Amount]์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @param.Comparison.TrgComparison @param.Amount.Number ]================================] function CurrentTechMax(Tech, Player, Comparison, Amount) --ํ…Œํฌ/Tech,TrgPlayer,TrgComparison,Number/[Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์ด [Comparison] [Amount]์ธ์ง€ ํ™•์ธํ•ฉ๋‹ˆ๋‹ค. Tech = ParseTechdata(Tech) Player = ParsePlayer(Player) Comparison = ParseComparison(Comparison) offset = TechOffsetMax(Tech, Player) if IsNumber(offset) then Mod = offset % 4 ROffset = offset - Mod if Mod == 0 then Mask = "0xFF" elseif Mod == 1 then Mask = "0xFF00" elseif Mod == 2 then Mask = "0xFF0000" elseif Mod == 3 then Mask = "0xFF000000" end if IsNumber(Amount) then rstr = string.format("MemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Comparison, Amount * math.pow(256, Mod), Mask) else rstr = string.format("MemoryXEPD(EPD(0x%X), %s, 0x%X, %s)", ROffset, Comparison, Amount .. " * " .. math.pow(256, Mod), Mask) end else if Comparison == 0 then rstr = string.format("bread(%s) >= %s", offset, Amount) elseif Comparison == 1 then rstr = string.format("bread(%s) <= %s", offset, Amount) elseif Comparison == 10 then rstr = string.format("bread(%s) == %s", offset, Amount) end end echo(rstr) end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer ]================================] function GetTechMax(Tech, Player) --ํ…Œํฌ/Tech,TrgPlayer/[Player]์˜ [Tech]์˜ ์ตœ๋Œ€๊ฐ’์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. Tech = ParseTechdata(Tech) Player = ParsePlayer(Player) offset = TechOffsetMax(Tech, Player) if IsNumber(offset) then rstr = string.format("bread(0x%X)", offset) else rstr = string.format("bread(%s)", offset) end echo(rstr) end --[================================[ @Language.ko-KR @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer @Language.us-EN @Summary [Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. @Group ํ…Œํฌ @param.Tech.Tech @param.Player.TrgPlayer ]================================] function TechOffsetMax(Tech, Player) --ํ…Œํฌ/Tech,TrgPlayer/[Player]์˜ [Tech]์˜ ํ˜„์žฌ๊ฐ’ ์ฃผ์†Œ๋ฅผ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค. --์ผ๋ฐ˜/58D088 0 ~ 45 --์ผ๋ฐ˜/58F278 46 Tech = ParseTechdata(Tech) + 0 Player = ParsePlayer(Player) if Tech <= 23 then offset = 0x58CE24 Size = 24 else offset = 0x58F050 Size = 20 end return offset end