content
stringlengths
5
1.05M
--------------------------------------------------------------------------------------------------- -- Proposal:https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0249-Persisting-HMI-Capabilities-specific-to-headunit.md -- -- Description: Check that SDL updates "hmi_capabilities_cache.json" file if HMI sends -- TTS/VR/UI.OnLanguageChange notification with appropriate language -- -- Preconditions: -- 1 Value of HMICapabilitiesCacheFile parameter is defined (hmi_capabilities_cache.json) in smartDeviceLink.ini file -- 2. HMI capabilities cache file (hmi_capabilities_cache.json) doesn't exist on file system -- 3. SDL and HMI are started -- 4. HMI sends all HMI capabilities to SDL -- 5. SDL persists capabilities to HMI capabilities cache file (hmi_capabilities_cache.json) in AppStorageFolder -- Sequence: -- 1. HMI sends "TTS/VR/UI.OnLanguageChange" notifications with language to SDL -- a. SDL overrides TTS/VR/UI.language in HMI capabilities cache file (hmi_capabilities_cache.json) --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local common = require('test_scripts/Capabilities/PersistingHMICapabilities/common') --[[ Local Variables ]] local language = { "FR-FR", "DE-DE", "EN-US" } --[[ Scenario ]] common.Title("Preconditions") common.Step("Clean environment", common.preconditions) common.Step("Start SDL, HMI", common.start, { common.updateHMILanguageCapability("EN-US") }) common.Title("Test") for _, pLanguage in pairs(language) do common.Step("OnLanguageChange notification " .. pLanguage , common.changeLanguage, { pLanguage }) common.Step("Check stored value to cache file", common.checkLanguageCapabilityInCache, { pLanguage }) end common.Title("Postconditions") common.Step("Stop SDL", common.postconditions)
DefineClass.Milestone = { __parents = { "Preset" }, properties = { { id = "display_name", name = T(1153, "Display Name"), editor = "text", default = "", translate = true, }, { id = "base_score", name = T(1154, "Base Score"), editor = "number", default = 1000, }, { id = "bonus_score", name = T(1155, "Bonus Score"), editor = "number", default = 1000, }, { id = "bonus_score_expiration", name = T(1156, "Bonus score expiration Sols"), editor = "number", default = 10, }, { id = "reward_research", name = T(11714, "Reward (RP)"), editor = "number", default = 250, }, { id = "trigger_fireworks", name = T(11412, "Trigger fireworks"), editor = "bool", default = false, }, { id = "Complete", name = T(1157, "Complete thread"), editor = "func" }, { id = "GetScore", name = T(1158, "Custom score"), editor = "func", }, }, PropertyTranslation = true, HasSortKey = true, EditorMenubarName = "Milestones", EditorMenubar = "Editors.Game", } function Milestone:Complete() print("Milestone without a complete func", self.id) end -- nil means not-yet, false means failed, X means completed with score X function Milestone:GetScore() local time = MilestoneCompleted[self.id] local expiration_days = self.bonus_score_expiration -- give full score on day 1 return time and (self.base_score + Max(0, MulDivTrunc(self.bonus_score, expiration_days - (TimeToDayHour(time) - 1), expiration_days))) end function Milestone:GetChallengeScore() local score = self:GetScore() return score and MulDivRound(score, ChallengeRating, 100) end -- nil means not-yet, false means failed, X means completed on sol X function Milestone:CompleteSol(milestone) local time = MilestoneCompleted[self.id] return time and ((time + City.hour * const.HourDuration) / const.DayDuration + 1) end function Milestone:GetCompleteText() local sol = self:CompleteSol() if sol then return T{1159, "<display_name> - Sol <sol>", self, sol = sol} elseif sol == false then local enactor = MilestoneEnactors[self.id] if enactor and enactor ~= UICity then return T{11675, "<display_name> - <enactor>", self, enactor = enactor.display_name} end end return self.display_name end GlobalVar("MilestoneCompleted", {}) GlobalVar("MilestoneThreads", {}) GlobalVar("MilestoneEnactors", {}) GlobalVar("ChallengeRating", 100) function OnMsg.NewDay() -- update challenge raiting in case it was affcted by later events ChallengeRating = 100 + CalcChallengeRating() end function MilestoneRestartThreads() if g_Tutorial then return end local all_milestones = {} local completed_milestones = {} local score_sum = 0 for _, milestone in ipairs(Presets.Milestone.Default) do local id = milestone.id if MilestoneCompleted[id] == nil then DeleteThread(MilestoneThreads[id]) completed_milestones[id] = true MilestoneThreads[id] = CreateGameTimeThread(function(id) local milestone = Presets.Milestone.Default[id] local res = milestone:Complete(UICity) MilestoneThreads[id] = nil if milestone and MilestoneCompleted[id] ~= false then -- some milestones might have disappeared (loadgame after patch) or could have already been failed all_milestones[id] = true MilestoneCompleted[id] = res and GameTime() or false MilestoneEnactors[id] = UICity Msg("MilestoneCompleted", id) if res then AddOnScreenNotification("MilestoneComplete", function() OpenDialog("Milestones") end, { display_name = milestone.display_name, reward_research = milestone.reward_research, score = milestone:GetScore() }) if milestone.trigger_fireworks then TriggerFireworks() end score_sum = score_sum + milestone:GetScore() local sponsor = GetMissionSponsor() local commander = GetCommanderProfile() if id == "Evaluation" and sponsor.goal == "" then WaitPopupNotification(sponsor.goal_completed_message, { params = { sponsor_name = sponsor.display_name, commander_profile = commander.display_name, score = milestone:GetScore() } }) end if #completed_milestones > 0 and #completed_milestones == #all_milestones then WaitPopupNotification("AllMilestonesCompleted", { params = { sponsor = sponsor.display_name, commander = commander.display_name, sol = UICity.day, score = score_sum } }) end end ObjModified(MilestoneCompleted) end end, id) end end end function OnMsg.GameTimeStart() MilestoneRestartThreads() end -- start threads for milestones that may have appeared after the game was saved -- restart all others to test if they work if started later function OnMsg.LoadGame() MilestoneRestartThreads() end GlobalVar("g_PopulationHighWatermark", 0) function UpdatePopulationHighWatermark() CreateGameTimeThread(function() local population = #(UICity.labels.Colonist or empty_table) if population > g_PopulationHighWatermark then g_PopulationHighWatermark = population Msg("PopulationHighWatermark") end end) end OnMsg.ColonistArrived = UpdatePopulationHighWatermark OnMsg.ColonistBorn = UpdatePopulationHighWatermark function Milestone_Population(pop) while true do if g_PopulationHighWatermark >= pop then return true end WaitMsg("PopulationHighWatermark") end end function Milestone_Building(class) while true do local ok, bld = WaitMsg("ConstructionComplete") if ok and (bld:IsKindOf(class) or bld.template_name == class) then return true end end end function Milestone_Wonder() while true do local ok, bld = WaitMsg("ConstructionComplete") if ok and BuildingTemplates[bld.template_name] and BuildingTemplates[bld.template_name].wonder then return true end end end function Milestone_AllSectorsScanned() local n = const.SectorCount while true do WaitMsg("SectorScanned") local scanned = true for x = 1, n do if not scanned then break end for y = 1, n do if g_MapSectors[x][y].status == "unexplored" then scanned = false break end end end if scanned then return true end end end function Milestone_WorkshopWorkersPercent(city, percent) while true do Sleep(5000) if city and city:GetWorkshopWorkersPercent() >= percent then return true end end end function OnMsg.MilestoneCompleted(milestone_id) local enactor = MilestoneEnactors[milestone_id] local research = Presets.Milestone.Default[milestone_id].reward_research if enactor == UICity then GrantResearchPoints(research) else enactor.resources.research = enactor.resources.research + research end end
return { armblastwing = { acceleration = 0.142, blocking = false, brakerate = 0.385, buildcostenergy = 1370, buildcostmetal = 75, builder = false, buildpic = "armblastwing.dds", buildtime = 2150, canattack = true, canfly = true, canguard = true, canmove = true, canpatrol = true, category = "ALL MOBILE VTOL", collide = false, cruisealt = "32", description = "Kamikaze EMP Bomb Drone", downloadable = 1, explodeas = "armblastwing", firestandorders = 1, footprintx = 3, footprintz = 3, hoverattack = true, idleautoheal = 5, idletime = 1800, kamikaze = "1", kamikazedistance = "64", losemitheight = 3, maneuverleashlength = 80, mass = 75, maxdamage = 125, maxslope = 10, maxvelocity = 9, maxwaterdepth = 0, mobilestandorders = 1, name = "blastwing", noautofire = false, objectname = "armblastwing", selfdestructas = "armblastwing", selfdestructcountdown = 1, sightdistance = 400, standingfireorder = 2, standingmoveorder = 1, steeringmode = 1, turninplaceanglelimit = 360, turninplacespeedlimit = 5.94, turnrate = 1144, unitname = "armblastwing", usesmoothmesh = 0, customparams = { buildpic = "armblastwing.dds", faction = "ARM", }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { canceldestruct = "cancel2", underattack = "warning1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "vtolarmv", }, select = { [1] = "vtolarac", }, }, }, }
object_tangible_item_item_outbreak_tie_helmet_hidden_content = object_tangible_item_shared_item_outbreak_tie_helmet_hidden_content:new { } ObjectTemplates:addTemplate(object_tangible_item_item_outbreak_tie_helmet_hidden_content, "object/tangible/item/item_outbreak_tie_helmet_hidden_content.iff")
local vstruct = require('vstruct') local zlib = require('zlib') local function crc32(...) local c = zlib.crc32() for i = 1, select('#', ...) do c = zlib.crc32(c, select(i, ...)) end return c end local chunks = { IDAT = vstruct.compile('s'), IEND = vstruct.compile(''), IHDR = vstruct.compile([[> width: u4 height: u4 bitDepth: u1 colorType: u1 compressionMethod: u1 filterMethod: u1 interlaceMethod: u1 ]]), } local function toChunk(type, data) local str = chunks[type]:write('', data) local fmt = ('> u4 s4 s%d u4'):format(#str) return vstruct.write(fmt, '', { #str, type, str, crc32(type, str) }) end local function write(width, height, rgba) local t = {} table.insert(t, '\137PNG\r\n\26\n') table.insert( t, toChunk('IHDR', { width = width, height = height, bitDepth = 8, colorType = 6, compressionMethod = 0, filterMethod = 0, interlaceMethod = 0, }) ) local lines = {} for i = 1, height do table.insert(lines, '\0') table.insert(lines, rgba:sub((i - 1) * width * 4 + 1, i * width * 4)) end table.insert(t, toChunk('IDAT', { zlib.compress(table.concat(lines, '')) })) table.insert(t, toChunk('IEND', {})) return table.concat(t, '') end return { write = write, }
-- evp.h local EVP_PKEY_ALG_CTRL = require("resty.openssl.include.evp").EVP_PKEY_ALG_CTRL return { EVP_PKEY_CTRL_TLS_MD = EVP_PKEY_ALG_CTRL, EVP_PKEY_CTRL_TLS_SECRET = EVP_PKEY_ALG_CTRL + 1, EVP_PKEY_CTRL_TLS_SEED = EVP_PKEY_ALG_CTRL + 2, EVP_PKEY_CTRL_HKDF_MD = EVP_PKEY_ALG_CTRL + 3, EVP_PKEY_CTRL_HKDF_SALT = EVP_PKEY_ALG_CTRL + 4, EVP_PKEY_CTRL_HKDF_KEY = EVP_PKEY_ALG_CTRL + 5, EVP_PKEY_CTRL_HKDF_INFO = EVP_PKEY_ALG_CTRL + 6, EVP_PKEY_CTRL_HKDF_MODE = EVP_PKEY_ALG_CTRL + 7, EVP_PKEY_CTRL_PASS = EVP_PKEY_ALG_CTRL + 8, EVP_PKEY_CTRL_SCRYPT_SALT = EVP_PKEY_ALG_CTRL + 9, EVP_PKEY_CTRL_SCRYPT_N = EVP_PKEY_ALG_CTRL + 10, EVP_PKEY_CTRL_SCRYPT_R = EVP_PKEY_ALG_CTRL + 11, EVP_PKEY_CTRL_SCRYPT_P = EVP_PKEY_ALG_CTRL + 12, EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES = EVP_PKEY_ALG_CTRL + 13, EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND = 0, EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY = 1, EVP_PKEY_HKDEF_MODE_EXPAND_ONLY = 2, }
include('shared.lua') print("pd_bank/cl_init.lua") function ENT:drawBankInfo() surface.SetDrawColor(Colours.filla) surface.DrawRect(32, 0, 508, 164) draw.SimpleTextOutlined( "Government", "Common_Font_86", 286, 0, Colours.text, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 2, Colours.outline) draw.SimpleTextOutlined( "Bank Vault", "Common_Font_86", 286, 68, Colours.text, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 2, Colours.outline) surface.SetDrawColor(Colours.filla) surface.DrawRect(32, 180, 508, 135) draw.SimpleTextOutlined( "City Income:", "Common_Font_38", 64, 180, Colours.text, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 2, Colours.outline) draw.SimpleTextOutlined( "+"..DarkRP.formatMoney(self:GetCityIncome() or 0), "Common_Font_38", 508, 180, Colours.positive, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP, 2, Colours.outline) draw.SimpleTextOutlined( "Police Expense:", "Common_Font_38", 64, 225, Colours.text, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 2, Colours.outline) draw.SimpleTextOutlined( "-"..DarkRP.formatMoney(self:GetPoliceExpense() or 0), "Common_Font_38", 508, 225, Colours.negative, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP, 2, Colours.outline) draw.SimpleTextOutlined( "Total Profit:", "Common_Font_38", 64, 270, Colours.text, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 2, Colours.outline) local totalProfit = (self:GetTotalProfit() or 0) local cashCol = Colours.positive local modifierStr = "+" if totalProfit == 0 then cashCol = Colours.neutral modifierStr = "" elseif totalProfit < 0 then cashCol = Colours.negative totalProfit = -totalProfit modifierStr = "-" end draw.SimpleTextOutlined( modifierStr..DarkRP.formatMoney(totalProfit), "Common_Font_38", 508, 270, cashCol, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP, 2, Colours.outline) surface.SetDrawColor(Colours.filla) surface.DrawRect(32, 331, 508, 45) draw.SimpleTextOutlined( "Cash Stored:", "Common_Font_38", 64, 331, Colours.text, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP, 2, Colours.outline) draw.SimpleTextOutlined( DarkRP.formatMoney(self:GetCashStored() or 0), "Common_Font_38", 508, 331, Colours.text, TEXT_ALIGN_RIGHT, TEXT_ALIGN_TOP, 2, Colours.outline) surface.SetDrawColor(Colours.filla) surface.DrawRect(32, 392, 508, 120) local robStatus = self:GetRobState() if robStatus == ROBSTATE_ROBBABLE then draw.SimpleTextOutlined( "The Bank can be robbed!", "Common_Font_46", 286, 425, Colours.text, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 2, Colours.outline) elseif robStatus == ROBSTATE_COOLDOWN then draw.SimpleTextOutlined( "Bank can be robbed in:", "Common_Font_46", 286, 400, Colours.text, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 2, Colours.outline) elseif robStatus == ROBSTATE_BEINGROBBED then draw.SimpleTextOutlined( "The Bank is being robbed!", "Common_Font_46", 286, 400, Colours.negative, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 2, Colours.outline) end if robStatus == ROBSTATE_COOLDOWN or robStatus == ROBSTATE_BEINGROBBED then local minutes = ""..math.floor(self:GetRobTimer()/60) if #minutes == 1 then minutes = "0"..minutes end local seconds = ""..math.floor(self:GetRobTimer()%60) if #seconds == 1 then seconds = "0"..seconds end local tmpCol = Colours.text if robStatus == ROBSTATE_BEINGROBBED then tmpCol = Colours.negative end draw.SimpleTextOutlined( minutes..":"..seconds, "Common_Font_46", 286, 450, tmpCol, TEXT_ALIGN_CENTER, TEXT_ALIGN_TOP, 2, Colours.outline) end end function ENT:Draw() self:DrawModel() -- width,height = 572,572 half:286 cam.Start3D2D(self:LocalToWorld(Vector(31.5,-29.6,61.5)), self:LocalToWorldAngles(Angle(0,90,90)), 0.1) self:drawBankInfo() cam.End3D2D() --[[ local cornerMult = 1.2 local locCorner = Vector(self:OBBMaxs().x*cornerMult,self:OBBMaxs().y*cornerMult,self:OBBMaxs().z*cornerMult) local positiveCorner = self:LocalToWorld(locCorner) local negativeCorner = self:LocalToWorld(Vector(locCorner.x*-1,locCorner.y*-1,0)) cam.Start3D(EyePos(), EyeAngles()) render.SetMaterial(Material("particle/Particle_Glow_05")) render.DrawQuadEasy(positiveCorner, EyeAngles():Forward() * -1, 64, 64, Colours.positive, 90) render.DrawQuadEasy(negativeCorner, EyeAngles():Forward() * -1, 64, 64, Colours.positive, 90) cam.End3D()]] end net.Receive("SendPlayerNotifMessage",function(len) chat.AddText(unpack(net.ReadTable())) end)
--[[ TheNexusAvenger Class representing a view for adding files. --]] local NexusGit = require(script.Parent.Parent.Parent.Parent):GetContext(script) local GitAddRequest = NexusGit:GetResource("NexusGitRequest.PostRequest.GitAddRequest") local Directory = NexusGit:GetResource("NexusGitRequest.File.Directory") local NexusWrappedInstance = NexusGit:GetResource("NexusPluginFramework.Base.NexusWrappedInstance") local FileSelectionFrame = NexusGit:GetResource("UI.Frame.FileSelection.FileSelectionFrame") local NexusEnums = NexusGit:GetResource("NexusPluginFramework.Data.Enum.NexusEnumCollection").GetBuiltInEnums() local GitAddView = NexusWrappedInstance:Extend() GitAddView:SetClassName("GitAddView") GitAddView:Implements(NexusGit:GetResource("UI.View.Frame.IViewFrame")) --[[ Creates an git add view object. --]] function GitAddView:__new(Files,Host) self:InitializeSuper("Frame") --Store the host. self:__SetChangedOverride("Host",function() end) self.Host = Host --Create the list frame. local FilterdFiles = Directory.FilterFiles(Files,{NexusEnums.FileStatus.Untracked}) local ListFrame = FileSelectionFrame.new(FilterdFiles) ListFrame.BorderSizePixel = 1 ListFrame.Size = UDim2.new(1,0,1,-30) ListFrame.Parent = self self:__SetChangedOverride("ListFrame",function() end) self.ListFrame = ListFrame --Create the buttons. local CancelButton = NexusWrappedInstance.GetInstance("TextButton") CancelButton.Size = UDim2.new(0,84,0,22) CancelButton.Position = UDim2.new(1,-88,1,-26) CancelButton.BackgroundColor3 = "DialogButton" CancelButton.TextColor3 = "DialogButtonText" CancelButton.Text = "Cancel" CancelButton.Parent = self self:__SetChangedOverride("CancelButton",function() end) self.CancelButton = CancelButton local AddButton = NexusWrappedInstance.GetInstance("TextButton") AddButton.Size = UDim2.new(0,84,0,22) AddButton.Position = UDim2.new(1,-176,1,-26) AddButton.BackgroundColor3 = "DialogMainButton" AddButton.TextColor3 = "DialogMainButtonText" AddButton.Text = "Add" AddButton.Parent = self self:__SetChangedOverride("AddButton",function() end) self.AddButton = AddButton --Set up the clicked events. local DB = true AddButton.MouseButton1Down:Connect(function() if DB then DB = false self.object:AddFiles(ListFrame:GetSelectedFiles()) end end) CancelButton.MouseButton1Down:Connect(function() if DB then DB = false self.object:Close() end end) end --[[ Sends a git request to add a file. --]] function GitAddView:SendAddRequest(Files) GitAddRequest.new(self.Host,Files):SendRequest() end --[[ Sends add requests to the server. --]] function GitAddView:AddFiles(SelectedFiles) --Convert the files to a list. local FilesList = {} --[[ Adds a file to the list. --]] local function AddFileToList(File,FileBase) if FileBase ~= "" then FileBase = FileBase.."/" end FileBase = FileBase..File:GetFileName() if File:IsA("Directory") then for _,SubFile in pairs(File:GetFiles()) do AddFileToList(SubFile,FileBase) end else table.insert(FilesList,FileBase) end end --Add the files. for _,File in pairs(SelectedFiles) do AddFileToList(File,"") end --Send the network requests to add the files. local Worked,Return = pcall(function() for i,FileString in pairs(FilesList) do self:UpdateAddStatus((i - 1)/#FilesList,"Adding "..tostring(FileString).."...") self:SendAddRequest({FileString}) end end) --Show either a success or failure. if Worked then if #FilesList == 1 then self:UpdateAddStatus(true,"1 file is now tracked.") else self:UpdateAddStatus(true,tostring(#FilesList).." files are now tracked.") end else self:UpdateAddStatus(false,"Add failed.") warn("Add request failed because "..tostring(Return)) end end --[[ Updates the status of the add. --]] function GitAddView:UpdateAddStatus(Percent,StatusText) if self ~= self.object then self.object:UpdateAddStatus(Percent,StatusText) end end --[[ Closes the view. --]] function GitAddView:Close() self:Destroy() end return GitAddView
function Log (msg) DebugPrint ( '[zonecontrol/test] ' .. msg ) end -- Taken from bb template if ZoneControlTest == nil then Log('zone control tester is enabled!!' ) Log('zone control tester is enabled!!' ) Log('zone control tester is enabled!!' ) ZoneControlTest = class({}) end function ZoneControlTest:Init () Log('starting up zone control tests') ZoneControlTest.lockIn = ZoneControl:CreateZone('lock_in', { mode = ZONE_CONTROL_EXCLUSIVE_IN, players = { [0] = true, [1] = true, [2] = true, [3] = true, [4] = true, [5] = true, [6] = true, [7] = true, [8] = true, [9] = true } }) ZoneControlTest.lockOut = ZoneControl:CreateZone('lock_out', { mode = ZONE_CONTROL_EXCLUSIVE_OUT, players = { [0] = true, [1] = true, [2] = true, [3] = true, [4] = true, [5] = true, [6] = true, [7] = true, [8] = true, [9] = true } }) ZoneControl:DisableZone(ZoneControlTest.lockIn) -- ZoneControl:DisableZone(ZoneControlTest.lockOut) ChatCommand:LinkCommand("-enable_lock_in", Dynamic_Wrap(ZoneControlTest, "EnableLockIn"), ZoneControlTest) ChatCommand:LinkCommand("-enable_lock_out", Dynamic_Wrap(ZoneControlTest, "EnableLockOut"), ZoneControlTest) end function ZoneControlTest:EnableLockIn () Log('Enabling lock in!') local lockIn = ZoneControlTest.lockIn local lockOut = ZoneControlTest.lockOut lockOut.disable() lockIn.enable() end function ZoneControlTest:EnableLockOut () Log('Enabling lock out!') local lockIn = ZoneControlTest.lockIn local lockOut = ZoneControlTest.lockOut lockIn.disable() lockOut.enable() end
RegisterNetEvent('chatCommandEntered') local guiEnabled = false function DisplayNotification(text) SetNotificationTextEntry("STRING") AddTextComponentString(text) DrawNotification(false, false) end function PrintChatMessage(text) TriggerEvent('chatMessage', "system", { 255, 0, 0 }, text) end function EnableGui(enable) SetNuiFocus(enable) guiEnabled = enable SendNUIMessage({ type = "enableui", enable = enable }) end AddEventHandler('chatCommandEntered', function(commands, player) PrintChatMessage(json.encode(commands)) if commands[1] == "/test" then EnableGui(true) end end) RegisterNUICallback('escape', function(data, cb) EnableGui(false) cb('ok') end) RegisterNUICallback('login', function(data, cb) PrintChatMessage(data.username .. " - " .. data.password) cb('ok') end) Citizen.CreateThread(function() while true do if guiEnabled then DisableControlAction(0, 1, guiEnabled) -- LookLeftRight DisableControlAction(0, 2, guiEnabled) -- LookUpDown DisableControlAction(0, 142, guiEnabled) -- MeleeAttackAlternate DisableControlAction(0, 106, guiEnabled) -- VehicleMouseControlOverride if IsDisabledControlJustReleased(0, 142) then -- MeleeAttackAlternate SendNUIMessage({ type = "click" }) end end Citizen.Wait(0) end end)
-- Implement static global utiity functions function write ( sText ) io.write(sText) end function clear ( ) if os.getenv("TERM") then os.execute("clear") end end -- Load a table from a file function table.load ( sPath ) local func,err = loadfile(tostring(sPath)) if err then return nil end return func() end -- Copy a table. 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
return { require("plugin/misc/comment"), require("plugin/misc/nvim_notify"), { "moll/vim-bbye" }, { "tpope/vim-repeat" }, -- { "godlygeek/tabular" } }
--[[ Author: MouJiaoZi Email: moujiaozi@gmail.com / ww64646464@vip.qq.com usage: To set an ability as charge-type: AbilityChargeController:AbilityChargeInitialize(hAbility, fChargeTime, iMaxCharges, iChargeCost, bResetByRefresh, bCDR) hAbility: the ability you want to set fChargeTime: the cooldown of charge iMaxCharges: the maximum charge points iChargeCost(optional): the cost of the ability, eg set it to 2 will cost 2 point when trigger cost bResetByRefresh(optional): should we set the ability to full points when use refresher or tinker's rearm bCDR(optional): if this charge can reduce the charge time by CoolDown Reduction To trigger the ability's cost: bool AbilityChargeController:CostCharge(hAbility, iCost, bIncreaseType) hAbility: the ability you want to trigger the cost iCost(optional): how many cost do you want to spend? default is the iChargeCost set by AbilityChargeInitialize function this can be a negative number, to increase the charge point bIncreaseType(optional x 2): if you set iCost a negative number, this will determin how we increase the charges if it's true, then we will remove the cooldown buffs which is the longest duration if it's false, we will remove that shortest buffs **IMPORTANT** this function will return a bool to let you know if it runs successfully, if it returns false, that means no hAbility recieved or no enough charge to cost, if it returns true, all work fine! you needn't to get this bool studiously, when there is no charge, the ability will go into cooldown automatically **IMPORTANT** To change the setting of a charge-type ability: AbilityChargeController:ChangeChargeAbilityConfig(hAbility, fChargeTime, iMaxCharges, iChargeCost, bResetByRefresh, bCDR) same as AbilityChargeInitialize function, but only hAbility is necessary, others are all optional if set one, it will overwrite previous setting API: bool AbilityChargeController:IsChargeTypeAbility(hAbility) : is this ability a charge-type ability? handle AbilityChargeController:GetChargeModifier(hAbility) : Get an ability's charge controller modifier, the abiliy must be a charge-type ability firstly in this way you can get this charge-type ability's setting, all are in below: handle buff.ability handle buff.caster float buff.chargetime int buff.maxcharges int buff.chargecost bool buff.refresh bool buff.getcdr ]] AbilityChargeController = AbilityChargeController or class({}) LinkLuaModifier("modifier_imba_ability_charge", "libraries/abilitychargecontroller.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("modifier_imba_ability_charge_cd_dummy", "libraries/abilitychargecontroller.lua", LUA_MODIFIER_MOTION_NONE) modifier_imba_ability_charge = modifier_imba_ability_charge or class({}) modifier_imba_ability_charge_cd_dummy = modifier_imba_ability_charge_cd_dummy or class({}) function modifier_imba_ability_charge:IsDebuff() return false end function modifier_imba_ability_charge:IsHidden() return false end function modifier_imba_ability_charge:IsPurgable() return false end function modifier_imba_ability_charge:IsPurgeException() return false end function modifier_imba_ability_charge:IsStunDebuff() return false end function modifier_imba_ability_charge:RemoveOnDeath() return false end function modifier_imba_ability_charge:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end function modifier_imba_ability_charge:DestroyOnExpire() return false end function modifier_imba_ability_charge:OnCreated(keys) self.ability = self:GetAbility() self.caster = self:GetCaster() self.chargetime = keys.chargetime self.maxcharges = keys.maxcharges self.chargecost = keys.chargecost if keys.refresh == 1 then self.refresh = true else self.refresh = false end if keys.getcdr == 1 then self.getcdr = true else self.getcdr = false end self:StartIntervalThink(0.1) end function modifier_imba_ability_charge:OnIntervalThink() if not self.caster:HasAbility(self.ability:GetAbilityName()) then self:Destroy() end if self:GetStackCount() > self.maxcharges then self:SetStackCount(self.maxcharges) end local cd_buff_number = 0 local my_cd_buff = {} local cd_buffs = self.caster:FindAllModifiersByName("modifier_imba_ability_charge_cd_dummy") for _, cd_buff in pairs(cd_buffs) do if cd_buff.ability == self.ability then cd_buff_number = cd_buff_number + 1 table.insert(my_cd_buff, cd_buff) end end local shortest_cd = 9999 for _,buff in pairs(my_cd_buff) do local duration = buff:GetRemainingTime() if duration < shortest_cd then shortest_cd = duration end end if cd_buff_number > 0 and self:GetDuration() == -1 then self:SetDuration(shortest_cd, true) end if cd_buff_number == 0 and self:GetDuration() ~= -1 then self:SetDuration(-1, true) end self:SetStackCount(math.max((self.maxcharges - cd_buff_number), 0)) if self.maxcharges - cd_buff_number > 0 then self.ability:EndCooldown() elseif self.ability:IsCooldownReady() or self.ability:GetCooldownTimeRemaining() > self:GetRemainingTime()+0.2 then self.ability:EndCooldown() self.ability:StartCooldown(self:GetRemainingTime()) end end function modifier_imba_ability_charge:DeclareFunctions() local funcs = { MODIFIER_EVENT_ON_ABILITY_FULLY_CAST } return funcs end function modifier_imba_ability_charge:OnAbilityFullyCast( keys ) if keys.unit == self.caster and keys.ability:GetAbilityName() == "item_refresher" or keys.ability:GetAbilityName() == "item_imba_refresher" or keys.ability:GetAbilityName() == "tinker_rearm" or keys.ability:GetAbilityName() == "imba_tinker_rearm" then if self.refresh then local cd_buffs = self.caster:FindAllModifiersByName("modifier_imba_ability_charge_cd_dummy") for _, cd_buff in pairs(cd_buffs) do if cd_buff.ability == self.ability then cd_buff:Destroy() end end end end end function modifier_imba_ability_charge_cd_dummy:IsDebuff() return false end function modifier_imba_ability_charge_cd_dummy:IsHidden() return true end function modifier_imba_ability_charge_cd_dummy:IsPurgable() return false end function modifier_imba_ability_charge_cd_dummy:IsPurgeException() return false end function modifier_imba_ability_charge_cd_dummy:IsStunDebuff() return false end function modifier_imba_ability_charge_cd_dummy:RemoveOnDeath() return false end function modifier_imba_ability_charge_cd_dummy:GetAttributes() return MODIFIER_ATTRIBUTE_MULTIPLE end function modifier_imba_ability_charge_cd_dummy:OnCreated() self.ability = self:GetAbility() end function modifier_imba_ability_charge_cd_dummy:OnDestroy() self.chargebuff:SetDuration(-1, true) end function AbilityChargeController:AbilityChargeInitialize(hAbility, fChargeTime, iMaxCharges, iChargeCost, bResetByRefresh, bCDR) if not hAbility or not fChargeTime or not iMaxCharges then print("parameter error! please check your code!!") return end if iChargeCost < 0 or iMaxCharges <= 0 or fChargeTime <= 0 then print("Number error, what are you doing?") return end local caster = hAbility:GetCaster() local bRefresh = 1 local bGetCDR = 0 if not bResetByRefresh or bResetByRefresh == true then bRefresh = 1 else bRefresh = 0 end if not bCDR or bCDR == false then bGetCDR = 0 else bGetCDR = 1 end local charge_buffs = caster:FindAllModifiersByName("modifier_imba_ability_charge") for _,charge_buff in pairs(charge_buffs) do if charge_buff.ability == hAbility then print("Already has charge buff!!") return nil end end caster:AddNewModifier(caster, hAbility, "modifier_imba_ability_charge", {chargetime = fChargeTime, maxcharges = iMaxCharges, chargecost = iChargeCost, refresh = bRefresh, getcdr = bGetCDR}) end function AbilityChargeController:CostCharge(hAbility, iCost, bIncreaseType) --bIncreaseType: true is destroy the longest duration buff, false is shortest, default is shortest. if not hAbility then return false end local ability = hAbility local caster = ability:GetCaster() local control_buffs = caster:FindAllModifiersByName("modifier_imba_ability_charge") local control_buff = nil for _, buff in pairs(control_buffs) do if buff.ability == ability then control_buff = buff break end end if not control_buff then print("No charge buff found! Does this ability have any charge?") return false end local cost = iCost or control_buff.chargecost local charge_time = control_buff.chargetime local current_charge = control_buff:GetStackCount() if cost >= 0 then if control_buff.getcdr then charge_time = charge_time * ((100 - caster:GetCooldownReduction()) / 100) end if current_charge >= cost then for i=1,cost do local cdbuff = caster:AddNewModifier(caster, ability, "modifier_imba_ability_charge_cd_dummy", {duration = charge_time}) cdbuff.chargebuff = control_buff end else return false end else -- cost<0 local incre = bIncreaseType or false cost = 0 - cost local cd_buff = {} local buffs = caster:FindAllModifiersByName("modifier_imba_ability_charge_cd_dummy") for _, buff in pairs(buffs) do if buff:GetAbility() == control_buff.ability then table.insert(cd_buff, buff) end end if control_buff.maxcharges - control_buff:GetStackCount() < cost then for _,buff in pairs(cd_buff) do buff:Destroy() end else if incre then for j=1,cost do local pin = 0 local longest = nil local longesttime = 0 for k=1, #cd_buff do if cd_buff[k]:GetRemainingTime() > longesttime then longesttime = cd_buff[k]:GetRemainingTime() longest = cd_buff[k] pin = k end end longest:Destroy() table.remove(cd_buff, pin) end else for j=1,cost do local pin = 0 local shortest = nil local shortesttime = 99999 for k=1, #cd_buff do if cd_buff[k]:GetRemainingTime() < shortesttime then shortesttime = cd_buff[k]:GetRemainingTime() shortest = cd_buff[k] pin = k end end shortest:Destroy() table.remove(cd_buff, pin) end end end end return true end function AbilityChargeController:ChangeChargeAbilityConfig(hAbility, fChargeTime, iMaxCharges, iChargeCost, bResetByRefresh, bCDR) if not hAbility then return end if not AbilityChargeController:IsChargeTypeAbility(hAbility) then print("Not a charge type ability!") return end local buff = AbilityChargeController:GetChargeModifier(hAbility) if iChargeCost < 0 or iMaxCharges <= 0 or fChargeTime <= 0 then print("Number error, what are you doing?") return end self.chargetime = fChargeTime or self.chargetime self.maxcharges = iMaxCharges or self.chargetime self.chargecost = iChargeCost or self.chargetime self.refresh = bResetByRefresh or self.chargetime self.getcdr = bCDR or self.chargetime end function AbilityChargeController:IsChargeTypeAbility(hAbility) if not hAbility then return end local ability = hAbility local caster = ability:GetCaster() local control_buffs = caster:FindAllModifiersByName("modifier_imba_ability_charge") local control_buff = nil for _, buff in pairs(control_buffs) do if buff.ability == ability then control_buff = buff return true end end return false end function AbilityChargeController:GetChargeModifier(hAbility) if not hAbility then return end if not AbilityChargeController:IsChargeTypeAbility(hAbility) then return nil end local ability = hAbility local caster = ability:GetCaster() local control_buffs = caster:FindAllModifiersByName("modifier_imba_ability_charge") local control_buff = nil for _, buff in pairs(control_buffs) do if buff.ability == ability then control_buff = buff return control_buff end end return nil end
local M = {} local function onVehicleSwitched(_, _, _) guihooks.trigger("_Radar_VehicleSwitch") end M.onVehicleSwitched = onVehicleSwitched return M
function test() c = a .. b end function test2() test() end test2()
local states = require("states") local button = require("button") local hexfieldModel = require("models/hexfieldModel") local overwrite = {} local filetointeract function overwrite.open(params) filetointeract = params.filetointeract end function overwrite.draw() love.graphics.setColor(1,1,1) love.graphics.setFont(largefont) love.graphics.printf("You are going to overwrite:\n"..filetointeract,width/2-200,height/2-100,400,"center") love.graphics.setFont(smallfont) button({x=width/3-75,y=height/2+100,width=150,height=50,lineWidth=3,text='OK'}) button({x=2*width/3-75,y=height/2+100,width=150,height=50,lineWidth=3,text='Cancel'}) button({x=width-225,y=height-125,width=150,height=50,lineWidth=3,text='Delete',colorBasic={120,0,0},colorHighlit={255,0,0}}) end function overwrite.keypressed(key,scancode) if key == "escape" then states.switch("map") end end function overwrite.mousepressed( x, y, button ) if button==1 and y<height/2+150 and y>height/2+100 and x>width/3-75 and x<width/3+75 then hexfieldModel.save(filetointeract) states.switch("map") elseif button==1 and y<height/2+150 and y>height/2+100 and x>2*width/3-75 and x<2*width/3+75 then states.switch("map") elseif button==1 and y<height-75 and y>height-125 and x>width-225 and x<width-75 then love.filesystem.remove("maps/"..filetointeract) states.switch("map") end end return overwrite
include("shared.lua") function ENT:Initialize() end local mat = Material("vgui/circle") local mat2 = Material("vgui/dashed_line") local mat3 = Material("stormfox/models/clock_mini_material") function ENT:Draw() render.MaterialOverrideByIndex( 0, mat3 ) self:DrawModel() render.MaterialOverrideByIndex( ) if ( halo.RenderedEntity() == self ) then return end if not StormFox then return end if not StormFox.GetTime then return end local t = StormFox.GetTime() local h = math.floor(t / 60) -- 0 - 24 local m = t - h * 60 -- 0 - 60 cam.Start3D2D(self:LocalToWorld(Vector(-1,0,0.5)),self:LocalToWorldAngles(Angle(0,270,90)),0.1) surface.SetMaterial(mat) surface.SetDrawColor(0,0,0) surface.DrawTexturedRect(-2,-2,4,4) surface.SetMaterial(mat2) -- hour arm local ang = h * 30 + m / 2 + 90 surface.DrawTexturedRectRotated(0,0,30,1,-ang) -- min arm local ang = m * 6 + 90 surface.DrawTexturedRectRotated(0,0,40,1,-ang) cam.End3D2D() cam.Start3D2D(self:LocalToWorld(Vector(1,0,0.5)),self:LocalToWorldAngles(Angle(0,90,90)),0.1) surface.SetMaterial(mat) surface.SetDrawColor(0,0,0) surface.DrawTexturedRect(-2,-2,4,4) surface.SetMaterial(mat2) -- hour arm local ang = h * 30 + m / 2 + 90 surface.DrawTexturedRectRotated(0,0,30,1,-ang) -- min arm local ang = m * 6 + 90 surface.DrawTexturedRectRotated(0,0,40,1,-ang) cam.End3D2D() end
----------------------------------- -- Area: Den of Rancor -- NPC: Lantern (SE) -- !pos -59 45 24 160 ----------------------------------- require("scripts/zones/Den_of_Rancor/globals") ----------------------------------- function onTrade(player,npc,trade) DEN_OF_RANCOR.onTradeLanternChamber(player, npc, trade) end function onTrigger(player,npc) DEN_OF_RANCOR.onTriggerLantern(player, npc) end
-- Meant for naval surface or submarine vehicles with yaw + propulsion -- control. -- Should have hydrofoils in front of and behind the CoM, otherwise use -- a different script (utility-ai.lua, utility.lua). -- Should have material gatherers and/or plenty of cargo space depending on -- configuration. -- CONFIGURATION -- Activate on these AI modes. Valid keys are "off", "on", "combat", -- "patrol", and "fleetmove". ActivateWhen = { -- on = true, combat = true, fleetmove = true, } -- How often to run. At 1, it will run every update. At 10, -- it will run every 10th update. The lower it is, the more -- responsive it will be, but it will also take more processing time. AI_UpdateRate = 4 DepthControl_UpdateRate = 4 DockManager_UpdateRate = nil ShieldManager_UpdateRate = nil
local bit = require "bit32" local masks = { "128.0.0.0", "192.0.0.0", "224.0.0.0", "240.0.0.0", "248.0.0.0", "252.0.0.0", "254.0.0.0", "255.0.0.0", "255.128.0.0", "255.192.0.0", "255.224.0.0", "255.240.0.0", "255.248.0.0", "255.252.0.0", "255.254.0.0", "255.255.0.0", "255.255.128.0", "255.255.192.0", "255.255.224.0", "255.255.240.0", "255.255.248.0", "255.255.252.0", "255.255.254.0", "255.255.255.0", "255.255.255.128", "255.255.255.192", "255.255.255.224", "255.255.255.240", "255.255.255.248", "255.255.255.252", "255.255.255.254", "255.255.255.255" } local bin_mask, bin_not_mask = {}, {} local function ip2octets(s) local a, b, c, d = string.match(s, "^(%d+)%.(%d+)%.(%d+)%.(%d+)$") a,b,c,d = tonumber(a),tonumber(b),tonumber(c),tonumber(d) if not a then return end if a > 255 or b > 255 or c > 255 or d > 255 then return end return a, b, c, d end local function ip2int(s) local a, b, c, d = ip2octets(s) if not a then return end return a * (256 ^ 3) + b * (256 ^ 2) + c * (256 ^ 1) + d end local tmp = {} local function int2ip(s) if s < 0 or s > 0xFFFFFFFF then return end for i = 4,1,-1 do tmp[i] = math.mod(s, 256); s = math.floor( s / 256 ); end return table.concat(tmp, '.') end for i = 1, #masks do bin_mask[i] = ip2int(masks[i]) bin_not_mask[i] = 0xFFFFFFFF - bin_mask[i] bin_mask[tostring(i)] = bin_mask[i] bin_not_mask[tostring(i)] = bin_not_mask[i] end local function cidr2range(s) local a, b, c, d, cidr = string.match(s, "^(%d+)%.(%d+)%.(%d+)%.(%d+)/(%d+)$") a,b,c,d = tonumber(a),tonumber(b),tonumber(c),tonumber(d) if not a then return end if a > 255 or b > 255 or c > 255 or d > 255 then return end local mask, not_mask = bin_mask[cidr], bin_not_mask[cidr] if not mask then return end local net = a * (256 ^ 3) + b * (256 ^ 2) + c * (256 ^ 1) + d local low, hi = bit.band(net, mask), bit.bor(net, not_mask) return low, hi end local function load_cidrs(s) local t = {ip={}} for i = 1, #s do local ip = ip2int(s[i]) if ip then t.ip[s[i]] = true else local low, hi = cidr2range(s[i]) if low then t[#t+1] = {low, hi, s[i]} end end end table.sort(t, function(lhs, rhs) if lhs[1] == rhs[1] then return lhs[2] < rhs[2] end return lhs[1] < rhs[1] end) return t end local function find_cidr(ip, s) if s.ip[ip] then return ip end local bin, i, n = ip2int(ip), 1, #s if bin then while (i <= n) and (bin >= s[i][1]) do if bin <= s[i][2] then return s[i][3] end i = i + 1 end end end local function cidr2mask(s) local ip = cidr2range(s) if not ip then return end local cidr = string.match(s, "^%d+%.%d+%.%d+%.%d+/(%d+)$") return int2ip(ip), masks[tonumber(cidr)] end return { load_cidrs = load_cidrs; cidr2mask = cidr2mask; cidr2range = cidr2mask; ip2int = ip2int; int2ip = int2ip; find_cidr = find_cidr; }
print(type("hello world")) print(type(print)) print(type(true)) print(type(360.0)) print(type(nil)) -- string -- function -- boolean -- number -- nil
local L = require( "lpeg" ) local LU = require( "adoc_cmd_ext.lpeg_util" ) local P = require( "adoc_cmd_ext.pattern" ) local U = require( "adoc_cmd_ext.util" ) -------------------------------------------------------------------------------- local function tokenize_table( adocFileStr ) local p = LU.list_pattern( P.cmdIns ) return p:match( adocFileStr ) or { adocFileStr } end local function scan_parameter_value( para ) local extractor = LU.extract_pattern( P.paraBegin, P.paraEnd ) local relevant = extractor:match( para ) if relevant == nil then return "" else return U.trim( relevant ) end end local function scan_command_instance( ins ) local p = L.Ct( L.P"/:" * L.C( P.cmdName ) * L.C( P.cmdInsPara )^1 ) local values = p:match( ins ) local name = values[ 1 ] local paras = U.slice( values, 2 ) local res = {} res.name = name res.para = {} for k,v in ipairs( paras ) do local i = scan_parameter_value( v ) table.insert( res.para, i ) end return res end local function scan_adoc( adocFileStr ) local t = tokenize_table( adocFileStr ) return U.modify_even_entries( t, function( e ) return scan_command_instance( e ) end ) end -------------------------------------------------------------------------------- -- Lua module with util functions that allow to scan an asciidoc file string -- with command instances in it. -- -- Function: scan_adoc -- The result structure of the main function scan_adoc is a table-array where -- on each odd position plain asciidoc is that will be not touched, and on each -- even position are table-objects that represent a command instance that should -- be replaced. -- -- Example: -- 1 = "This is a simple " -- 2 = { name = "topic", para = { "Example" } } -- 3 = " to show the power. " -- 3 = { name = "author", para = { "AIQ", "Alexander" } } -- 4 = "" -- -- The other functions are just public for the testing of the module interface -- and will be used internal from the scan_adoc function. -------------------------------------------------------------------------------- return { tokenize_table = tokenize_table, scan_parameter_value = scan_parameter_value, scan_command_instance = scan_command_instance, scan_adoc = scan_adoc }
UIMenuColouredItem = setmetatable({}, UIMenuColouredItem) UIMenuColouredItem.__index = UIMenuColouredItem UIMenuColouredItem.__call = function() return "UIMenuItem", "UIMenuColouredItem" end function UIMenuColouredItem.New(Text, Description, MainColour, HighlightColour) if type(Colour) ~= "table" then Colour = {R = 0, G = 0, B = 0, A = 255} end if type(HighlightColour) ~= "table" then Colour = {R = 255, G = 255, B = 255, A = 255} end local _UIMenuColouredItem = { Base = UIMenuItem.New(Text or "", Description or ""), Rectangle = UIResRectangle.New(0, 0, 431, 38, MainColour.R, MainColour.G, MainColour.B, MainColour.A), MainColour = MainColour, HighlightColour = HighlightColour, Activated = function(menu, item) end, } _UIMenuColouredItem.Base.SelectedSprite:Colour(HighlightColour.R, HighlightColour.G, HighlightColour.B, HighlightColour.A) return setmetatable(_UIMenuColouredItem, UIMenuColouredItem) end function UIMenuColouredItem:SetParentMenu(Menu) if Menu() == "UIMenu" then self.Base.ParentMenu = Menu else return self.Base.ParentMenu end end function UIMenuColouredItem:Position(Y) if tonumber(Y) then self.Base:Position(Y) self.Rectangle:Position(self.Base._Offset.X, Y + 144 + self.Base._Offset.Y) end end function UIMenuColouredItem:Selected(bool) if bool ~= nil then self.Base._Selected = tobool(bool) else return self.Base._Selected end end function UIMenuColouredItem:Hovered(bool) if bool ~= nil then self.Base._Hovered = tobool(bool) else return self.Base._Hovered end end function UIMenuColouredItem:Enabled(bool) if bool ~= nil then self.Base._Enabled = tobool(bool) else return self.Base._Enabled end end function UIMenuColouredItem:Description(str) if tostring(str) and str ~= nil then self.Base._Description = tostring(str) else return self.Base._Description end end function UIMenuColouredItem:Offset(X, Y) if tonumber(X) or tonumber(Y) then if tonumber(X) then self.Base._Offset.X = tonumber(X) end if tonumber(Y) then self.Base._Offset.Y = tonumber(Y) end else return self.Base._Offset end end function UIMenuColouredItem:Text(Text) if tostring(Text) and Text ~= nil then self.Base.Text:Text(tostring(Text)) else return self.Base.Text:Text() end end function UIMenuColouredItem:RightLabel(Text, MainColour, HighlightColour) if tostring(Text) and Text ~= nil then if type(MainColour) == "table" then self.Base.Label.MainColour = MainColour end if type(HighlightColour) == "table" then self.Base.Label.HighlightColour = HighlightColour end self.Base.Label.Text:Text(tostring(Text)) else return self.Base.Label.Text:Text() end end function UIMenuColouredItem:SetLeftBadge(Badge) if tonumber(Badge) then self.Base.LeftBadge.Badge = tonumber(Badge) end end function UIMenuColouredItem:SetRightBadge(Badge) if tonumber(Badge) then self.Base.RightBadge.Badge = tonumber(Badge) end end function UIMenuColouredItem:Draw() self.Rectangle:Size(431 + self.ParentMenu.WidthOffset, self.Rectangle.Height) self.Rectangle:Draw() self.Base:Draw() end
local Quality = {} --Quality.__index = Quality local qualityNames = { 'Common', -- 1 'Uncommon', -- 2 'Rare', -- 3 'Epic', -- 4 'Legendary', -- 5 } local qualityValues = { ['Common'] = 1, ['Uncommon'] = 2, ['Rare'] = 3, ['Epic'] = 4, ['Legendary'] = 5, } local qualityColors = { ['Common'] = 0xffcccccc, ['Uncommon'] = 0xff85ed1e, -- #1eed85 ['Rare'] = 0xffff9936, ['Epic'] = 0xffff42bd, -- #a537ff ['Legendary'] = 0xff3195fa, } --function Quality:new(value) -- local this = { value = value } -- -- setmetatable(this, self) -- -- return this --end function Quality.toName(value) return qualityNames[value] end function Quality.toValue(name) return qualityValues[name] end function Quality.maxValue() return #qualityNames end function Quality.toColor(name) return qualityColors[name] end function Quality.all() return qualityNames end function Quality.upTo(max) local list = {} for _, quality in ipairs(qualityNames) do table.insert(list, quality) if quality == max then break end end return list end function Quality.min(quality, max) if Quality.toValue(quality) > Quality.toValue(max) then return max end return quality end return Quality
local function _classify(z_A, z_B, ground_truth, thresh) local _classify_res = 1; if z_A - z_B > thresh then _classify_res = 1 elseif z_A - z_B < -thresh then _classify_res = -1 elseif z_A - z_B <= thresh and z_A - z_B >= -thresh then _classify_res = 0; end if _classify_res == ground_truth then return true else return false end end local function _count_correct(output, target, record) for point_idx = 1, target.n_point do x_A = target.x_A[point_idx] y_A = target.y_A[point_idx] x_B = target.x_B[point_idx] y_B = target.y_B[point_idx] z_A = output[{1, 1, y_A, x_A}] z_B = output[{1, 1, y_B, x_B}] assert(x_A ~= x_B or y_A ~= y_B) ground_truth = target.ordianl_relation[point_idx]; -- the ordinal_relation is in the form of 1 and -1 and 0 for tau_idx = 1 , record.n_thresh do if _classify(z_A, z_B, ground_truth, record.thresh[tau_idx]) then if ground_truth == 0 then record.eq_correct_count[tau_idx] = record.eq_correct_count[tau_idx] + 1; elseif ground_truth == 1 or ground_truth == -1 then record.not_eq_correct_count[tau_idx] = record.not_eq_correct_count[tau_idx] + 1; end end end if ground_truth == 0 then record.eq_count = record.eq_count + 1 elseif ground_truth == 1 or ground_truth == -1 then record.not_eq_count = record.not_eq_count + 1 end end end local _eval_record = {} _eval_record.n_thresh = 15; _eval_record.eq_correct_count = torch.Tensor(_eval_record.n_thresh ) _eval_record.not_eq_correct_count = torch.Tensor(_eval_record.n_thresh ) _eval_record.not_eq_count = 0; _eval_record.eq_count = 0; _eval_record.thresh = torch.Tensor(_eval_record.n_thresh ) _eval_record.WKDR = torch.Tensor(_eval_record.n_thresh , 4) for i = 1, _eval_record.n_thresh do _eval_record.thresh[i] = i * 0.1; end local function reset_record(record) record.eq_correct_count:fill(0) record.not_eq_correct_count:fill(0) record.WKDR:fill(0) record.not_eq_count = 0 record.eq_count = 0 -- print(record.eq_correct_count) -- print(record.not_eq_correct_count) -- print(record.not_eq_count) -- print(record.eq_count) -- io.read() end function evaluate( data_loader, model, criterion, max_n_sample ) print('>>>>>>>>>>>>>>>>>>>>>>>>> Valid Crit Threshed: Evaluating on validation set...'); print("Evaluate() Switch On!!!") model:evaluate() -- this is necessary -- reset the record reset_record(_eval_record) local total_validation_loss = 0; local n_iters = math.min(data_loader.n_relative_depth_sample, max_n_sample); local n_total_point_pair = 0; print(string.format("Number of samples we are going to examine: %d", n_iters)) for iter = 1, n_iters do -- Get sample one by one local batch_input, batch_target = data_loader:load_indices(torch.Tensor({iter}), nil) -- The the relative depth target. Since there is only one sample, we just take its first component. local relative_depth_target = batch_target[1] -- forward local batch_output = model:forward(batch_input) local batch_loss = criterion:forward(batch_output, batch_target); local output_depth = get_depth_from_model_output(batch_output) -- count the number of correct point pairs. _count_correct(output_depth, relative_depth_target, _eval_record) -- get relative depth loss total_validation_loss = total_validation_loss + batch_loss * relative_depth_target.n_point -- -- update the number of point pair n_total_point_pair = n_total_point_pair + relative_depth_target.n_point collectgarbage() end print("Evaluate() Switch Off!!!") model:training() local max_min = 0; local max_min_i = 1; for tau_idx = 1 , _eval_record.n_thresh do _eval_record.WKDR[{tau_idx, 1}] = _eval_record.thresh[tau_idx] _eval_record.WKDR[{tau_idx, 2}] = (_eval_record.eq_correct_count[tau_idx] + _eval_record.not_eq_correct_count[tau_idx]) / (_eval_record.eq_count + _eval_record.not_eq_count) _eval_record.WKDR[{tau_idx, 3}] = _eval_record.eq_correct_count[tau_idx] / _eval_record.eq_count _eval_record.WKDR[{tau_idx, 4}] = _eval_record.not_eq_correct_count[tau_idx] / _eval_record.not_eq_count if math.min(_eval_record.WKDR[{tau_idx,3}], _eval_record.WKDR[{tau_idx,4}]) > max_min then max_min = math.min(_eval_record.WKDR[{tau_idx,3}], _eval_record.WKDR[{tau_idx,4}]) max_min_i = tau_idx; end end print(_eval_record.WKDR) print(_eval_record.WKDR[{{max_min_i}, {}}]) print(string.format("\tEvaluation Completed. Loss = %f, WKDR = %f", total_validation_loss, 1 - max_min)) --Return the loss per point pair, and ERROR ratio return total_validation_loss / n_total_point_pair, 1 - max_min end
oxomoco = { core = require 'oxomoco.core', units = {} } --- Scientific notation with default base 10. -- Base can be changed (eg 1000 / 1024 for prefixes) oxomoco.units.scinot = function(value, base) base = base or 10 local mg = 0 repeat if value < 1 then mg = mg - 1 value = value * base elseif value > 10 then mg = mg + 1 value = value / base end until (1 < value) and (value < base) return value, mg end oxomoco.units.SI = { base = 1000, {-8,'y', 'yocto'}, {-7,'z', 'zepto'}, {-6,'a', 'atto'}, {-5,'f', 'femto'}, {-4,'p', 'pico'}, {-3,'n', 'nano'}, {-2,'µ', 'micro'}, {-1,'m', 'milli'}, {1, 'k', 'kilo'}, {2, 'M', 'mega'}, {3, 'G', 'giga'}, {4, 'T', 'tera'}, {5, 'P', 'peta'}, {6, 'E', 'exa'}, {7, 'Z', 'zetta'}, {8, 'Y', 'yotta'}, } oxomoco.units.IEC = { base = 1024, {1, 'Ki', 'kibi'}, {2, 'Mi', 'mebi'}, {3, 'Gi', 'gibi'}, {4, 'Ti', 'tebi'}, {5, 'Pi', 'pebi'}, {6, 'Ei', 'ebi'}, {7, 'Zi', 'zibi'}, {8, 'Yi', 'yibi'}, } oxomoco.units.prefix = function(number, digits, longForm, system) digits = digits or 3 system = system or oxomoco.units.SI longForm = longForm or false local value, mg = oxomoco.units.scinot(number, system.base) value = string.format('%.' .. tostring(digits) .. 'f', value) if system then for i, p in ipairs(system) do local magnitude, prefix, long = p if mg == magnitude then if longForm then prefix = long end return value .. ' ' .. prefix end end end return value .. '×' .. system.base .. '^' .. mg end oxomoco.units.scientific = function(number, digits) local value, mg = oxomoco.units.scinot(number, system.base) value = string.format('%.' .. tostring(digits) .. 'f', value) return value ..'×10^' .. mg end return oxomoco.units
VERSION = "1.0.1" MakeCommand("wc", "wc.wordCount", 0) function wordCount () buffer = CurView().Buf --Pulls working screen buffer from editor view charCount = buffer:len() --Finds length of buffer bufstr = tostring(buffer) local _ , wordCount = bufstr:gsub("%S+","") --Lua patterns, see: lua.org/pil/20.2.html messenger:Message("Words:"..wordCount.." Characters:"..charCount) end AddRuntimeFile("wc", "help", "help/wc.md") BindKey("F5", "wc.wordCount")
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ------------------ -- Guild Finder -- ------------------ ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_ENTRY_TEMPLATE = { COMBOBOX = 1, COMBOBOX_STATUS = 2, COMBOBOX_START_TIME = 3, COMBOBOX_END_TIME = 4, CHECKBOX = 5, CHECKBOX_END = 6, EDITBOX = 7, DESCRIPTION_EDITBOX = 8, ROLE_SELECTOR = 9, ROLE_SELECTOR_END = 10, SINGLE_LINE_EDITBOX = 11, } ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_NOT_LISTED_DIALOG_NAME = "GAMEPAD_GUILD_LISTING_NOT_LISTED_PROMPT" ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_UNLISTED_DIALOG_NAME = "GAMEPAD_GUILD_LISTING_UNLISTED_PROMPT" ZO_GuildRecruitment_GuildListing_Gamepad = ZO_Object.MultiSubclass(ZO_GuildRecruitment_GuildListing_Shared, ZO_GuildFinder_Panel_GamepadBehavior) function ZO_GuildRecruitment_GuildListing_Gamepad:New(...) return ZO_GuildFinder_Panel_GamepadBehavior.New(self, ...) end function ZO_GuildRecruitment_GuildListing_Gamepad:Initialize(control) local templateData = { gridListClass = ZO_GridScrollList_Gamepad, gridHighlightTemplate = "ZO_GuildRecruitment_GuildListing_Gamepad_Highlight_Template", headerTemplate = "ZO_GuildRecruitment_GuildListing_Gamepad_Header_Template", headerHeight = ZO_GRID_SCROLL_LIST_DEFAULT_HEADER_TEMPLATE_HEIGHT, gridPaddingY = 10, attributeSelection = { entryTemplate = "ZO_GuildRecruitment_AttributeSelectionTile_Gamepad_Control", dimensionsX = ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_COLUMN_WIDTH, dimensionsY = ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_COMBOBOX_ENTRY_HEIGHT, statusEntryTemplate = "ZO_GuildRecruitment_StatusSelectionTile_Gamepad_Control", startTimeEntryTemplate = "ZO_GuildRecruitment_StartTimeSelectionTile_Gamepad_Control", endTimeEntryTemplate = "ZO_GuildRecruitment_EndTimeSelectionTile_Gamepad_Control", startTimeDimensionsX = ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_START_TIME_COMBOBOX_ENTRY_WIDTH, timeDimensionsY = ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_COMBOBOX_ENTRY_HEIGHT, statusDimensionsX = ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_COMBOBOX_LONG_ENTRY_WIDTH, recruitmentHeaderText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_RECRUITMENT_STATUS), primaryFocusHeaderText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_PRIMARY_FOCUS), secondaryFocusHeaderText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_SECONDARY_FOCUS), personalityHeaderText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_PERSONALITIES), languageHeaderText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_LANGUAGES), timeRangeHeaderText = GetString(SI_GUILD_FINDER_CORE_HOURS_LABEL), gridPaddingX = 20, gridPaddingY = 10, }, activityCheckbox = { entryTemplate = "ZO_CheckboxTile_Gamepad_Control", dimensionsX = ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_COLUMN_WIDTH, dimensionsY = ZO_CHECKBOX_TILE_GAMEPAD_HEIGHT, endEntryTemplate = "ZO_GuildRecruitment_ActivityCheckboxEndTile_Gamepad_Control", endDimensionsY = ZO_CHECKBOX_TILE_GAMEPAD_HEIGHT, gridPaddingX = 20, gridPaddingY = 0, headerText = GetString(SI_GAMEPAD_GUILD_RECRUITMENT_ADDITIONAL_ACTIVITIES_HEADER), }, headlineEditBox = { entryTemplate = "ZO_GuildRecruitment_EditBoxTile_Gamepad_Control", dimensionsX = ZO_GUILD_RECRUITMENT_EDITBOX_GAMEPAD_WIDTH, dimensionsY = ZO_GUILD_RECRUITMENT_EDITBOX_GAMEPAD_HEADLINE_HEIGHT, headerText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_HEADER_MESSAGE), gridPaddingY = 10, }, descriptionEditBox = { entryTemplate = "ZO_GuildRecruitment_EditBoxTile_Description_Gamepad_Control", dimensionsX = ZO_GUILD_RECRUITMENT_EDITBOX_GAMEPAD_WIDTH, dimensionsY = ZO_GUILD_RECRUITMENT_EDITBOX_GAMEPAD_DESCRIPTION_HEIGHT, headerText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_RECRUITMENT_MESSAGE), gridPaddingY = 10, }, roleSelector = { entryTemplate = "ZO_GuildRecruitment_RoleSelectorTile_Gamepad_Control", endEntryTemplate = "ZO_GuildRecruitment_RoleSelectorEndTile_Gamepad_Control", headerText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_ROLES), dimensionsX = ZO_GUILD_RECRUITMENT_ROLE_GAMEPAD_WIDTH, dimensionsY = ZO_GUILD_RECRUITMENT_ROLE_SELECTOR_GAMEPAD_HEIGHT, endDimensionsX = ZO_GUILD_RECRUITMENT_ROLE_END_GAMEPAD_WIDTH, gridPaddingY = 0, }, minimumCP = { entryTemplate = "ZO_GuildRecruitment_NumericEditBoxTile_Gamepad_Control", headerText = GetString("SI_GUILDMETADATAATTRIBUTE", GUILD_META_DATA_ATTRIBUTE_MINIMUM_CP), dimensionsX = ZO_GUILD_RECRUITMENT_NUMERIC_EDITBOX_GAMEPAD_WIDTH, dimensionsY = ZO_GUILD_RECRUITMENT_NUMERIC_EDITBOX_GAMEPAD_ENTRY_HEIGHT, gridPaddingY = 10, }, } ZO_GuildRecruitment_GuildListing_Shared.Initialize(self, control, templateData) ZO_GuildFinder_Panel_GamepadBehavior.Initialize(self, control) self:InitializeGuildNotListedDialog() self:InitializeGuildUnlistedDialog() end function ZO_GuildRecruitment_GuildListing_Gamepad:InitializeGridList() ZO_GuildRecruitment_GuildListing_Shared.InitializeGridList(self) self.gridList:SetOnSelectedDataChangedCallback(function(...) self:OnGridSelectionChanged(...) end) end function ZO_GuildRecruitment_GuildListing_Gamepad:UpdateAlert(previousData, selectedData) if self:GetFragment():IsShowing() then GAMEPAD_TOOLTIPS:ClearLines(GAMEPAD_RIGHT_TOOLTIP) local numMembers, _, _, numInvitees = GetGuildInfo(self.guildId) if numMembers + numInvitees >= MAX_GUILD_MEMBERS then GAMEPAD_TOOLTIPS:LayoutGuildAlert(GAMEPAD_RIGHT_TOOLTIP, GetString(SI_GUILD_RECRUITMENT_GUILD_LISTING_FULL_GUILD_ALERT)) elseif GetGuildFinderNumGuildApplications(self.guildId) >= MAX_PENDING_APPLICATIONS_PER_GUILD then GAMEPAD_TOOLTIPS:LayoutGuildAlert(GAMEPAD_RIGHT_TOOLTIP, GetString(SI_GUILD_RECRUITMENT_GUILD_LISTING_APPLICATIONS_FULL_GUILD_ALERT)) end end end function ZO_GuildRecruitment_GuildListing_Gamepad:OnGridSelectionChanged(oldSelectedData, selectedData) -- Deselect previous tile if oldSelectedData and oldSelectedData.dataEntry then oldSelectedData.isSelected = false end -- Select newly selected tile. if selectedData and selectedData.dataEntry then selectedData.isSelected = true if oldSelectedData and oldSelectedData.dataEntry then self.currentGridListSelectedData = self.gridList:GetSelectedData() end end self.gridList:RefreshGridList() end function ZO_GuildRecruitment_GuildListing_Gamepad:OnShowing() ZO_GuildRecruitment_GuildListing_Shared.OnShowing(self) end function ZO_GuildRecruitment_GuildListing_Gamepad:OnHidden() ZO_GuildRecruitment_GuildListing_Shared.OnHidden(self) GAMEPAD_TOOLTIPS:ClearLines(GAMEPAD_RIGHT_TOOLTIP) end function ZO_GuildRecruitment_GuildListing_Gamepad:Activate() ZO_GuildFinder_Panel_GamepadBehavior.Activate(self) self.gridList:Activate() end function ZO_GuildRecruitment_GuildListing_Gamepad:Deactivate() ZO_GuildFinder_Panel_GamepadBehavior.Deactivate(self) if self.currentActiveGridListEntry then self.currentActiveGridListEntry:Deactivate() self.currentActiveGridListEntry = nil end self.currentGridListSelectedData = nil self.gridList:Deactivate() self:Save() end function ZO_GuildRecruitment_GuildListing_Gamepad:Save(onRecruitmentStatusChanged) if self:CanSave() then local desiredRecruitmentStatus = self.attributeSelectionData.recruitmentStatus.currentValue local remainingRequiredFields = { SaveGuildRecruitmentPendingChanges(self.guildId) } PlaySound(SOUNDS.GUILD_RANK_SAVED) if desiredRecruitmentStatus == GUILD_RECRUITMENT_STATUS_ATTRIBUTE_VALUE_LISTED and #remainingRequiredFields > 0 then self:RefreshData() if onRecruitmentStatusChanged then ZO_Dialogs_ShowPlatformDialog(ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_NOT_LISTED_DIALOG_NAME, remainingRequiredFields) else ZO_Dialogs_ShowPlatformDialog(ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_UNLISTED_DIALOG_NAME, remainingRequiredFields) end elseif onRecruitmentStatusChanged then local guildName = ZO_WHITE:Colorize(GetGuildName(self.guildId)) local decoratedGuildName = ZO_AllianceIconNameFormatter(GetGuildAlliance(self.guildId), guildName) if desiredRecruitmentStatus == GUILD_RECRUITMENT_STATUS_ATTRIBUTE_VALUE_LISTED then ZO_Dialogs_ShowPlatformDialog("GUILD_FINDER_SAVE_FROM_RECRUITMENT_STATUS_LISTED", nil, { mainTextParams = { decoratedGuildName } }) else ZO_Dialogs_ShowPlatformDialog("GUILD_FINDER_SAVE_FROM_RECRUITMENT_STATUS_UNLISTED", nil, { mainTextParams = { decoratedGuildName } }) end end KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor) end end function ZO_GuildRecruitment_GuildListing_Gamepad:InitializeKeybinds() ZO_GuildFinder_Panel_GamepadBehavior.InitializeKeybinds(self) self.keybindsNeededInActiveAttributes = {} for i, data in pairs(self.keybindStripDescriptor) do if i ~= "alignment" then table.insert(self.keybindsNeededInActiveAttributes, data) end end table.insert(self.keybindStripDescriptor, -- select { name = GetString(SI_GAMEPAD_SELECT_OPTION), keybind = "UI_SHORTCUT_PRIMARY", callback = function() local selectedData = self.gridList:GetSelectedData() if selectedData then if selectedData.dataEntry.typeId == ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_ENTRY_TEMPLATE.CHECKBOX or selectedData.dataEntry.typeId == ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_ENTRY_TEMPLATE.CHECKBOX_END then selectedData.dataEntry.control.object:OnCheckboxToggle() elseif selectedData.dataEntry.typeId == ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_ENTRY_TEMPLATE.ROLE_SELECTOR or selectedData.dataEntry.typeId == ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_ENTRY_TEMPLATE.ROLE_SELECTOR_END then selectedData.dataEntry.control.object:OnRoleToggle() else self.currentGridListSelectedData = selectedData self.gridList:Deactivate() local function DeactivateCallback() self.gridList:Activate() self.currentActiveGridListEntry = nil end self.currentActiveGridListEntry = selectedData.dataEntry.control.object self.currentActiveGridListEntry:SetDeactivateCallback(DeactivateCallback) self.currentActiveGridListEntry:Activate() end end end, } ) end function ZO_GuildRecruitment_GuildListing_Gamepad:BuildGridList() ZO_GuildRecruitment_GuildListing_Shared.BuildGridList(self) if self.currentGridListSelectedData then self.gridList:SelectData(self.currentGridListSelectedData) end end do local BULLET_ICON = "EsoUI/Art/Miscellaneous/Gamepad/gp_bullet.dds" local BULLET_ICON_SIZE = 32 function ZO_GuildRecruitment_GuildListing_Gamepad:InitializeGuildNotListedDialog() local function ReleaseDialog() GAMEPAD_TOOLTIPS:ClearLines(GAMEPAD_LEFT_TOOLTIP) ZO_Dialogs_ReleaseDialogOnButtonPress(ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_NOT_LISTED_DIALOG_NAME) end ZO_Dialogs_RegisterCustomDialog(ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_NOT_LISTED_DIALOG_NAME, { blockDialogReleaseOnPress = true, canQueue = true, gamepadInfo = { dialogType = GAMEPAD_DIALOGS.STATIC_LIST, allowShowOnNextScene = true, }, setup = function(dialog) dialog:setupFunc() end, title = { text = SI_GUILD_RECRUITMENT_NOT_LISTED_DIALOG_TITLE, }, mainText = { text = SI_GUILD_RECRUITMENT_NOT_LISTED_DIALOG_DESCRIPTION, }, itemInfo = function(dialog) local bulletListTable = {} for i, attribute in ipairs(dialog.data) do table.insert(bulletListTable, { icon = BULLET_ICON, iconSize = BULLET_ICON_SIZE, label = GetString("SI_GUILDMETADATAATTRIBUTE", attribute), }) end return bulletListTable end, buttons = { -- Exit Button { keybind = "DIALOG_NEGATIVE", text = SI_GAMEPAD_BACK_OPTION, callback = function(dialog) ReleaseDialog() end, }, } }) end function ZO_GuildRecruitment_GuildListing_Gamepad:InitializeGuildUnlistedDialog() local function ReleaseDialog() GAMEPAD_TOOLTIPS:ClearLines(GAMEPAD_LEFT_TOOLTIP) ZO_Dialogs_ReleaseDialogOnButtonPress(ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_UNLISTED_DIALOG_NAME) end ZO_Dialogs_RegisterCustomDialog(ZO_GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD_UNLISTED_DIALOG_NAME, { blockDialogReleaseOnPress = true, canQueue = true, gamepadInfo = { dialogType = GAMEPAD_DIALOGS.STATIC_LIST, allowShowOnNextScene = true, }, setup = function(dialog) dialog:setupFunc() end, title = { text = SI_GUILD_RECRUITMENT_LISTING_FAILED_DIALOG_TITLE, }, mainText = { text = SI_GUILD_RECRUITMENT_LISTING_FAILED_DIALOG_DESCRIPTION, }, itemInfo = function(dialog) local bulletListTable = {} for i, attribute in ipairs(dialog.data) do table.insert(bulletListTable, { icon = BULLET_ICON, iconSize = BULLET_ICON_SIZE, label = GetString("SI_GUILDMETADATAATTRIBUTE", attribute), }) end return bulletListTable end, buttons = { -- Exit Button { keybind = "DIALOG_NEGATIVE", text = SI_GAMEPAD_BACK_OPTION, callback = function(dialog) ReleaseDialog() end, }, } }) end end -- XML functions ---------------- function ZO_GuildRecruitment_GuildListing_Gamepad_OnInitialized(control) GUILD_RECRUITMENT_GUILD_LISTING_GAMEPAD = ZO_GuildRecruitment_GuildListing_Gamepad:New(control) end
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") include("server/autotaunt.lua") function GM:PlayerInitialSpawn(ply) ply:SetTeam(TEAM_SPECTATOR) player_manager.SetPlayerClass(ply, "player_spectator") if (ply:IsBot()) then -- Auto add bots to the smaller team for testing. SetTeam(ply, TEAM_ANY) end ply:SetCustomCollisionCheck(true) net.Start("Class Selection") -- Just used as a hook net.Send(ply) end -- Add command to hunter blindness for testing. -- This is a huge hack but it is only needed for testing. concommand.Add("testmode", function (ply) if IsValid(ply) then return end -- Bail if this is sent from a player. BroadcastLua("OBJHUNT_HIDE_TIME = 1") OBJHUNT_HIDE_TIME = 1 print("Test mode enabled.") end) -- [[ Class Selection ]] -- function GM:ShowTeam(ply) -- This hook is called everytime F2 is pressed. net.Start("Class Selection") -- Just used as a hook net.Send(ply) end function GM:ShowHelp(ply) net.Start("Help") -- Just used as a hook net.Send(ply) end function SetTeam(ply, chosen) local playerTable = {} local oldTeam = ply:Team() if chosen == ply:Team() then ply:ChatPrint("You are already on that team.") return end if chosen == TEAM_SPECTATOR then player_manager.SetPlayerClass(ply, "player_spectator") end playerTable[ TEAM_PROPS ] = team.NumPlayers(TEAM_PROPS) playerTable[ TEAM_HUNTERS ] = team.NumPlayers(TEAM_HUNTERS) playerTable[ TEAM_SPECTATOR ] = team.NumPlayers(TEAM_SPECTATOR) playerTable[ ply:Team() ] = playerTable[ ply:Team() ] - 1 if chosen == TEAM_ANY then if playerTable[ TEAM_PROPS ] > playerTable[ TEAM_HUNTERS ] then chosen = TEAM_HUNTERS else chosen = TEAM_PROPS end end if math.abs(playerTable[ TEAM_PROPS ] - playerTable[ TEAM_HUNTERS ]) >= MAX_TEAM_NUMBER_DIFFERENCE then if playerTable[ chosen ] == math.max(playerTable[ TEAM_PROPS ], playerTable[ TEAM_HUNTERS ]) then ply:ChatPrint("Sorry, that team is currently full.") return end end ply:SetTeam(chosen) if (chosen == TEAM_PROPS) then player_manager.SetPlayerClass(ply, "player_prop") elseif (chosen == TEAM_HUNTERS) then player_manager.SetPlayerClass(ply, "player_hunter") end PrintMessage(HUD_PRINTTALK, ply:Nick() .. " moved from " .. TeamString(oldTeam) .. " to " .. TeamString(ply:Team())) RemovePlayerProp(ply) ply:KillSilent() --ply:Spawn() end -- [[ Taunts ]] -- function SendTaunt(ply, taunt, pitch) -- Checks: the player has to be allowed to make a taunt right now, and the -- server has to know about the taunt they want to play. local now = CurTime() if !IsValid(ply) or !ply:CanTauntAt(now) then return end if (ply:Team() == TEAM_PROPS and !table.HasValue(PROP_TAUNTS, taunt)) then return end if (ply:Team() == TEAM_HUNTERS and !table.HasValue(HUNTER_TAUNTS, taunt)) then return end -- NOTE: `NewSoundDuration` uses the "GAME" search path, which includes our -- game mode's content/ folder. The taunt itself is relative to -- content/sound/, so we have to extend the path with the sound/ prefix. -- Normally, sound-specific APIs don't need to adjust the path in this way; -- for instance, clients won't have to do this when playing the sound. local duration = NewSoundDuration("sound/" .. taunt) -- Bail out if the duration could not be determined or is nonsensical. -- NewSoundDuration's fallback to the built in SoundDuration can return -- junk values if it can't parse a sound file. This is game-breaking so -- bail if that happens. For more details see: -- https://github.com/Facepunch/garrysmod-issues/issues/936 if (!duration or duration <= 0 or duration >= 50) then if (!duration) then duration = "nil" end print("[ERROR] Taunt '" .. taunt .. "' has bad duration '" .. duration .. "'") return end print("Taunt: " .. taunt .. " from " .. ply:Nick() .. " at pitch " .. tostring(pitch) .. "; pre-pitch-adjusted duration is " .. duration .. "s" ) local adjustedDuration = duration * (100 / pitch) ply:SetLastTauntTime(now) ply:SetLastTauntDuration(adjustedDuration) -- NOTE: +1 on the modifier to ensure that the previous taunt doesn't count -- against the player's time, even if the modifier is 0. ply:SetNextAutoTauntDelay( (OBJHUNT_AUTOTAUNT_DURATION_MODIFIER + 1) * adjustedDuration + OBJHUNT_AUTOTAUNT_BASE_INTERVAL ) net.Start("Taunt Selection BROADCAST") net.WriteString(taunt) net.WriteUInt(pitch, 8) net.WriteUInt(ply:EntIndex(), 8) net.Broadcast() if (!ply.tauntHistory) then ply.tauntHistory = EmptySet() end SetAdd(ply.tauntHistory, taunt) end function GM:PlayerSetModel(ply) local class = player_manager.GetPlayerClass(ply) if (class == "player_hunter") then ply:SetModel(TEAM_HUNTERS_DEFAULT_MODEL) elseif (class == "player_prop") then ply:SetModel(TEAM_PROPS_DEFAULT_MODEL) else return end end -- disable the regular damage system function GM:PlayerShouldTakeDamage(victim, attacker) return false end function BroadcastPlayerDeath(ply) net.Start("Player Death") -- the player who died, so sad, too bad. net.WriteUInt(ply:EntIndex(), 8) net.Broadcast() -- remove ragdoll local ragdoll = ply:GetRagdollEntity() -- ideally this ragdoll stays around the same amount of time as a prop can play dead for SafeRemoveEntityDelayed(ragdoll, PROP_RAGDOLL_DURATION) end function AnnouncePlayerDeath(ply, attacker) net.Start("Death Notice") net.WriteString(attacker:Nick()) net.WriteUInt(attacker:Team(), 16) net.WriteString("found") net.WriteString(ply:Nick()) net.WriteUInt(ply:Team(), 16) net.Broadcast() end function PayRespects(ply) local victim = GetLatestVictim() -- can't pay respects to yourself or without a victim if (victim == ply or victim == nil) then return end local display_string = RESPECTS_VERBS[math.random(#RESPECTS_VERBS)] net.Start("Display Respects") net.WriteString(ply:Nick()) net.WriteUInt(ply:Team(), 16) net.WriteString(display_string) net.WriteString(victim:Nick()) net.WriteUInt(victim:Team(), 16) net.Broadcast() end -- NOTE: damage from hunters should go through HurtProp, which first rewards -- the attacker based on damage dealt and then calls this procedure. This -- procedure merely: -- - deals the damage -- - performs prop-specific on-death effects if new health <= 0 function HurtPropAndCheckForDeath(ply, dmg, attacker) ply:SetHealth(ply:Health() - dmg) if (ply:Health() < 1 and ply:Alive()) then ply:PropDeath(attacker) end end -- how damage to props is handled local function HurtProp(ply, dmg, attacker) if (attacker:Alive()) then local gain = math.min(ply:Health(), dmg) gain = gain / 2 local newHP = math.Clamp(attacker:Health() + gain, 0, 100) attacker:SetHealth(newHP) end HurtPropAndCheckForDeath(ply, dmg, attacker) end -- new damage system local function DamageHandler(target, dmgInfo) local attacker = dmgInfo:GetAttacker() -- dynamic damage local dmg = dmgInfo:GetDamage() if (attacker:IsPlayer()) then if (attacker:Team() == TEAM_HUNTERS) then -- since player_prop_ent isn't in USABLE_PROP_ENTS this is sufficient logic to prevent -- player owned props from getting hurt if (!target:IsPlayer() and table.HasValue(USABLE_PROP_ENTITIES, target:GetClass()) and attacker:Alive()) then -- disable stepping on bottles to hurt local dmgType = dmgInfo:GetDamageType() if (dmgType == DMG_CRUSH) then return end -- static damage if (HUNTER_DAMAGE_PENALTY > 0) then dmg = HUNTER_DAMAGE_PENALTY end attacker:SetHealth(attacker:Health() - dmg) if (attacker:Health() < 1) then attacker:Kill() -- default suicide notice end elseif (target:GetOwner():IsPlayer() and target:GetOwner():Team() == TEAM_PROPS and !target:GetOwner():ObjIsPlaydead()) then local ply = target:GetOwner() if (ply:ObjGetPlaydeadCallback()) then ply:ObjGetPlaydeadCallback():AbilityTrigger() else HurtProp(ply, dmg, attacker) end elseif (target:IsPlayer() and target:Team() == TEAM_PROPS and !target:ObjIsPlaydead()) then local ply = target if (ply:ObjGetPlaydeadCallback()) then ply:ObjGetPlaydeadCallback():AbilityTrigger() else HurtProp(ply, dmg, attacker) end elseif (target:IsPlayer() and target:Team() == TEAM_HUNTERS and IsHunterFriendlyFireEnabled()) then target:SetHealth(target:Health() - dmg) if (target:Health() < 1) then target:KillSilent() AnnouncePlayerDeath(target, attacker) end end end end end hook.Add("EntityTakeDamage", "forward dmg to new system", function(target, dmg) DamageHandler(target, dmg) end) --[[ Door Exploit fix ]]-- function GM:PlayerUse(ply, ent) if (table.HasValue(DOORS, ent:GetClass()) and CurTime() < ply:GetTimeOfNextDoorOpen()) then return false else ply:SetTimeOfNextDoorOpen(CurTime() + 0.5 + math.random()) return true end end --[[ sets the players prop, run PlayerCanBeEnt before using this ]]-- function SetPlayerProp(ply, ent, scale, revert) ply.lastChange = CurTime() -- The player's prop entity will be adjusted in-place to look like `ent`. local prop = ply:GetProp() if (!revert) then ResetPrevVals(ply) ply.prevPropModel = prop:GetModel() ply.prevPropSkin = prop:GetSkin() ply.prevPropMass = ply:GetPhysicsObject():GetMass() ply.prevPropVMesh = ply:GetPhysicsObject():GetMeshConvexes() ply.prevPropScale = prop:GetModelScale() ply.prevPos = ply:GetPos() ply.prevAngle = ply:GetAngles() ply.prevLockedAngle = ply:GetPropLockedAngle() ply.prevRollAngle = ply:GetPropRollAngle() end -- scaling if (revert and ply.prevPropScale) then prop:SetModelScale(ply.prevPropScale, 0) else prop:SetModelScale(scale, 0) end if (revert and ply.prevPropModel) then prop:SetModel(ply.prevPropModel) else prop:SetModel(ent:GetModel()) end if (revert and ply.prevPropSkin) then prop:SetSkin(ply.prevPropSkin) else prop:SetSkin(ent:GetSkin()) end prop:SetSolid(SOLID_VPHYSICS) -- We will reset the roll and pitch of a Prop when changing to make for easier escapes if (revert and ply.prevLockedAngle) then ply:SetPropLockedAngle(ply.prevLockedAngle) else local lockedAngle = ply:GetPropLockedAngle() local newAngle = Angle(0, lockedAngle.y, 0) ply:SetPropLockedAngle(newAngle) end if (revert and ply.prevRollAngle) then ply:SetPropRollAngle(ply.prevRollAngle) else ply:SetPropRollAngle(0) end local tHitboxMin, tHitboxMax = PropHitbox(ply) if (revert and ply.prevPos) then ply:SetPos(ply.prevPos) else --Adjust Position for no stuck ply:SetPos(FindSpotFor(ply, tHitboxMin, tHitboxMax)) end UpdatePlayerPropHitbox(ply, tHitboxMin, tHitboxMax) local tHeight = tHitboxMax.z - tHitboxMin.z -- scale steps to prop size ply:SetStepSize(math.Round(4 + tHeight / 4)) -- give bigger props a bonus for being big ply:SetJumpPower(PROP_DEFAULT_JUMP_POWER + math.sqrt(tHeight)) if (prop == ent) then -- In the case of the first Prop let's leave the Last Change Time at 0 so no cooldown ply:SetPropLastChange(0) else ply:SetPropLastChange(CurTime()) end local volume = (tHitboxMax.x - tHitboxMin.x) * (tHitboxMax.y - tHitboxMin.y) * (tHitboxMax.z - tHitboxMin.z) ply.propSize = volume ^ (1 / 3) ply:SetupPropHealth() ply:SetupPropSpeed() -- Update the player's mass to be something more reasonable to the prop if (revert and ply.prevPropMass) then ply:GetPhysicsObject():SetMass(ply.prevPropMass) if (ply.prevPropVMesh) then prop:PhysicsInitMultiConvex(ply.prevPropVMesh) end else local phys = ent:GetPhysicsObject() if IsValid(ent) and phys:IsValid() then ply:GetPhysicsObject():SetMass(phys:GetMass()) -- vphysics local vPhysMesh = phys:GetMeshConvexes() prop:PhysicsInitMultiConvex(vPhysMesh) else -- Entity doesn't have a physics object so calculate mass local density = PROP_DEFAULT_DENSITY local mass = volume * density mass = math.Clamp(mass, 0, 100) ply:GetPhysicsObject():SetMass(mass) end end if (!ply.propHistory) then ply.propHistory = EmptySet() end SetAdd(ply.propHistory, ent:GetModel()) end function UpdatePlayerPropHitbox(ply, hbMin, hbMax) ply:SetHull(hbMin, hbMax) ply:SetHullDuck(hbMin, hbMax) local height = hbMax.z - hbMin.z -- match the view offset for calcviewing to the height ply:SetViewOffset(Vector(0,0,height)) net.Start("Prop Update") net.WriteVector(hbMax) net.WriteVector(hbMin) net.Send(ply) end function RevertProp(ply) if ( !ply:Alive() or !ply.lastChange or !ply.prevPos or !ply.prevAngle or !ply.prevLockedAngle or !ply.prevRollAngle or CurTime() > ply.lastChange + 3 * PROP_CHOOSE_COOLDOWN ) then return end if (ply.prevPropModel) then SetPlayerProp( ply, ply:GetProp(), ply:GetProp():GetModelScale(), true ) else ply:SetPos(ply.prevPos) ply:SetAngles(ply.prevAngle) if (ply.prevAngleLockChange) then ply:SetPropAngleLocked(!ply:GetPropAngleLocked()) end ply:SetPropLockedAngle(ply.prevLockedAngle) ply:SetPropRollAngle(ply.prevRollAngle) local tHitboxMin, tHitboxMax = PropHitbox(ply) UpdatePlayerPropHitbox(ply, tHitboxMin, tHitboxMax) end ResetPrevVals(ply) end function ResetPrevVals(ply) ply.prevPropModel = nil ply.prevPropSkin = nil ply.prevPropMass = nil ply.prevPropVMesh = nil ply.prevPropScale = nil ply.prevPos = nil ply.prevAngle = nil ply.prevAngleLockChange = false ply.prevLockedAngle = nil ply.prevRollAngle = nil end function ResetPropToProp(ply) ResetPrevVals(ply) ply.lastChange = CurTime() ply.prevPos = ply:GetPos() ply.prevAngle = ply:GetAngles() ply.prevLockedAngle = ply:GetPropLockedAngle() ply.prevRollAngle = ply:GetPropRollAngle() local tHitboxMin, tHitboxMax = PropHitbox(ply) --Adjust Position for no stuck local foundSpot = FindSpotFor(ply, tHitboxMin, tHitboxMax) ply:SetPos(foundSpot) UpdatePlayerPropHitbox(ply, tHitboxMin, tHitboxMax) end function UnstickPlayer(ply, searchMultplier) local tHitboxMin, tHitboxMax if (ply:Team() == TEAM_PROPS) then ply.lastChange = CurTime() ResetPrevVals(ply) ply.prevPos = ply:GetPos() ply.prevAngle = ply:GetAngle() ply.prevLockedAngle = ply:GetPropLockedAngle() ply.prevRollAngle = ply:GetPropRollAngle() tHitboxMin, tHitboxMax = PropHitbox(ply) elseif (ply:Team() == TEAM_HUNTERS) then tHitboxMin, tHitboxMax = GetHitBoxInModelCoordinates(ply) else return end --Adjust Position for no stuck local foundSpot = FindSpotFor(ply, tHitboxMin, tHitboxMax, searchMultplier) ply:SetPos(foundSpot) UpdatePlayerPropHitbox(ply, tHitboxMin, tHitboxMax) end function GetNumValidPropsOnMap() local numProps = 0 local allEnts = ents.GetAll() for _, someEnt in pairs( allEnts ) do if ( IsValid(someEnt) and table.HasValue(USABLE_PROP_ENTITIES, someEnt:GetClass()) and IsValid(someEnt:GetPhysicsObject()) and someEnt:GetClass() and someEnt:GetModel() ) then numProps = numProps + 1 end end print(numProps) return numProps end hook.Add("InitPostEntity", "Entities ready, count props", function () SetGlobalInt("NumPropsOnMap", GetNumValidPropsOnMap()) end) --[[ When a player on team_props spawns ]]-- hook.Add("PlayerSpawn", "Set ObjHunt model", function (ply) -- default prop should be able to step wherever ply:SetStepSize(20) ply:SetNotSolid(false) if (ply:Team() == TEAM_PROPS) then ply.propSize = 100 ply:SetupPropHealth() ply:SetupPropSpeed() -- make the player invisible ply:SetRenderMode(RENDERMODE_NONE) ply:SetBloodColor(DONT_BLEED) timer.Simple(0.5, function() ply:SetProp(ents.Create("player_prop_ent")) ply:GetProp():Spawn() ply:GetProp():SetOwner(ply) -- custom initial hb (REMVOED): PROP_DEFAULT_HB_MIN, PROP_DEFAULT_HB_MAX SetPlayerProp(ply, ply:GetProp(), PROP_DEFAULT_SCALE) end) -- this fixes ent culling when head in ceiling -- should be based on default hit box! ply:SetViewOffset(Vector(0,0,35)) elseif (ply:Team() == TEAM_HUNTERS) then ply:SetRenderMode(RENDERMODE_NORMAL) ply:SetColor(Color(255,255,255,255)) -- default ply:SetViewOffset(Vector(0,0,64)) end end) hook.Add("PlayerDisconnected", "Remove ent prop on dc", function(ply) RemovePlayerProp(ply) end) hook.Add("PlayerDeath", "Remove ent prop on death", function(ply) BroadcastPlayerDeath(ply) RemovePlayerProp(ply) if (ply:IsFrozen()) then ply:Freeze(false) end ply:SetTimeOfDeath(CurTime()) end) --[[ remove the ent prop ]]-- function RemovePlayerProp(ply) if (ply.GetProp and IsValid(ply:GetProp())) then ply:GetProp():Remove() ply:SetProp(nil) end ply:ResetHull() net.Start("Reset Prop") -- empty, just used for the hook net.Send(ply) end function GM:PlayerSelectSpawn(ply) local spawns = team.GetSpawnPoints(ply:Team()) if (!spawns) then return false end local ret, _ = table.Random(spawns) return ret end function GM:PlayerCanSeePlayersChat(text, teamOnly, listener, speaker) if (DISABLE_GLOBAL_CHAT) then if (speaker:IsAdmin()) then return true end if (listener:Team() != speaker:Team()) then return false end end if (teamOnly) then if (listener:Team() != speaker:Team()) then return false end end return true end function GM:PlayerCanPickupWeapon(ply, wep) return ply:Team() == TEAM_HUNTERS or (ply:Team() == TEAM_PROPS and wep:IsScripted()) end function GM:AllowPlayerPickup(ply, ent) return (OBJHUNT_TEAM_HUNTERS_CAN_MOVE_PROPS and ply:Team() == TEAM_HUNTERS and ply.pickupProp) or (OBJHUNT_TEAM_PROPS_CAN_MOVE_PROPS and ply:Team() == TEAM_PROPS and ply.pickupProp) end function GM:PlayerButtonDown(ply, button) if (button == KEY_LCONTROL) then ply.pickupProp = true end end function GM:PlayerButtonUp(ply, button) if (button == KEY_LCONTROL) then ply.pickupProp = false end end -- Q-menu (Taunt Selection) Anti Abuse -- function QMenuAntiAbuse(ply) if (!QMENU_ANTI_ABUSE or ply:Team() != TEAM_PROPS) then return false end local tauntRepeatsModifier = math.max(1, SetCountGetMax(ply.tauntHistory) - 2) if (math.random() * QMENU_CONSEQUENCE_ODDS / tauntRepeatsModifier < 1.0) then if (ply:Alive()) then ply:SetRenderMode(RENDERMODE_NORMAL) ply:CreateRagdoll() RemovePlayerProp(ply) ply:KillSilent() BroadcastPlayerDeath(ply) net.Start("Death Notice") net.WriteString("QAnon") net.WriteUInt(TEAM_HUNTERS, 16) net.WriteString("found") net.WriteString(ply:Nick()) net.WriteUInt(ply:Team(), 16) net.Broadcast() end return true; end return false end
gameState = "play" --libs local bump = require 'lib.bump' local inspect = require 'lib.inspect' local class = require 'lib.middleclass' local gamera = require 'lib.gamera' local txt = require 'lib.txt' -- source files local Player = require 'src.player' local MapSystem = require 'src.mapsystem' local LevelManager = require 'src.levelmanager' local Blocks = require 'src.blocks' local Quads = require 'src.quads' local Entity = require 'src.entity' local Enemy = require 'src.enemy' local map = txt.parseMap('levels/level_' .. tostring(LevelManager.currLevel-1) .. '.txt') local world = bump.newWorld() -- ** tilesets ** local tileset = love.graphics.newImage('images/solid_tileset2.png') local tilesetW, tilesetH = tileset:getWidth(), tileset:getHeight() -- camera -- local Camera = class('Camera') -- function Camera:initialize(tileW, tileH, mapW, mapH, windowWidth, windowHeight) -- cam = gamera.new(0, 0, windowWidth, windowHeight) -- cam:setWorld(0, 0, mapW*tileW, mapH*tileH) -- end function love.load() local tileswide = tilesetW/map.tilewidth local tileshigh = tilesetH/map.tileheight cam = gamera.new(0, 0, love.graphics.getWidth(), love.graphics.getHeight()) cam:setWorld(0, 0, map.w*map.tilewidth, map.h*map.tileheight) Enemy:initialize(world) Blocks:initialize(world) Quads.quadInfo = Quads:loadQuadInfo(map.tilewidth, map.tileheight, tilesetW/map.tilewidth, tilesetH/map.tileheight) Quads.quads = Quads:loadQuads(map.tilewidth, map.tileheight, tilesetW, tilesetH) MapSystem:loadMap(map) LevelManager:initialize(world) LevelManager:loadLevels("levels") love.graphics.setBackgroundColor(53,118,143) font = love.graphics.newFont('fonts/font.ttf', 48) local PlayerLoadX, PlayerLoadY = MapSystem:returnTileCoors(4) Player:initialize(world, PlayerLoadX, PlayerLoadY, 32, 32) end function love.update(dt) if gameState == 'play' then Enemy:update(dt, Player.x, Player.y) Player:update(dt) Player:canPassLevel(MapSystem.itemCount) local width, height = MapSystem.tilewidth*MapSystem.mapwidth, MapSystem.tileheight*MapSystem.mapheight cam:setWorld(0, 0, width, height) debugX = cam:getCameraX() - cam.w / 2 debugY = cam:getCameraY() - cam.h / 2 local var = Player:canPassLevel(MapSystem.itemCount) -- print(Player.keyCount, var, MapSystem.itemCount) end end function love.draw() cam:draw(function(l,t,w,h) Player:drawPlayer() MapSystem:drawTiles(tileset, Quads.quadInfo, Quads.quads) -- Player:drawDebugStrings(debugX, debugY) Enemy:drawEnemies() end) if gameState == "dead" then love.graphics.setColor(255,255,255) love.graphics.setFont(font) love.graphics.print("YOU'RE DEAD KIDDO", cam:getCameraX()-120, cam:getCameraY()) end end function love.keypressed(key) if key == 'escape' then love.event.quit() end if key == 'r' then local var = Player:canPassLevel(MapSystem.itemCount) if var then LevelManager:nextLevel(MapSystem.data) print(var, MapSystem.itemCount) local PlayerLoadX, PlayerLoadY = MapSystem:returnTileCoors(4) world:update(Player, PlayerLoadX, PlayerLoadY) Player:resetPlayer(PlayerLoadX, PlayerLoadY) end end Player:jump(key) end
local P = require 'posix' local fd1 = P.open(arg[1], P.O_RDONLY) local fd2 = P.open(arg[2], P.O_RDONLY) local fds = { [fd1] = { events = {IN=true} }, [fd2] = { events = {IN=true} } } while true do P.poll(fds,-1) for fd in pairs(fds) do if fds[fd].revents.IN then local res = P.read(fd,1024) P.write(1,res); end if fds[fd].revents.HUP then P.close(fd) fds[fd] = nil if not next(fds) then return end end end end
local stat = { { _id = "life", elona_id = 2, calc_final = function(level) return { level = level, potential = 100 } end }, { _id = "mana", elona_id = 3, calc_final = function(level) return { level = level, potential = 100 } end }, { _id = "strength", elona_id = 10, }, { _id = "constitution", elona_id = 11, }, { _id = "dexterity", elona_id = 12, }, { _id = "perception", elona_id = 13, }, { _id = "learning", elona_id = 14, }, { _id = "will", elona_id = 15, }, { _id = "magic", elona_id = 16, }, { _id = "charisma", elona_id = 17, }, { _id = "speed", elona_id = 18, calc_initial_level = function(level, chara) return math.floor(level * (100 * chara.level * 2) / 100) end }, { _id = "luck", elona_id = 19, calc_final = function(level) return { level = level, potential = 100 } end } } data:add_multi("base.stat", stat)
local JoinController= require(game.ServerScriptService.kwatworks.Base.BaseController):extend() local Players = game:GetService("Players") local Player = require(game.ServerScriptService.kwatworks.Core.PlayerObject) local PlayerController = require(game.ServerScriptService.kwatworks.Core.PlayerController) function JoinController:Activate(customFunction) Players.PlayerAdded:Connect(function(player) local playerObj = Player(player,player.Name) self:Handle(playerObj) customFunction(playerObj) end) end function JoinController:Handle(playerObj) PlayerController:Add(playerObj) end return JoinController
-- =========================================================================== -- CivicsTree -- Tabs set to 4 spaces retaining tab. -- -- Items exist in one of 7 "rows" that span horizontally and within a -- "column" based on the era and cost. -- -- Rows Start Eras-> -- -3 _____ _____ -- -2 /-|_____|----/-|_____| -- -1 | _____ | Nodes -- 0 O----%-|_____|----' -- 1 -- 2 -- 3 -- -- =========================================================================== include( "InstanceManager" ); include( "SupportFunctions" ); include( "Civ6Common" ); -- Tutorial check support include( "TechAndCivicSupport" ); include( "TechFilterFunctions" ); include( "ModalScreen_PlayerYieldsHelper" ); -- =========================================================================== -- DEBUG -- Toggle these for temporary debugging help. -- =========================================================================== local m_debugFilterEraMaxIndex :number = -1; -- (-1 default) Only load up to a specific ERA (Value less than 1 to disable) local m_debugOutputTechInfo :boolean= false; -- (false default) Send to console detailed information on tech? local m_debugShowIDWithName :boolean= false; -- (false default) Show the ID before the name in each node. local m_debugShowAllMarkers :boolean= false; -- (false default) Show all player markers in the timline; even if they haven't been met. -- =========================================================================== -- CONSTANTS -- =========================================================================== -- Graphic constants local PIC_BOLT_OFF :string = "Controls_BoltOff"; local PIC_BOLT_ON :string = "Controls_BoltOn"; local PIC_BOOST_OFF :string = "BoostTech"; local PIC_BOOST_ON :string = "BoostTechOn"; local PIC_DEFAULT_ERA_BACKGROUND:string = "CivicsTree_BGAncient"; local PIC_MARKER_PLAYER :string = "Tree_TimePipPlayer"; local PIC_MARKER_OTHER :string = "Controls_TimePip"; local PIC_METER_BACK :string = "Tree_Meter_GearBack"; local PIC_METER_BACK_DONE :string = "TechTree_Meter_Done"; local SIZE_ART_ERA_OFFSET_X :number = 40; -- How far to push each era marker local SIZE_ART_ERA_START_X :number = 40; -- How far to set the first era marker local SIZE_GOVTPANEL_HEIGHT :number = 220; local SIZE_MARKER_PLAYER_X :number = 122; -- Marker of player local SIZE_MARKER_PLAYER_Y :number = 42; -- " local SIZE_MARKER_OTHER_X :number = 34; -- Marker of other players local SIZE_MARKER_OTHER_Y :number = 37; -- " local SIZE_NODE_X :number = 460; -- Item node dimensions local SIZE_NODE_Y :number = 84; local SIZE_NODE_LARGE_Y :number = 140; -- " local SIZE_OPTIONS_X :number = 200; local SIZE_OPTIONS_Y :number = 150; local SIZE_PATH :number = 40; local SIZE_PATH_HALF :number = 20; local SIZE_TIMELINE_AREA_Y :number = 41; local SIZE_TOP_AREA_Y :number = 60; local SIZE_WIDESCREEN_HEIGHT :number = 768; local PATH_MARKER_OFFSET_X :number = 20; local PATH_MARKER_OFFSET_Y :number = 50; local PATH_MARKER_NUMBER_0_9_OFFSET :number = 20; local PATH_MARKER_NUMBER_10_OFFSET :number = 15; -- Other constants local COLUMN_WIDTH :number = 250; -- Space of node and line(s) after it to the next node local COLUMNS_NODES_SPAN :number = 2; -- How many colunms do the nodes span local DATA_FIELD_GOVERNMENT :string = "_GOVERNMENT"; --holds players govt and policies local DATA_FIELD_LIVEDATA :string = "_LIVEDATA"; -- The current status of an item. local DATA_FIELD_PLAYERINFO :string = "_PLAYERINFO";-- Holds a table with summary information on that player. local DATA_FIELD_UIOPTIONS :string = "_UIOPTIONS"; -- What options the player has selected for this screen. local DATA_ICON_PREFIX :string = "ICON_"; local DATA_ICON_UNAVAILABLE :string = "_FOW"; local ITEM_STATUS :table = { BLOCKED = 1, READY = 2, CURRENT = 3, RESEARCHED = 4, }; local LINE_LENGTH_BEFORE_CURVE :number = 20; -- How long to make a line before a node before it curves local LINE_VERTICAL_OFFSET :number = 0; local PADDING_TIMELINE_LEFT :number = 250; local PADDING_NODE_STACK_Y :number = 20; local PARALLAX_SPEED :number = 1.1; -- Speed for how much slower background moves (1.0=regular speed, 0.5=half speed) local PARALLAX_ART_SPEED :number = 1.2; -- Speed for how much slower background moves (1.0=regular speed, 0.5=half speed) local PREREQ_ID_TREE_START :string = "_TREESTART"; -- Made up, unique value, to mark a non-node tree start local ROW_MAX :number = 3; -- Highest level row above 0 local ROW_MIN :number = -3; -- Lowest level row below 0 local STATUS_ART :table = {}; local STATUS_ART_LARGE :table = {}; local TREE_START_ROW :number = -999; -- Which virtual "row" does tree start on? (or -999 for first node) local TREE_START_COLUMN :number = 0; -- Which virtual "column" does tree start on? (Can be negative!) local TREE_START_NONE_ID :number = -999; -- Special, unique value, to mark no special tree start node. local TXT_BOOSTED :string = Locale.Lookup("LOC_BOOST_BOOSTED"); local TXT_TO_BOOST :string = Locale.Lookup("LOC_BOOST_TO_BOOST"); local VERTICAL_CENTER :number = (SIZE_NODE_Y) / 2; local MAX_BEFORE_TRUNC_GOV_TITLE :number = 165; local MAX_BEFORE_TRUNC_TO_BOOST :number = 385; -- CQUI CONSTANTS local CQUI_STATUS_MESSAGE_CIVIC :number = 3; -- Number to distinguish civic messages STATUS_ART[ITEM_STATUS.BLOCKED] = { Name="BLOCKED", TextColor0=0xff202726, TextColor1=0x00000000, FillTexture="CivicsTree_GearButtonTile_Disabled.dds",BGU=0,BGV=(SIZE_NODE_Y*3), HideIcon=true, IsButton=false, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.READY] = { Name="READY", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=0, HideIcon=true, IsButton=true, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.CURRENT] = { Name="CURRENT", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=(SIZE_NODE_Y*4), HideIcon=false, IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.RESEARCHED] = { Name="RESEARCHED", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture="CivicsTree_GearButtonTile_Done.dds", BGU=0,BGV=(SIZE_NODE_Y*5), HideIcon=false, IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK_DONE }; STATUS_ART_LARGE[ITEM_STATUS.BLOCKED] = { Name="LARGEBLOCKED", TextColor0=0xff202726, TextColor1=0x00000000, FillTexture="CivicsTree_GearButton2Tile_Disabled.dds",BGU=0,BGV=(SIZE_NODE_LARGE_Y*3), HideIcon=true, IsButton=false, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART_LARGE[ITEM_STATUS.READY] = { Name="LARGEREADY", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=0, HideIcon=true, IsButton=true, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART_LARGE[ITEM_STATUS.CURRENT] = { Name="LARGECURRENT", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=(SIZE_NODE_LARGE_Y*4), HideIcon=false, IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK }; STATUS_ART_LARGE[ITEM_STATUS.RESEARCHED] = { Name="LARGERESEARCHED", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture="CivicsTree_GearButton2Tile_Completed.dds", BGU=0,BGV=(SIZE_NODE_LARGE_Y*5),HideIcon=false, IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK_DONE }; -- =========================================================================== -- MEMBERS / VARIABLES -- =========================================================================== local m_kNodeIM :table = InstanceManager:new( "NodeInstance", "Top", Controls.NodeScroller ); local m_kLargeNodeIM :table = InstanceManager:new( "LargeNodeInstance", "Top", Controls.NodeScroller ); local m_kLineIM :table = InstanceManager:new( "LineImageInstance", "LineImage",Controls.NodeScroller ); local m_kEraArtIM :table = InstanceManager:new( "EraArtInstance", "Top", Controls.FarBackArtScroller ); local m_kEraLabelIM :table = InstanceManager:new( "EraLabelInstance", "Top", Controls.ArtScroller ); local m_kEraDotIM :table = InstanceManager:new( "EraDotInstance", "Dot", Controls.ScrollbarBackgroundArt ); local m_kMarkerIM :table = InstanceManager:new( "PlayerMarkerInstance", "Top", Controls.TimelineScrollbar ); local m_kSearchResultIM :table = InstanceManager:new( "SearchResultInstance", "Root", Controls.SearchResultsStack); local m_kDiplomaticPolicyIM :table = InstanceManager:new( "DiplomaticPolicyInstance", "DiplomaticPolicy", Controls.DiplomaticStack ); local m_kEconomicPolicyIM :table = InstanceManager:new( "EconomicPolicyInstance", "EconomicPolicy", Controls.EconomicStack ); local m_kMilitaryPolicyIM :table = InstanceManager:new( "MilitaryPolicyInstance", "MilitaryPolicy", Controls.MilitaryStack ); local m_kWildcardPolicyIM :table = InstanceManager:new( "WildcardPolicyInstance", "WildcardPolicy", Controls.WildcardStack ); local m_kPathMarkerIM :table = InstanceManager:new( "ResearchPathMarker", "Top", Controls.NodeScroller); local m_kUnlocksIM :table = {}; local m_width :number= 1024; -- Screen Width (default / min spec) local m_height :number= 768; -- Screen Height (default / min spec) local m_scrollWidth :number= 1024; -- Width of the scroll bar (default to screen min_spec until set) local m_kEras :table = {}; -- type to costs local m_maxColumns :number= 0; -- # of columns (highest column #) local m_ePlayer :number= -1; local m_kAllPlayersTechData :table = {}; -- All data for local players. local m_kCurrentData :table = {}; -- Current set of data. local m_kItemDefaults :table = {}; -- Static data about items local m_kNodeGrid :table = {}; -- Static data about node location once it's laid out local m_uiNodes :table = {}; local m_uiConnectorSets :table = {}; local m_kFilters :table = {}; local m_ToggleCivicsTreeId = Input.GetActionId("ToggleCivicsTree"); -- Hot key to toggle screen open/close. local m_kGovernments :table = {}; local m_kPolicyCatalogData :table; local m_shiftDown :boolean = false; -- CQUI variables local CQUI_halfwayNotified :table = {}; -- =========================================================================== -- Return string respresenation of a prereq table -- =========================================================================== function GetPrereqsString( prereqs:table ) local out:string = ""; for _,prereq in pairs(prereqs) do if prereq == PREREQ_ID_TREE_START then out = "n/a "; else out = out .. m_kItemDefaults[prereq].Type .. " "; -- Add space between techs end end return "[" .. string.sub(out,1,string.len(out)-1) .. "]"; -- Remove trailing space end -- =========================================================================== function SetCurrentNode( hash ) if hash ~= nil then local localPlayerCulture = Players[Game.GetLocalPlayer()]:GetCulture(); -- Get the complete path to the tech local pathToCivic = localPlayerCulture:GetCivicPath( hash ); local tParameters = {}; tParameters[PlayerOperations.PARAM_CIVIC_TYPE] = pathToCivic; if m_shiftDown then tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_APPEND; else tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_EXCLUSIVE; end UI.RequestPlayerOperation(Game.GetLocalPlayer(), PlayerOperations.PROGRESS_CIVIC, tParameters); UI.PlaySound("Confirm_Civic_CivicsTree"); else UI.DataError("Attempt to change current tree item with NIL hash!"); end end -- =========================================================================== -- If the next item isn't immediate, show a path of #s traversing the tree -- to the desired node. -- =========================================================================== function RealizePathMarkers() local pCulture :table = Players[Game.GetLocalPlayer()]:GetCulture(); local kNodeIds :table = pCulture:GetCivicQueue(); -- table: index, IDs m_kPathMarkerIM:ResetInstances(); for i,nodeNumber in pairs(kNodeIds) do local pathPin = m_kPathMarkerIM:GetInstance(); if(i < 10) then pathPin.NodeNumber:SetOffsetX(PATH_MARKER_NUMBER_0_9_OFFSET); else pathPin.NodeNumber:SetOffsetX(PATH_MARKER_NUMBER_10_OFFSET); end pathPin.NodeNumber:SetText(tostring(i)); for j,node in pairs(m_kItemDefaults) do if node.Index == nodeNumber then local x:number = m_uiNodes[node.Type].x; local y:number = m_uiNodes[node.Type].y; pathPin.Top:SetOffsetX(x-PATH_MARKER_OFFSET_X); pathPin.Top:SetOffsetY(y-PATH_MARKER_OFFSET_Y); end end end end -- =========================================================================== -- Convert a virtual column # and row # to actual pixels within the -- scrollable tree area. -- =========================================================================== function ColumnRowToPixelXY( column:number, row:number) local horizontal :number = ((column-1) * COLUMNS_NODES_SPAN * COLUMN_WIDTH) + PADDING_TIMELINE_LEFT; local vertical :number = PADDING_NODE_STACK_Y + (SIZE_WIDESCREEN_HEIGHT / 2) + (row * SIZE_NODE_Y); return horizontal, vertical; end -- =========================================================================== -- Get the width of the scroll panel -- =========================================================================== function GetMaxScrollWidth() return m_maxColumns + (m_maxColumns * COLUMN_WIDTH) + PADDING_TIMELINE_LEFT; end -- =========================================================================== -- Take the default item data and build the nodes that work with it. -- One time creation, any dynamic pieces should be -- -- No state specific data (e.g., selected node) should be set here in order -- to reuse the nodes across viewing other players' trees for single seat -- multiplayer or if a (spy) game rule allows looking at another's tree. -- =========================================================================== function AllocateUI() m_uiNodes = {}; m_kNodeIM:ResetInstances(); m_kLargeNodeIM:ResetInstances(); m_uiConnectorSets = {}; m_kLineIM:ResetInstances(); -- By era, layout all items in single "sort" row local eraGrids:table = {}; -- each era has it's own "grid" of items to layout for _,item in pairs(m_kItemDefaults) do -- Create any data structures related to this era/row that don't exist: if eraGrids[item.EraType] == nil then eraGrids[item.EraType] = { rows={}, sortRow={ columns={} } }; for i= ROW_MIN, ROW_MAX, 1 do eraGrids[item.EraType].rows[i] = { columns={} }; end end -- For first placement, ignore row and place everything in the middle (row 0) local pos:number = table.count(eraGrids[item.EraType].sortRow.columns) + 1; eraGrids[item.EraType].sortRow.columns[pos] = item.Type; end -- Manually sort based on prereqs, 2(N log N) for eraType,grid in pairs(eraGrids) do local numEraItems:number = table.count(grid.sortRow.columns); if numEraItems > 1 then for pass=1,2,1 do -- Make 2 passes so the first swapped item is checked. for a=1,numEraItems do for b=a,numEraItems do if a ~= b then for _,prereq in ipairs(m_kItemDefaults[grid.sortRow.columns[a] ].Prereqs) do if prereq == grid.sortRow.columns[b] then grid.sortRow.columns[a], grid.sortRow.columns[b] = grid.sortRow.columns[b], grid.sortRow.columns[a]; -- swap LUA style end end end end end end end end -- Unflatten single, traversing each era grid from left to right, pushing the item to the right if it hits a prereq for eraType,grid in pairs(eraGrids) do local maxColumns:number = table.count(grid.sortRow.columns); -- Worst case, straight line while ( table.count(grid.sortRow.columns) > 0 ) do local typeName :string = table.remove( grid.sortRow.columns, 1); -- Rip off first item in sort row (next item to place) local item :table = m_kItemDefaults[typeName]; local pos :number = 1; -- No prereqs? Just put at start, otherwise push forward past them all. if item.Prereqs ~= nil then for _,prereq in ipairs(item.Prereqs) do -- For every prereq local isPrereqMatched :boolean = false; for x=pos,maxColumns,1 do -- For every column (from last highest found start position) for y=ROW_MIN, ROW_MAX,1 do -- For every row in the column if grid.rows[y].columns[x] ~= nil then -- Is a prereq in that position of the grid? if prereq == grid.rows[y].columns[x] then -- And is it a prereq for this item? pos = x + 1; -- If so, this item can only exist at least 1 column further over from the prereq isPrereqMatched = true; break; end end end if isPrereqMatched then -- Ensuring this node wasn't just placed on top of another: while( grid.rows[item.UITreeRow].columns[pos] ~= nil ) do pos = pos + 1; end break; end end end end grid.rows[item.UITreeRow].columns[pos] = typeName; -- Set for future lookups. item.Column = pos; -- Set which column within era item exists. if pos > m_kEras[item.EraType].NumColumns then m_kEras[item.EraType].NumColumns = pos; end end end -- Determine total # of columns prior to a given era, and max columns overall. local priorColumns:number = 0; m_maxColumns = 0; for i=1,table.count(m_kEras),1 do for era,eraData in pairs(m_kEras) do if eraData.Index == i then -- Ensure indexed order eraData.PriorColumns = priorColumns; priorColumns = priorColumns + eraData.NumColumns + 1; -- Add one for era art between if i==table.count(m_kEras) then -- Last era determins total # of columns in tree m_maxColumns = priorColumns; end break; end end end -- Create grid used to route lines, determine maximum number of columns. m_kNodeGrid = {}; for i = ROW_MIN,ROW_MAX,1 do m_kNodeGrid[i] = {}; end for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; local columnNum :number = era.PriorColumns + item.Column; m_kNodeGrid[item.UITreeRow][columnNum] = true; end -- Era divider information m_kEraArtIM:ResetInstances(); m_kEraLabelIM:ResetInstances(); m_kEraDotIM:ResetInstances(); for era,eraData in pairs(m_kEras) do local instArt :table = m_kEraArtIM:GetInstance(); if eraData.BGTexture ~= nil then instArt.BG:SetTexture( eraData.BGTexture ); else UI.DataError("Civic tree is unable to find an EraCivicBackgroundTexture entry for era '"..eraData.Description.."'; using a default."); instArt.BG:SetTexture(PIC_DEFAULT_ERA_BACKGROUND); end local startx, _ = ColumnRowToPixelXY( eraData.PriorColumns + 1, 0); instArt.Top:SetOffsetX( (startx ) * (1/PARALLAX_ART_SPEED) ); instArt.Top:SetOffsetY( (SIZE_WIDESCREEN_HEIGHT * 0.5) - (instArt.BG:GetSizeY()*0.5) ); instArt.Top:SetSizeVal(eraData.NumColumns*SIZE_NODE_X, 600); local inst:table = m_kEraLabelIM:GetInstance(); local eraMarkerx, _ = ColumnRowToPixelXY( eraData.PriorColumns + 1, 0); inst.Top:SetOffsetX( (eraMarkerx - (SIZE_NODE_X*0.5)) * (1/PARALLAX_SPEED) ); inst.EraTitle:SetText( Locale.Lookup("LOC_GAME_ERA_DESC",eraData.Description) ); -- Dots on scrollbar local markerx:number = (eraData.PriorColumns / m_maxColumns) * Controls.ScrollbarBackgroundArt:GetSizeX(); if markerx > 0 then local inst:table = m_kEraDotIM:GetInstance(); inst.Dot:SetOffsetX(markerx); end end local playerId = Game.GetLocalPlayer(); if (playerId == -1) then return; end -- Actually build UI nodes for _,item in pairs(m_kItemDefaults) do local civic = GameInfo.Civics[item.Index]; local civicType = civic and civic.CivicType; local unlockableTypes = GetUnlockablesForCivic_Cached(civicType, playerId); local node :table; local numUnlocks :number = 0; if unlockableTypes ~= nil then for _, unlockItem in ipairs(unlockableTypes) do local typeInfo = GameInfo.Types[unlockItem[1]]; if typeInfo.Kind == "KIND_GOVERNMENT" then numUnlocks = numUnlocks + 4; -- 4 types of policy slots else numUnlocks = numUnlocks + 1; end end end -- Create node based on # of unlocks for this civic. if numUnlocks <= 8 then node = m_kNodeIM:GetInstance(); else node = m_kLargeNodeIM:GetInstance(); node.IsLarge = true; end node.Top:SetTag( item.Hash ); -- Set the hash of the civic to the tag of the node (for tutorial to be able to callout) local era:table = m_kEras[item.EraType]; -- Horizontal # = All prior nodes across all previous eras + node position in current era (based on cost vs. other nodes in that era) local horizontal, vertical = ColumnRowToPixelXY(era.PriorColumns + item.Column, item.UITreeRow ); -- Add data fields to UI component node.Type = civicType; -- Dynamically add "Type" field to UI node for quick look ups in item data table. node.x = horizontal; -- Granted x,y can be looked up via GetOffset() but caching the values here for node.y = vertical - VERTICAL_CENTER; -- other LUA functions to use removes the necessity of a slow C++ roundtrip. if node["unlockIM"] ~= nil then node["unlockIM"]:DestroyInstances() end node["unlockIM"] = InstanceManager:new( "UnlockInstance", "UnlockIcon", node.UnlockStack ); if node["unlockGOV"] ~= nil then node["unlockGOV"]:DestroyInstances() end node["unlockGOV"] = InstanceManager:new( "GovernmentIcon", "GovernmentInstanceGrid", node.UnlockStack ); PopulateUnlockablesForCivic(playerId, item.Index, node["unlockIM"], node["unlockGOV"], function() SetCurrentNode(item.Hash); end); -- What happens when clicked function OpenPedia() LuaEvents.OpenCivilopedia(civicType); end node.NodeButton:RegisterCallback( Mouse.eLClick, function() SetCurrentNode(item.Hash); end); node.OtherStates:RegisterCallback( Mouse.eLClick, function() SetCurrentNode(item.Hash); end); -- Only wire up Civilopedia handlers if not in a on-rails tutorial. if IsTutorialRunning()==false then node.NodeButton:RegisterCallback( Mouse.eRClick, OpenPedia); node.OtherStates:RegisterCallback( Mouse.eRClick, OpenPedia); end -- Set position and save. node.Top:SetOffsetVal( horizontal, vertical); m_uiNodes[item.Type] = node; end if Controls.TreeStart ~= nil then local h,v = ColumnRowToPixelXY( TREE_START_COLUMN, TREE_START_ROW ); Controls.TreeStart:SetOffsetVal( h,v ); end -- Determine the lines between nodes. -- NOTE: Potentially move this to view, since lines are constantly change in look, but -- it makes sense to have at least the routes computed here since they are -- consistent regardless of the look. local spaceBetweenColumns:number = COLUMN_WIDTH - SIZE_NODE_X; for _,item in pairs(m_kItemDefaults) do local node:table = m_uiNodes[item.Type]; for _,prereqId in pairs(item.Prereqs) do local previousRow :number = 0; local previousColumn:number = 0; if prereqId == PREREQ_ID_TREE_START then previousRow = TREE_START_ROW; previousColumn = TREE_START_COLUMN; else local prereq :table = m_kItemDefaults[prereqId]; previousRow = prereq.UITreeRow; previousColumn = m_kEras[prereq.EraType].PriorColumns + prereq.Column; end local startColumn :number = m_kEras[item.EraType].PriorColumns + item.Column; local column :number = startColumn - 1; -- start one back while m_kNodeGrid[item.UITreeRow][column] == nil and column > previousColumn do -- keep working backwards until hitting a node column = column - 1; end if previousRow == TREE_START_NONE_ID then -- Nothing goes before this, not even a fake start area. elseif previousRow < item.UITreeRow or previousRow > item.UITreeRow then -- Obtain the line objects local inst :table = m_kLineIM:GetInstance(); local line1 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line2 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line3 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line4 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line5 :table = inst.LineImage; -- Find all the empty space before the node before to make a bend. local LineStartX:number = node.x; local LineEndX1 :number = (node.x - LINE_LENGTH_BEFORE_CURVE ) ; local LineEndX2, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX2 = LineEndX2 + SIZE_NODE_X; local LineY1 :number; local LineY2 :number; if previousRow < item.UITreeRow then LineY2 = node.y-((item.UITreeRow-previousRow)*SIZE_NODE_Y)+ LINE_VERTICAL_OFFSET;-- above LineY1 = node.y -LINE_VERTICAL_OFFSET; else LineY2 = node.y+((previousRow-item.UITreeRow)*SIZE_NODE_Y)- LINE_VERTICAL_OFFSET;-- below LineY1 = node.y +LINE_VERTICAL_OFFSET; end line1:SetOffsetVal(LineEndX1 + SIZE_PATH_HALF, LineY1 - SIZE_PATH_HALF); line1:SetSizeVal( LineStartX - LineEndX1 - SIZE_PATH_HALF, SIZE_PATH); line2:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, LineY1 - SIZE_PATH_HALF); line2:SetSizeVal( SIZE_PATH, SIZE_PATH); if previousRow < item.UITreeRow then line2:SetTexture("Controls_TreePathDashSE"); else line2:SetTexture("Controls_TreePathDashNE"); end line3:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, math.min(LineY1 + SIZE_PATH_HALF, LineY2 + SIZE_PATH_HALF) ); line3:SetSizeVal( SIZE_PATH, math.abs(LineY1 - LineY2) - SIZE_PATH ); line3:SetTexture("Controls_TreePathDashNS"); line4:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, LineY2 - SIZE_PATH_HALF); line4:SetSizeVal( SIZE_PATH, SIZE_PATH); if previousRow < item.UITreeRow then line4:SetTexture("Controls_TreePathDashES"); else line4:SetTexture("Controls_TreePathDashEN"); end line5:SetSizeVal( LineEndX1 - LineEndX2 - SIZE_PATH_HALF, SIZE_PATH ); line5:SetOffsetVal(LineEndX2, LineY2 - SIZE_PATH_HALF); -- Directly store the line (not instance) with a key name made up of this type and the prereq's type. m_uiConnectorSets[item.Type..","..prereqId] = {line1,line2,line3,line4,line5}; else -- Prereq is on the same row local inst:table = m_kLineIM:GetInstance(); local line:table = inst.LineImage; local end1, _ = ColumnRowToPixelXY( column, item.UITreeRow ); end1 = end1 + SIZE_NODE_X; line:SetOffsetVal(end1, node.y - SIZE_PATH_HALF); line:SetSizeVal( node.x - end1, SIZE_PATH); -- Directly store the line (not instance) with a key name made up of this type and the prereq's type. m_uiConnectorSets[item.Type..","..prereqId] = {line}; end end end Controls.NodeScroller:CalculateSize(); Controls.NodeScroller:ReprocessAnchoring(); Controls.ArtScroller:CalculateSize(); Controls.FarBackArtScroller:CalculateSize(); Controls.NodeScroller:RegisterScrollCallback( OnScroll ); -- We use a separate BG within the PeopleScroller control since it needs to scroll with the contents Controls.ModalBG:SetHide(true); Controls.ModalScreenClose:RegisterCallback(Mouse.eLClick, OnClose); Controls.ModalScreenTitle:SetText(Locale.ToUpper(Locale.Lookup("LOC_CIVICS_TREE_HEADER"))); end -- =========================================================================== -- UI Event -- Callback when the main scroll panel is scrolled. -- =========================================================================== function OnScroll( control:table, percent:number ) -- Parallax -- ??TRON re-examine: --Controls.ArtScroller:SetScrollValue( percent * PARALLAX_SPEED); --Controls.FarBackArtScroller:SetScrollValue( percent * PARALLAX_ART_SPEED); Controls.ArtScroller:SetScrollValue( percent ); Controls.FarBackArtScroller:SetScrollValue( percent ); -- Audio if percent==0 or percent==1.0 then UI.PlaySound("UI_TechTree_ScrollTick_End"); else UI.PlaySound("UI_TechTree_ScrollTick"); end end -- =========================================================================== -- Display the state of the tree (filter, node display, etc...) based on the -- active player's item data. -- Viewxx -- =========================================================================== function View( playerTechData:table ) -- Output the node states for the tree for _,node in pairs(m_uiNodes) do local item :table = m_kItemDefaults[node.Type]; -- static item data local live :table = playerTechData[DATA_FIELD_LIVEDATA][node.Type]; -- live (changing) data local artInfo :table = (node.IsLarge) and STATUS_ART_LARGE[live.Status] or STATUS_ART[live.Status]; if(live.Status == ITEM_STATUS.RESEARCHED) then for _,prereqId in pairs(item.Prereqs) do if(prereqId ~= PREREQ_ID_TREE_START) then local prereq :table = m_kItemDefaults[prereqId]; local previousRow :number = prereq.UITreeRow; local previousColumn:number = m_kEras[prereq.EraType].PriorColumns; for lineNum,line in pairs(m_uiConnectorSets[item.Type..","..prereqId]) do if(lineNum == 1 or lineNum == 5) then line:SetTexture("Controls_TreePathEW"); end if( lineNum == 3) then line:SetTexture("Controls_TreePathNS"); end if(lineNum==2)then if previousRow < item.UITreeRow then line:SetTexture("Controls_TreePathSE"); else line:SetTexture("Controls_TreePathNE"); end end if(lineNum==4)then if previousRow < item.UITreeRow then line:SetTexture("Controls_TreePathES"); else line:SetTexture("Controls_TreePathEN"); end end end end end end node.NodeName:SetColor( artInfo.TextColor0, 0 ); node.NodeName:SetColor( artInfo.TextColor1, 1 ); if m_debugShowIDWithName then node.NodeName:SetText( tostring(item.Index).." "..Locale.Lookup(item.Name) ); -- Debug output else node.NodeName:SetText( Locale.ToUpper( Locale.Lookup(item.Name) )); -- Normal output end if live.Turns > 0 then node.Turns:SetHide( false ); node.Turns:SetColor( artInfo.TextColor0, 0 ); node.Turns:SetColor( artInfo.TextColor1, 1 ); node.Turns:SetText( Locale.Lookup("LOC_TECH_TREE_TURNS",live.Turns) ); else node.Turns:SetHide( true ); end if item.IsBoostable and live.Status ~= ITEM_STATUS.RESEARCHED then node.BoostIcon:SetHide( false ); node.BoostText:SetHide( false ); node.BoostText:SetColor( artInfo.TextColor0, 0 ); node.BoostText:SetColor( artInfo.TextColor1, 1 ); local boostText:string; if live.IsBoosted then boostText = TXT_BOOSTED.." "..item.BoostText; node.BoostIcon:SetTexture( PIC_BOOST_ON ); node.BoostMeter:SetHide( false ); else boostText = TXT_TO_BOOST.." "..item.BoostText; node.BoostedBack:SetHide( true ); node.BoostIcon:SetTexture( PIC_BOOST_OFF ); node.BoostMeter:SetHide( false ); local boostAmount = (item.BoostAmount*.01) + (live.Progress/ live.Cost); node.BoostMeter:SetPercent( boostAmount ); end TruncateStringWithTooltip(node.BoostText, MAX_BEFORE_TRUNC_TO_BOOST, boostText); else node.BoostIcon:SetHide( true ); node.BoostText:SetHide( true ); node.BoostedBack:SetHide( true ); node.BoostMeter:SetHide( true ); end if live.Status == ITEM_STATUS.CURRENT then node.GearAnim:SetHide( false ); else node.GearAnim:SetHide( true ); end if live.Progress > 0 then node.ProgressMeter:SetHide( false ); node.ProgressMeter:SetPercent(live.Progress / live.Cost); else node.ProgressMeter:SetHide( true ); end -- Set art for icon area if(item.Type ~= nil) then local iconName :string = DATA_ICON_PREFIX .. item.Type; if (artInfo.Name == "BLOCKED" or artInfo.Name == "LARGEBLOCKED") then node.IconBacking:SetHide(true); iconName = iconName .. "_FOW"; node.BoostMeter:SetColor(0x66ffffff); node.BoostIcon:SetColor(0x66000000); else node.IconBacking:SetHide(false); iconName = iconName; node.BoostMeter:SetColor(0xffffffff); node.BoostIcon:SetColor(0xffffffff); end local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(iconName,42); if (textureOffsetX ~= nil) then node.Icon:SetTexture( textureOffsetX, textureOffsetY, textureSheet ); end end if artInfo.IsButton then node.OtherStates:SetHide( true ); node.NodeButton:SetTextureOffsetVal( artInfo.BGU, artInfo.BGV ); else node.OtherStates:SetHide( false ); node.OtherStates:SetTextureOffsetVal( artInfo.BGU, artInfo.BGV ); end if artInfo.FillTexture ~= nil then node.FillTexture:SetHide( false ); node.FillTexture:SetTexture( artInfo.FillTexture ); else node.FillTexture:SetHide( true ); end if artInfo.BoltOn then node.Bolt:SetTexture(PIC_BOLT_ON); else node.Bolt:SetTexture(PIC_BOLT_OFF); end node.NodeButton:SetToolTipString(ToolTipHelper.GetToolTip(item.Type, Game.GetLocalPlayer())); node.IconBacking:SetTexture(artInfo.IconBacking); -- Darken items not making it past filter. local currentFilter:table = playerTechData[DATA_FIELD_UIOPTIONS].filter; if currentFilter == nil or currentFilter.Func == nil or currentFilter.Func( item.Type ) then node.FilteredOut:SetHide( true ); else node.FilteredOut:SetHide( false ); end -- Show/Hide Recommended Icon if live.IsRecommended and live.AdvisorType ~= nil then node.RecommendedIcon:SetIcon(live.AdvisorType); node.RecommendedIcon:SetHide(false); else node.RecommendedIcon:SetHide(true); end end -- Fill in where the markers (representing players) are at: m_kMarkerIM:ResetInstances(); local PADDING :number = 24; local thisPlayerID :number = Game.GetLocalPlayer(); local markers :table = m_kCurrentData[DATA_FIELD_PLAYERINFO].Markers; for _,markerStat in ipairs( markers ) do -- Only build a marker if a player has started researching... if markerStat.HighestColumn ~= -1 then local instance :table = m_kMarkerIM:GetInstance(); if markerStat.IsPlayerHere then -- Representing the player viewing the tree instance.Portrait:SetHide( true ); instance.TurnGrid:SetHide( false ); instance.TurnLabel:SetText( Locale.Lookup("LOC_TECH_TREE_TURN_NUM" )); instance.TurnNumber:SetText( tostring(Game.GetCurrentGameTurn()) ); local turnLabelWidth = PADDING + instance.TurnLabel:GetSizeX() + instance.TurnNumber:GetSizeX(); instance.TurnGrid:SetSizeX( turnLabelWidth ); instance.Marker:SetTexture( PIC_MARKER_PLAYER ); instance.Marker:SetSizeVal( SIZE_MARKER_PLAYER_X, SIZE_MARKER_PLAYER_Y ); else -- An other player instance.TurnGrid:SetHide( true ); instance.Marker:SetTexture( PIC_MARKER_OTHER ); instance.Marker:SetSizeVal( SIZE_MARKER_OTHER_X, SIZE_MARKER_OTHER_Y ); end -- Different content in marker based on if there is just 1 player in the column, or more than 1 local tooltipString :string = Locale.Lookup("LOC_TREE_ERA", Locale.Lookup(GameInfo.Eras[markerStat.HighestEra].Name) ).."[NEWLINE]"; local numOfPlayersAtThisColumn :number = table.count(markerStat.PlayerNums); if numOfPlayersAtThisColumn < 2 then instance.Num:SetHide( true ); local playerNum :number = markerStat.PlayerNums[1]; local pPlayerConfig :table = PlayerConfigurations[playerNum]; tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetPlayerName()); -- TODO: Temporary using player name until leaderame is fixed if not markerStat.IsPlayerHere then local iconName:string = "ICON_"..pPlayerConfig:GetLeaderTypeName(); instance.Portrait:SetHide( false ); instance.Portrait:SetIcon( iconName ); end else instance.Portrait:SetHide( true ); instance.Num:SetHide( false ); instance.Num:SetText(tostring(numOfPlayersAtThisColumn)); for i,playerNum in ipairs(markerStat.PlayerNums) do local pPlayerConfig :table = PlayerConfigurations[playerNum]; --[[ TODO: The human player, player 0, has whack values! No leader name coming from engine! local name = pPlayerConfig:GetPlayerName(); local nick = pPlayerConfig:GetNickName(); local leader = pPlayerConfig:GetLeaderName(); local civ = pPlayerConfig:GetCivilizationTypeName(); local isHuman = pPlayerConfig:IsHuman(); print("debug info:",name,nick,leader,civ,isHuman); ]] --tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetLeaderName()); tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetPlayerName()); -- TODO:: Temporary using player name until leaderame is fixed if i < numOfPlayersAtThisColumn then tooltipString = tooltipString.."[NEWLINE]"; end end end instance.Marker:SetToolTipString( tooltipString ); local MARKER_OFFSET_START:number = 20; local markerPercent :number = math.clamp( markerStat.HighestColumn / m_maxColumns, 0, 1 ); local markerX :number = MARKER_OFFSET_START + (markerPercent * m_scrollWidth ); instance.Top:SetOffsetVal(markerX ,0); end end RealizePathMarkers(); RealizeFilterPulldown(); RealizeKeyPanel(); RealizeGovernmentPanel(); end -- -- -- function GetPlayerGovernment(ePlayer:number) local kPlayer :table = Players[ePlayer]; local playerCulture :table = kPlayer:GetCulture(); local kCurrentGovernment:table; local kGovernmentInfo:table = {}; local governmentRowId :number = playerCulture:GetCurrentGovernment(); if governmentRowId ~= -1 then kCurrentGovernment = GameInfo.Governments[governmentRowId]; kGovernmentInfo["NAMES"] = Locale.Lookup(kCurrentGovernment.Name); end kGovernmentInfo["DIPLOMATIC"] = 0; kGovernmentInfo["ECONOMIC"] = 0; kGovernmentInfo["WILDCARD"] = 0; kGovernmentInfo["MILITARY"] = 0; kGovernmentInfo["DIPLOMATICPOLICIES"] = {}; kGovernmentInfo["ECONOMICPOLICIES"] = {}; kGovernmentInfo["MILITARYPOLICIES"] = {}; kGovernmentInfo["WILDCARDPOLICIES"] = {}; local numSlots:number = playerCulture:GetNumPolicySlots(); for i = 0, numSlots-1, 1 do local iSlotType :number = playerCulture:GetSlotType(i); local iSlotPolicy :number= playerCulture:GetSlotPolicy(i); local rowSlotType :string = GameInfo.GovernmentSlots[iSlotType].GovernmentSlotType; if rowSlotType == "SLOT_DIPLOMATIC" then kGovernmentInfo["DIPLOMATIC"] = kGovernmentInfo["DIPLOMATIC"]+1; table.insert(kGovernmentInfo["DIPLOMATICPOLICIES"], iSlotPolicy); elseif rowSlotType == "SLOT_ECONOMIC" then kGovernmentInfo["ECONOMIC"] = kGovernmentInfo["ECONOMIC"]+1; table.insert(kGovernmentInfo["ECONOMICPOLICIES"], iSlotPolicy); elseif rowSlotType == "SLOT_MILITARY" then kGovernmentInfo["MILITARY"] = kGovernmentInfo["MILITARY"]+1; table.insert(kGovernmentInfo["MILITARYPOLICIES"], iSlotPolicy); elseif rowSlotType == "SLOT_WILDCARD" then kGovernmentInfo["WILDCARD"] = kGovernmentInfo["WILDCARD"]+1; table.insert(kGovernmentInfo["WILDCARDPOLICIES"], iSlotPolicy); else UI.DataError("On initialization; unhandled slot type for a policy '"..rowSlotType.."'"); end end return kGovernmentInfo; end -- =========================================================================== -- Load all the 'live' data for a player. -- =========================================================================== function GetLivePlayerData( ePlayer:number, eCompletedCivic:number ) -- If first time, initialize player data tables. local data :table = m_kAllPlayersTechData[ePlayer]; if data == nil then -- Initialize player's top level tables: data = {}; data[DATA_FIELD_LIVEDATA] = {}; data[DATA_FIELD_PLAYERINFO] = {}; data[DATA_FIELD_UIOPTIONS] = {}; data[DATA_FIELD_GOVERNMENT] = {}; -- Initialize data, and sub tables within the top tables. data[DATA_FIELD_PLAYERINFO].Player = ePlayer; -- Number of this player data[DATA_FIELD_PLAYERINFO].Markers = {}; -- Hold a condenced, UI-ready version of stats data[DATA_FIELD_PLAYERINFO].Stats = {}; -- Hold stats on where each player is (based on what this player can see) end local kPlayer :table = Players[ePlayer]; local playerCulture :table = kPlayer:GetCulture(); local currentTechID :number = playerCulture:GetProgressingCivic(); -- DEBUG: Output header to console. if m_debugOutputTechInfo then print(" Item Id Status Progress $ Era Prereqs"); print("------------------------------ --- ---------- --------- --- ---------------- --------------------------"); end -- Loop through all items and place in appropriate buckets as well -- read in the associated information for it. for type,item in pairs(m_kItemDefaults) do local status :number = ITEM_STATUS.BLOCKED; local turnsLeft :number = 0; if eCompletedCivic == item.Index or playerCulture:HasCivic(item.Index) then status = ITEM_STATUS.RESEARCHED; elseif item.Index == currentTechID then status = ITEM_STATUS.CURRENT; turnsLeft = playerCulture:GetTurnsLeft(); elseif playerCulture:CanProgress(item.Index) then status = ITEM_STATUS.READY; turnsLeft = playerCulture:GetTurnsToProgressCivic(item.Index); else turnsLeft = playerCulture:GetTurnsToProgressCivic(item.Index); end data[DATA_FIELD_LIVEDATA][type] = { Cost = playerCulture:GetCultureCost(item.Index), IsBoosted = playerCulture:HasBoostBeenTriggered(item.Index), Progress = playerCulture:GetCulturalProgress(item.Index), Status = status, Turns = turnsLeft } -- DEBUG: Output to console detailed information about the tech. if m_debugOutputTechInfo then local this:table = data[DATA_FIELD_LIVEDATA][type]; print( string.format("%30s %-3d %-10s %4d/%-4d %3d %-16s %s", type,item.Index, STATUS_ART[status].Name, this.Progress, this.Cost, this.Turns, item.EraType, GetPrereqsString(item.Prereqs) )); end end local players = Game.GetPlayers{Major = true}; -- Determine where all players are. local playerVisibility = PlayersVisibility[ePlayer]; if playerVisibility ~= nil then for i, otherPlayer in ipairs(players) do local playerID :number = otherPlayer:GetID(); local playerCulture :table = players[i]:GetCulture(); local currentCivic :number = playerCulture:GetProgressingCivic(); data[DATA_FIELD_PLAYERINFO].Stats[playerID] = { CurrentID = currentCivic, HasMet = kPlayer:GetDiplomacy():HasMet(playerID) or playerID==ePlayer or m_debugShowAllMarkers; HighestColumn = -1, -- where they are in the timeline HighestEra = "" }; -- The latest tech a player may be researching may not be the one -- furthest along in time; so go through ALL the techs and track -- the highest column of all researched tech. local highestColumn :number = -1; local highestEra :string = ""; for _,item in pairs(m_kItemDefaults) do if playerCulture:HasCivic(item.Index) then local column:number = item.Column + m_kEras[item.EraType].PriorColumns; if column > highestColumn then highestColumn = column; highestEra = item.EraType; end end end data[DATA_FIELD_PLAYERINFO].Stats[playerID].HighestColumn = highestColumn; data[DATA_FIELD_PLAYERINFO].Stats[playerID].HighestEra = highestEra; end end -- All player data is added.. build markers data based on player data. local checkedID:table = {}; data[DATA_FIELD_PLAYERINFO].Markers = {}; for playerID:number, targetPlayer:table in pairs(data[DATA_FIELD_PLAYERINFO].Stats) do -- Only look for IDs that haven't already been merged into a marker. if checkedID[playerID] == nil and targetPlayer.HasMet then checkedID[playerID] = true; local markerData:table = {}; if data[DATA_FIELD_PLAYERINFO].Markers[playerID] ~= nil then markerData = data[DATA_FIELD_PLAYERINFO].Markers[playerID]; markerData.HighestColumn = targetPlayer.HighestColumn; markerData.HighestEra = targetPlayer.HighestEra; markerData.IsPlayerHere = (playerID == ePlayer); else markerData = { HighestColumn = targetPlayer.HighestColumn, -- Which column this marker should be placed HighestEra = targetPlayer.HighestEra, IsPlayerHere = (playerID == ePlayer), PlayerNums = {playerID}} -- All players who share this marker spot table.insert( data[DATA_FIELD_PLAYERINFO].Markers, markerData ); end -- SPECIAL CASE: Current player starts at column 0 so it's immediately visible on timeline: if playerID == ePlayer and markerData.HighestColumn == -1 then markerData.HighestColumn = 0; local firstEra:table = nil; for _,era in pairs(m_kEras) do if firstEra == nil or era.Index < firstEra.Index then firstEra = era; end end markerData.HighestEra = firstEra.Index; end -- Traverse all the IDs and merge them with this one. for anotherID:number, anotherPlayer:table in pairs(data[DATA_FIELD_PLAYERINFO].Stats) do -- Don't add if: it's outself, if hasn't researched at least 1 tech, if we haven't met if playerID ~= anotherID and anotherPlayer.HighestColumn > -1 and anotherPlayer.HasMet then if markerData.HighestColumn == data[DATA_FIELD_PLAYERINFO].Stats[anotherID].HighestColumn then checkedID[anotherID] = true; -- Need to do this check if player's ID didn't show up first in the list in creating the marker. if anotherID == ePlayer then markerData.IsPlayerHere = true; end local foundAnotherID:boolean = false; for _, playernumsID in pairs(markerData.PlayerNums) do if not foundAnotherID and playernumsID == anotherID then foundAnotherID = true; end end if not foundAnotherID then table.insert( markerData.PlayerNums, anotherID ); end end end end end end data[DATA_FIELD_GOVERNMENT] = GetPlayerGovernment(ePlayer); return data; end -- =========================================================================== function OnGovernmentChanged() local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then if m_ePlayer ~= ePlayer then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( ePlayer, -1 ); end end end -- =========================================================================== function OnGovernmentPolicyChanged() local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then if m_ePlayer ~= ePlayer then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( ePlayer, -1 ); end end end -- =========================================================================== function OnLocalPlayerTurnBegin() local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then if m_ePlayer ~= ePlayer then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( ePlayer, -1 ); end -------------------------------------------------------------------------- -- CQUI Check for Civic Progress -- Get the current tech local kPlayer :table = Players[ePlayer]; local playerCivics :table = kPlayer:GetCulture(); local currentCivicID :number = playerCivics:GetProgressingCivic(); local isCurrentBoosted :boolean = playerCivics:HasBoostBeenTriggered(currentCivicID); -- Make sure there is a civic selected before continuing with checks if currentCivicID ~= -1 then local civicName = GameInfo.Civics[currentCivicID].Name; local civicType = GameInfo.Civics[currentCivicID].Type; local currentCost = playerCivics:GetCultureCost(currentCivicID); local currentProgress = playerCivics:GetCulturalProgress(currentCivicID); local currentYield = playerCivics:GetCultureYield(); local percentageToBeDone = (currentProgress + currentYield) / currentCost; local percentageNextTurn = (currentProgress + currentYield*2) / currentCost; local CQUI_halfway:number = .5; -- Finds boost amount, always 50 in base game, China's +10% modifier is not applied here for row in GameInfo.Boosts() do if(row.CivicType == civicType) then CQUI_halfway = (100 - row.Boost) / 100; break; end end --If playing as china, apply boost modifier. Not sure where I can query this value... if(PlayerConfigurations[Game.GetLocalPlayer()]:GetCivilizationTypeName() == "CIVILIZATION_CHINA") then CQUI_halfway = CQUI_halfway - .1; end -- Is it greater than 50% and has yet to be displayed? if isCurrentBoosted then CQUI_halfwayNotified[civicName] = true; elseif percentageNextTurn >= CQUI_halfway and CQUI_halfwayNotified[civicName] ~= true then LuaEvents.CQUI_AddStatusMessage("The current Civic, " .. Locale.Lookup( civicName ) .. ", is one turn away from maximum Inspiration potential.", 10, CQUI_STATUS_MESSAGE_CIVIC); CQUI_halfwayNotified[civicName] = true; end end -- end of if currentCivivID ~= -1 -------------------------------------------------------------------------- end -- end of ePlayer ~= -1 end -- =========================================================================== -- EVENT -- Player turn is ending -- =========================================================================== function OnLocalPlayerTurnEnd() -- If current data set is for the player, save back any changes into -- the table of player tables. local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then if m_kCurrentData[DATA_FIELD_PLAYERINFO].Player == ePlayer then m_kAllPlayersTechData[ePlayer] = m_kCurrentData; end end if(GameConfiguration.IsHotseat()) then Close(); end end -- =========================================================================== function OnCivicChanged( ePlayer:number, eTech:number ) if ePlayer == Game.GetLocalPlayer() then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( m_ePlayer, -1 ); if not ContextPtr:IsHidden() then View( m_kCurrentData ); end end end -- =========================================================================== function OnCivicComplete( ePlayer:number, eTech:number) if ePlayer == Game.GetLocalPlayer() then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( m_ePlayer, eTech ); if not ContextPtr:IsHidden() then View( m_kCurrentData ); end -------------------------------------------------------------------------- -- CQUI Civic Complete -- Get the current tech local kPlayer :table = Players[ePlayer]; local currentCivicID :number = eTech; -- Make sure there is a civic selected before continuing with checks if currentCivicID ~= -1 then local civicName = GameInfo.Civics[currentCivicID].Name; LuaEvents.CQUI_AddStatusMessage(Locale.Lookup("LOC_CIVIC_BOOST_COMPLETE", civicName), 10, CQUI_STATUS_MESSAGE_CIVIC); end -- end of if currentCivivID ~= -1 -------------------------------------------------------------------------- end end -- =========================================================================== -- Initially size static UI elements -- (or re-size if screen resolution changed) -- =========================================================================== function Resize() m_width, m_height = UIManager:GetScreenSizeVal(); -- Cache screen dimensions m_scrollWidth = m_width - 80; -- Scrollbar area (where markers are placed) slightly smaller than screen width local keyHeight:number = SIZE_WIDESCREEN_HEIGHT - (SIZE_OPTIONS_Y + SIZE_TIMELINE_AREA_Y + SIZE_TOP_AREA_Y); if not Controls.GovernmentPanel:IsHidden() then keyHeight = keyHeight - SIZE_GOVTPANEL_HEIGHT; end Controls.KeyPanel:SetSizeY(keyHeight); Controls.KeyScroll:SetSizeY(keyHeight-20); if(Controls.KeyPanel:IsHidden()) then Controls.GovernmentPanel:SetOffsetY(-87); else Controls.GovernmentPanel:SetOffsetY(keyHeight - 90); end -- Determine how far art will span. -- First obtain the size of the tree by taking the visible size and multiplying it by the ratio of the full content local scrollPanelX:number = (Controls.NodeScroller:GetSizeX() / Controls.NodeScroller:GetRatio()); local artAndEraScrollWidth:number = scrollPanelX * (1/PARALLAX_SPEED); Controls.ArtParchmentDecoTop:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentDecoBottom:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentRippleTop:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentRippleBottom:SetSizeX( artAndEraScrollWidth ); Controls.ForceSizeX:SetSizeX( artAndEraScrollWidth ); Controls.ArtScroller:CalculateSize(); Controls.ArtCornerGrungeTR:ReprocessAnchoring(); Controls.ArtCornerGrungeBR:ReprocessAnchoring(); local PADDING_DUE_TO_LAST_BACKGROUND_ART_IMAGE:number = 100; local backArtScrollWidth:number = scrollPanelX * (1/PARALLAX_ART_SPEED); Controls.Background:SetSizeX( backArtScrollWidth + PADDING_DUE_TO_LAST_BACKGROUND_ART_IMAGE ); Controls.Background:SetSizeY( SIZE_WIDESCREEN_HEIGHT - (SIZE_TIMELINE_AREA_Y-8) ); Controls.FarBackArtScroller:CalculateSize(); Controls.KeyScroll:CalculateSize(); end -- =========================================================================== function OnUpdateUI( type:number, tag:string, iData1:number, iData2:number, strData1:string) if type == SystemUpdateUI.ScreenResize then Resize(); end end -- =========================================================================== -- Obtain the data from the DB that doesn't change -- Base costs and relationships (prerequisites) -- RETURN: A table of node data (techs/civics/etc...) with a prereq for each entry. -- =========================================================================== function PopulateItemData( tableName:string, tableColumn:string, prereqTableName:string, itemColumn:string, prereqColumn:string) -- Build main item table. m_kItemDefaults = {}; local index :number = 0; function GetHash(t) local r = GameInfo.Types[t]; if(r) then return r.Hash; else return 0; end end for row:table in GameInfo[tableName]() do local entry:table = {}; entry.Type = row[tableColumn]; entry.Name = row.Name; entry.BoostText = ""; entry.Column = -1; -- Dynamically computed during UI layout entry.Cost = row.Cost; entry.Description = row.Description and Locale.Lookup( row.Description ); entry.EraType = row.EraType; entry.Hash = GetHash(entry.Type); entry.Index = index; entry.IsBoostable = false; entry.Prereqs = {}; entry.UITreeRow = row.UITreeRow; entry.Unlocks = {}; -- Each unlock has: unlockType, iconUnavail, iconAvail, tooltip -- Boost? for boostRow in GameInfo.Boosts() do if boostRow.CivicType == entry.Type then entry.BoostText = Locale.Lookup( boostRow.TriggerDescription ); entry.IsBoostable = true; entry.BoostAmount = boostRow.Boost; break; end end for prereqRow in GameInfo[prereqTableName]() do if prereqRow[itemColumn] == entry.Type then table.insert( entry.Prereqs, prereqRow[prereqColumn] ); end end -- If no prereqs were found, set item to special tree start value if table.count(entry.Prereqs) == 0 then table.insert(entry.Prereqs, PREREQ_ID_TREE_START); end -- Warn if DB has an out of bounds entry. if entry.UITreeRow < ROW_MIN or entry.UITreeRow > ROW_MAX then UI.DataError("UITreeRow for '"..entry.Type.."' has an out of bound UITreeRow="..tostring(entry.UITreeRow).." MIN="..tostring(ROW_MIN).." MAX="..tostring(ROW_MAX)); end -- Only build up a limited number of eras if debug information is forcing a subset. if m_debugFilterEraMaxIndex < 1 or ( m_debugFilterEraMaxIndex ~= -1 and m_kEras[entry.EraType] ~= nil ) then m_kItemDefaults[entry.Type] = entry; index = index + 1; end end end -- =========================================================================== -- Create a hash table of EraType to its chronological index. -- =========================================================================== function PopulateEraData() m_kEras = {}; for row:table in GameInfo.Eras() do if m_debugFilterEraMaxIndex < 1 or row.ChronologyIndex <= m_debugFilterEraMaxIndex then m_kEras[row.EraType] = { BGTexture = row.EraCivicBackgroundTexture, NumColumns = 0, Description = Locale.Lookup(row.Name), Index = row.ChronologyIndex, PriorColumns= -1 -- Will not be known until UI is laid out } end end end -- =========================================================================== -- -- =========================================================================== function PopulateFilterData() -- Filters. m_kFilters = {}; table.insert( m_kFilters, { Func=nil, Description="LOC_TECH_FILTER_NONE", Icon=nil } ); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_FOOD"], Description="LOC_TECH_FILTER_FOOD", Icon="[ICON_FOOD]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_SCIENCE"], Description="LOC_TECH_FILTER_SCIENCE", Icon="[ICON_SCIENCE]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_PRODUCTION"], Description="LOC_TECH_FILTER_PRODUCTION", Icon="[ICON_PRODUCTION]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_CULTURE"], Description="LOC_TECH_FILTER_CULTURE", Icon="[ICON_CULTURE]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_GOLD"], Description="LOC_TECH_FILTER_GOLD", Icon="[ICON_GOLD]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_UNITS"], Description="LOC_TECH_FILTER_UNITS", Icon="[ICON_UNITS]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_IMPROVEMENTS"], Description="LOC_TECH_FILTER_IMPROVEMENTS", Icon="[ICON_IMPROVEMENTS]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_WONDERS"], Description="LOC_TECH_FILTER_WONDERS", Icon="[ICON_WONDERS]" }); for i,filter in ipairs(m_kFilters) do local filterLabel = Locale.Lookup( filter.Description ); local filterIconText = filter.Icon; local controlTable = {}; Controls.FilterPulldown:BuildEntry( "FilterItemInstance", controlTable ); -- If a text icon exists, use it and bump the label in the button over. --[[ TODO: Uncomment if icons are added. if filterIconText ~= nil and filterIconText ~= "" then controlTable.IconText:SetText( Locale.Lookup(filterIconText) ); controlTable.DescriptionText:SetOffsetX(24); else controlTable.IconText:SetText( "" ); controlTable.DescriptionText:SetOffsetX(4); end ]] controlTable.DescriptionText:SetOffsetX(8); controlTable.DescriptionText:SetText( filterLabel ); -- Callback controlTable.Button:RegisterCallback( Mouse.eLClick, function() OnFilterClicked(filter); end ); end Controls.FilterPulldown:CalculateInternals(); end -- =========================================================================== -- Populate Full Text Search -- =========================================================================== function PopulateSearchData() local searchContext = "Civics"; if(Search.CreateContext(searchContext, "[COLOR_LIGHTBLUE]", "[ENDCOLOR]", "...")) then for row in GameInfo.Civics() do local description = row.Description and Locale.Lookup(row.Description) or ""; Search.AddData(searchContext, row.CivicType, Locale.Lookup(row.Name), description); end for row in GameInfo.Improvements() do if(row.PrereqCivic) then Search.AddData(searchContext, row.PrereqCivic, Locale.Lookup(GameInfo.Civics[row.PrereqCivic].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Units() do if(row.PrereqCivic) then Search.AddData(searchContext, row.PrereqCivic, Locale.Lookup(GameInfo.Civics[row.PrereqCivic].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Buildings() do if(row.PrereqCivic) then Search.AddData(searchContext, row.PrereqCivic, Locale.Lookup(GameInfo.Civics[row.PrereqCivic].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Districts() do if(row.PrereqCivic) then Search.AddData(searchContext, row.PrereqCivic, Locale.Lookup(GameInfo.Civics[row.PrereqCivic].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Resources() do if(row.PrereqCivic) then Search.AddData(searchContext, row.PrereqCivic, Locale.Lookup(GameInfo.Civics[row.PrereqCivic].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Policies() do if(row.PrereqCivic) then Search.AddData(searchContext, row.PrereqCivic, Locale.Lookup(GameInfo.Civics[row.PrereqCivic].Name), Locale.Lookup(row.Name)); end end Search.Optimize(searchContext); end end -- =========================================================================== -- Update the Filter text with the current label. -- =========================================================================== function RealizeFilterPulldown() local pullDownButton = Controls.FilterPulldown:GetButton(); if m_kCurrentData[DATA_FIELD_UIOPTIONS].filter == nil or m_kCurrentData[DATA_FIELD_UIOPTIONS].filter.Func== nil then pullDownButton:SetText( " "..Locale.Lookup("LOC_TREE_FILTER_W_DOTS")); else local description:string = m_kCurrentData[DATA_FIELD_UIOPTIONS].filter.Description; pullDownButton:SetText( " "..Locale.Lookup( description )); end end -- =========================================================================== -- filterLabel, Readable lable of the current filter. -- filterFunc, The funciton filter to apply to each node as it's built, -- nil will reset the filters to none. -- =========================================================================== function OnFilterClicked( filter ) m_kCurrentData[DATA_FIELD_UIOPTIONS].filter = filter; View( m_kCurrentData ) end -- =========================================================================== function OnOpen() if (Game.GetLocalPlayer() == -1) then return end UI.PlaySound("UI_Screen_Open"); View( m_kCurrentData ); ContextPtr:SetHide(false); -- From ModalScreen_PlayerYieldsHelper RefreshYields(); -- From Civ6_styles: FullScreenVignetteConsumer Controls.ScreenAnimIn:SetToBeginning(); Controls.ScreenAnimIn:Play(); LuaEvents.CivicsTree_OpenCivicsTree(); Controls.SearchEditBox:TakeFocus(); end -- =========================================================================== -- Show the Key panel based on the state -- =========================================================================== function RealizeKeyPanel() if UserConfiguration.GetShowCivicsTreeKey() then Controls.KeyPanel:SetHide( false ); UI.PlaySound("UI_TechTree_Filter_Open"); else if Controls.KeyPanel:IsHidden() then UI.PlaySound("UI_TechTree_Filter_Closed"); end Controls.KeyPanel:SetHide( true ); end if Controls.KeyPanel:IsHidden() then Controls.ToggleKeyButton:SetText(Locale.Lookup("LOC_TREE_SHOW_KEY")); Controls.ToggleKeyButton:SetSelected(false); else Controls.ToggleKeyButton:SetText(Locale.Lookup("LOC_TREE_HIDE_KEY")); Controls.ToggleKeyButton:SetSelected(true); end end -- =========================================================================== function OnClickCurrentPolicy(clickedPolicy:number) local percent:number = 0; local prereqCivic:string = GameInfo.Policies[clickedPolicy].PrereqCivic; percent = (m_uiNodes[prereqCivic].x - PADDING_TIMELINE_LEFT)/(m_maxColumns * COLUMN_WIDTH); Controls.NodeScroller:SetScrollValue(percent); end -- =========================================================================== -- Show the Key panel based on the state -- =========================================================================== function RealizeGovernmentPanel() m_kDiplomaticPolicyIM:DestroyInstances(); m_kEconomicPolicyIM:DestroyInstances(); m_kMilitaryPolicyIM:DestroyInstances(); m_kWildcardPolicyIM:DestroyInstances(); m_kDiplomaticPolicyIM = InstanceManager:new( "DiplomaticPolicyInstance", "DiplomaticPolicy", Controls.DiplomaticStack ); m_kEconomicPolicyIM = InstanceManager:new( "EconomicPolicyInstance", "EconomicPolicy", Controls.EconomicStack ); m_kMilitaryPolicyIM = InstanceManager:new( "MilitaryPolicyInstance", "MilitaryPolicy", Controls.MilitaryStack ); m_kWildcardPolicyIM = InstanceManager:new( "WildcardPolicyInstance", "WildcardPolicy", Controls.WildcardStack ); if UserConfiguration.GetShowCivicsTreeGovernment() then Controls.GovernmentPanel:SetHide( false ); UI.PlaySound("UI_TechTree_Filter_Open"); else if Controls.GovernmentPanel:IsHidden() then UI.PlaySound("UI_TechTree_Filter_Closed"); end Controls.GovernmentPanel:SetHide( true ); end if Controls.GovernmentPanel:IsHidden() then Controls.ToggleGovernmentButton:SetText(Locale.Lookup("LOC_TREE_SHOW_GOVERNMENT")); Controls.ToggleGovernmentButton:SetSelected(false); else Controls.ToggleGovernmentButton:SetText(Locale.Lookup("LOC_TREE_HIDE_GOVERNMENT")); Controls.ToggleGovernmentButton:SetSelected(true); end TruncateStringWithTooltip( Controls.GovernmentTitle, MAX_BEFORE_TRUNC_GOV_TITLE, Locale.ToUpper(m_kCurrentData[DATA_FIELD_GOVERNMENT]["NAMES"])); Controls.DiplomaticIconCount:SetText(tostring(m_kCurrentData[DATA_FIELD_GOVERNMENT]["DIPLOMATIC"])); Controls.EconomicIconCount:SetText(tostring(m_kCurrentData[DATA_FIELD_GOVERNMENT]["ECONOMIC"])); Controls.MilitaryIconCount:SetText(tostring(m_kCurrentData[DATA_FIELD_GOVERNMENT]["MILITARY"])); Controls.WildcardIconCount:SetText(tostring(m_kCurrentData[DATA_FIELD_GOVERNMENT]["WILDCARD"])); local int numDiploResults = #m_kCurrentData[DATA_FIELD_GOVERNMENT]["DIPLOMATICPOLICIES"]; for i,policy in ipairs(m_kCurrentData[DATA_FIELD_GOVERNMENT]["DIPLOMATICPOLICIES"]) do if(policy ~= -1) then local diploInst:table = m_kDiplomaticPolicyIM:GetInstance(); local policyType:string = GameInfo.Policies[policy].Name; if numDiploResults > 3 then diploInst.DiplomaticPolicy:SetSizeVal(111/numDiploResults, 44 * (3/numDiploResults)); end diploInst.DiplomaticPolicy:SetToolTipString(m_kPolicyCatalogData[policyType].Name .. ": " .. m_kPolicyCatalogData[policyType].Description); diploInst.DiplomaticPolicy:RegisterCallback( Mouse.eLClick, function() OnClickCurrentPolicy(policy) end ); end end local int numEcoResults = #m_kCurrentData[DATA_FIELD_GOVERNMENT]["ECONOMICPOLICIES"]; for i,policy in ipairs(m_kCurrentData[DATA_FIELD_GOVERNMENT]["ECONOMICPOLICIES"]) do if(policy ~= -1) then local ecoInst:table = m_kEconomicPolicyIM:GetInstance(); local policyType:string = GameInfo.Policies[policy].Name if numEcoResults > 3 then ecoInst.EconomicPolicy:SetSizeVal(111/numEcoResults, 44 * (3/numEcoResults)); end local description:string = m_kPolicyCatalogData[policyType].Name .. ": " .. m_kPolicyCatalogData[policyType].Description ecoInst.EconomicPolicy:SetToolTipString(description); ecoInst.EconomicPolicy:RegisterCallback( Mouse.eLClick, function() OnClickCurrentPolicy(policy) end ); end end local int numMilResults = #m_kCurrentData[DATA_FIELD_GOVERNMENT]["MILITARYPOLICIES"]; for i,policy in ipairs(m_kCurrentData[DATA_FIELD_GOVERNMENT]["MILITARYPOLICIES"]) do if(policy ~= -1) then local milInst:table = m_kMilitaryPolicyIM:GetInstance(); local policyType:string = GameInfo.Policies[policy].Name if numMilResults > 3 then milInst.MilitaryPolicy:SetSizeVal(111/numMilResults, 44 * (3/numMilResults)); end milInst.MilitaryPolicy:SetToolTipString(m_kPolicyCatalogData[policyType].Name .. ": " .. m_kPolicyCatalogData[policyType].Description); milInst.MilitaryPolicy:RegisterCallback( Mouse.eLClick, function() OnClickCurrentPolicy(policy) end ); end end local int numWildResults = #m_kCurrentData[DATA_FIELD_GOVERNMENT]["WILDCARDPOLICIES"]; for i,policy in ipairs(m_kCurrentData[DATA_FIELD_GOVERNMENT]["WILDCARDPOLICIES"]) do if(policy ~= -1) then local wildInst:table = m_kWildcardPolicyIM:GetInstance(); local policyType:string = GameInfo.Policies[policy].Name; local slotType:string = GameInfo.Policies[policy].GovernmentSlotType; if numWildResults > 3 then wildInst.WildcardPolicy:SetSizeVal(111/numWildResults, 44 * (3/numWildResults)); end if slotType == "SLOT_DIPLOMATIC" then wildInst.WildcardPolicy:SetTexture("Governments_DiplomacyCard_Small"); else if slotType == "SLOT_ECONOMIC" then wildInst.WildcardPolicy:SetTexture("Governments_EconomicCard_Small"); else if slotType == "SLOT_MILITARY" then wildInst.WildcardPolicy:SetTexture("Governments_MilitaryCard_Small"); end end end wildInst.WildcardPolicy:SetToolTipString(m_kPolicyCatalogData[policyType].Name .. ": " .. m_kPolicyCatalogData[policyType].Description); wildInst.WildcardPolicy:RegisterCallback( Mouse.eLClick, function() OnClickCurrentPolicy(policy) end ); end end end -- =========================================================================== -- Fill the catalog with the static (unchanging) policy data used by -- all players when viewing the screen. -- =========================================================================== function PopulateStaticData() -- Fill in the complete catalog of policies. m_kPolicyCatalogData = {}; for row in GameInfo.Policies() do local policyTypeRow :table = GameInfo.Types[row.PolicyType]; local policyName :string = Locale.Lookup(row.Name); local policyTypeHash :number = policyTypeRow.Hash; local slotType :string = row.GovernmentSlotType; local description :string = Locale.Lookup(row.Description); --local draftCost :number = kPlayerCulture:GetEnactPolicyCost(policyTypeHash); --Move to live data m_kPolicyCatalogData[row.Name] = { Description = description, Name = policyName, PolicyHash = policyTypeHash, SlotType = slotType, -- SLOT_MILITARY, SLOT_ECONOMIC, SLOT_DIPLOMATIC, SLOT_WILDCARD, (SLOT_GREAT_PERSON) UniqueID = row.Index -- the row this policy exists in, is guaranteed to be unique (as-is the house, but these are readable. ;) ) }; end -- Fill in governments m_kGovernments = {}; for row in GameInfo.Governments() do local government :table = GameInfo.Types[row.GovernmentType]; local slotMilitary :number = 0; local slotEconomic :number = 0; local slotDiplomatic :number = 0; local slotWildcard :number = 0; for entry in GameInfo.Government_SlotCounts() do if row.GovernmentType == entry.GovernmentType then local slotType = entry.GovernmentSlotType; for i = 1, entry.NumSlots, 1 do if slotType == "SLOT_MILITARY" then slotMilitary = slotMilitary + 1; elseif slotType == "SLOT_ECONOMIC" then slotEconomic = slotEconomic + 1; elseif slotType == "SLOT_DIPLOMATIC" then slotDiplomatic = slotDiplomatic + 1; elseif slotType == "SLOT_WILDCARD" or slotType=="SLOT_GREAT_PERSON" then slotWildcard = slotWildcard + 1; end end end end m_kGovernments[row.Name] = { BonusAccumlatedText = row.AccumulatedBonusDesc, BonusInherentText = row.InherentBonusDesc, BonusType = row.BonusType, Hash = government.Hash, Index = row.Index, Name = row.Name, NumSlotMilitary = slotMilitary, NumSlotEconomic = slotEconomic, NumSlotDiplomatic = slotDiplomatic, NumSlotWildcard = slotWildcard } end end -- =========================================================================== -- Show/Hide key panel -- =========================================================================== function OnClickToggleKey() if Controls.KeyPanel:IsHidden() then UserConfiguration.SetShowCivicsTreeKey(true); else UI.PlaySound("UI_TechTree_Filter_Closed"); UserConfiguration.SetShowCivicsTreeKey(false); end RealizeKeyPanel(); end Controls.ToggleKeyButton:RegisterCallback(Mouse.eLClick, OnClickToggleKey); function OnClickToggleGovernment() if Controls.GovernmentPanel:IsHidden() then UserConfiguration.SetShowCivicsTreeGovernment(true); else UI.PlaySound("UI_TechTree_Filter_Closed"); UserConfiguration.SetShowCivicsTreeGovernment(false); end RealizeGovernmentPanel(); end Controls.ToggleGovernmentButton:RegisterCallback(Mouse.eLClick, OnClickToggleGovernment); function OnClickToggleFilter() if Controls.FilterPulldown:IsOpen() then UI.PlaySound("UI_TechTree_Filter_Open"); else UI.PlaySound("UI_TechTree_Filter_Closed"); end end -- =========================================================================== -- Main close function all exit points should call. -- =========================================================================== function Close() UI.PlaySound("UI_Screen_Close"); ContextPtr:SetHide(true); LuaEvents.CivicsTree_CloseCivicsTree(); Controls.SearchResultsPanelContainer:SetHide(true); end -- =========================================================================== -- Close via click -- =========================================================================== function OnClose() Close(); end -- =========================================================================== -- Input -- UI Event Handler -- =========================================================================== function KeyDownHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = true; -- let it fall through end return false; end function KeyUpHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = false; -- let it fall through end if key == Keys.VK_ESCAPE then Close(); return true; end if key == Keys.VK_RETURN then -- Don't let enter propigate or it will hit action panel which will raise a screen (potentially this one again) tied to the action. return true; end return false; end function OnInputHandler( pInputStruct:table ) local uiMsg = pInputStruct:GetMessageType(); if uiMsg == KeyEvents.KeyDown then return KeyDownHandler( pInputStruct:GetKey() ); end if uiMsg == KeyEvents.KeyUp then return KeyUpHandler( pInputStruct:GetKey() ); end return false; end function OnSearchBarGainFocus() Controls.SearchEditBox:ClearString(); end function OnSearchBarLoseFocus() Controls.SearchEditBox:SetText(Locale.Lookup("LOC_TREE_SEARCH_W_DOTS")); end -- =========================================================================== -- UI Event Handler -- =========================================================================== function OnShutdown() -- Clean up events LuaEvents.CivicsPanel_RaiseCivicsTree.Remove( OnOpen ); LuaEvents.LaunchBar_RaiseCivicsTree.Remove( OnOpen ); LuaEvents.LaunchBar_CloseCivicsTree.Remove( OnClose ); Events.GovernmentChanged.Remove( OnGovernmentChanged ); Events.GovernmentPolicyChanged.Remove( OnGovernmentPolicyChanged ); Events.GovernmentPolicyObsoleted.Remove( OnGovernmentPolicyChanged ); Events.LocalPlayerTurnBegin.Remove( OnLocalPlayerTurnBegin ); Events.LocalPlayerTurnEnd.Remove( OnLocalPlayerTurnEnd ); Events.CivicChanged.Remove( OnCivicChanged ); Events.CivicCompleted.Remove( OnCivicComplete ); Events.SystemUpdateUI.Remove( OnUpdateUI ); Search.DestroyContext("Civics"); end -- =========================================================================== -- Centers scroll panel (if possible) on a specfic type. -- =========================================================================== function ScrollToNode( typeName:string ) local percent:number = 0; local x = m_uiNodes[typeName].x - ( m_width * 0.5); local size = (m_width / Controls.NodeScroller:GetRatio()) - m_width; percent = math.clamp( x / size, 0, 1); Controls.NodeScroller:SetScrollValue(percent); m_kSearchResultIM:DestroyInstances(); Controls.SearchResultsPanelContainer:SetHide(true); end -- =========================================================================== -- Input Hotkey Event -- =========================================================================== function OnInputActionTriggered( actionId ) if m_ToggleCivicsTreeId ~= nil and actionId == m_ToggleCivicsTreeId then UI.PlaySound("Play_UI_Click"); if(ContextPtr:IsHidden()) then LuaEvents.CivicsChooser_RaiseCivicsTree(); else OnClose(); end end end -- =========================================================================== -- UI Callback -- =========================================================================== function OnSearchCharCallback() local has_found = {}; local str = Controls.SearchEditBox:GetText(); if str ~= nil and str ~= Locale.Lookup("LOC_TREE_SEARCH_W_DOTS") then local results = Search.Search("Civics", str); if (results and #results > 0) then m_kSearchResultIM:DestroyInstances(); for i, v in ipairs(results) do -- v[1]chnologyType -- v[2] == Name of Technology w/ search term highlighted. -- v[3] == Snippet of Technology description w/ search term highlighted. if has_found[v[1]] == nil then local instance = m_kSearchResultIM:GetInstance(); local civicID:number; local i:number = 0; for row in GameInfo.Civics() do if row.CivicType == v[1] then civicID = i; end i = i + 1; end local iconName :string = DATA_ICON_PREFIX .. v[1]; instance.SearchIcon:SetIcon(iconName); -- Search results already localized. instance.Name:SetText(v[2]); instance.Button:RegisterCallback(Mouse.eLClick, function() ScrollToNode(v[1]); end ); instance.Button:SetToolTipString(ToolTipHelper.GetToolTip(v[1], Game.GetLocalPlayer())); has_found[v[1]] = true; end end Controls.SearchResultsStack:CalculateSize(); Controls.SearchResultsStack:ReprocessAnchoring(); Controls.SearchResultsPanel:CalculateSize(); Controls.SearchResultsPanelContainer:SetHide(false); else Controls.SearchResultsPanelContainer:SetHide(true); end end end -- =========================================================================== function OnCityInitialized(owner, ID) if (owner == m_ePlayer) then m_kCurrentData = GetLivePlayerData( m_ePlayer, -1 ); end end -- =========================================================================== function OnBuildingChanged( plotX:number, plotY:number, buildingIndex:number, playerID:number, iPercentComplete:number ) if playerID == m_ePlayer then m_kCurrentData = GetLivePlayerData( m_ePlayer, -1 ); -- Buildings can change culture/science yield which can effect "turns to complete" values end end -- =========================================================================== -- Load all static information as well as display information for the -- current local player. -- =========================================================================== function Initialize() PopulateStaticData(); PopulateEraData(); PopulateItemData("Civics","CivicType","CivicPrereqs","Civic","PrereqCivic"); PopulateFilterData(); PopulateSearchData(); AllocateUI(); -- May be observation mode. m_ePlayer = Game.GetLocalPlayer(); if (m_ePlayer == -1) then return; end Resize(); -- Now that view has been called once, size of tree is known. m_kCurrentData = GetLivePlayerData( m_ePlayer, -1 ); View( m_kCurrentData ); -- UI Events ContextPtr:SetInputHandler( OnInputHandler, true ); ContextPtr:SetShutdown( OnShutdown ); Controls.SearchEditBox:RegisterStringChangedCallback(OnSearchCharCallback); Controls.SearchEditBox:RegisterHasFocusCallback( OnSearchBarGainFocus); Controls.SearchEditBox:RegisterCommitCallback( OnSearchBarLoseFocus); local pullDownButton = Controls.FilterPulldown:GetButton(); pullDownButton:RegisterCallback(Mouse.eLClick, OnClickToggleFilter); -- LUA Events LuaEvents.CivicsChooser_RaiseCivicsTree.Add( OnOpen ); LuaEvents.LaunchBar_RaiseCivicsTree.Add( OnOpen ); LuaEvents.LaunchBar_CloseCivicsTree.Add( OnClose ); -- Game engine Event Events.CityInitialized.Add( OnCityInitialized ); Events.BuildingChanged.Add( OnBuildingChanged ); Events.CivicChanged.Add( OnCivicChanged ); Events.CivicCompleted.Add( OnCivicComplete ); Events.GovernmentChanged.Add( OnGovernmentChanged ); Events.GovernmentPolicyChanged.Add( OnGovernmentPolicyChanged ); Events.GovernmentPolicyObsoleted.Add( OnGovernmentPolicyChanged ); Events.InputActionTriggered.Add( OnInputActionTriggered ); Events.LocalPlayerTurnBegin.Add( OnLocalPlayerTurnBegin ); Events.LocalPlayerTurnEnd.Add( OnLocalPlayerTurnEnd ); Events.LocalPlayerChanged.Add(AllocateUI); Events.SystemUpdateUI.Add( OnUpdateUI ); -- CQUI add exceptions to the 50% notifications by putting civics into the CQUI_halfwayNotified table CQUI_halfwayNotified["LOC_CIVIC_CODE_OF_LAWS_NAME"] = true; end Initialize();
require 'keycodes' local BLIP_WAYPOINT = 8 local want_teleport = false local current_position = nil function OnScriptTick() current_position = entity.GET_ENTITY_COORDS(player.PLAYER_PED_ID(), 1) if want_teleport then local blip_id = ui.GET_FIRST_BLIP_INFO_ID(BLIP_WAYPOINT) if blip_id > 0 then local target = ui.GET_BLIP_INFO_ID_COORD(blip_id) --streaming.LOAD_SCENE(target.x, target.y, target.z) entity.SET_ENTITY_COORDS(player.PLAYER_PED_ID(), target.x, target.y, 1000, 1, 1, 1, 1) local new_z = gameplay.GET_GROUND_Z_FOR_3D_COORD(target.x, target.y, 1000) entity.SET_ENTITY_COORDS(player.PLAYER_PED_ID(), target.x, target.y, new_z, 1, 1, 1, 1) end end want_teleport = false end function OnDrawTick() if gui.TreeNode("Teleport") then gui.Text(current_position.x .. " " .. current_position.y .. " " .. current_position.z) if gui.Button("Teleport") then want_teleport = true end gui.TreePop() end end function Initialize() end
if not modules then modules = { } end modules ['util-sql-users'] = { version = 1.001, comment = "companion to lmx-*", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- This is experimental code and currently part of the base installation simply -- because it's easier to dirtribute this way. Eventually it will be documented -- and the related scripts will show up as well. local sql = utilities.sql local find, topattern = string.find, string.topattern local sumHEXA = md5.sumHEXA local toboolean = string.toboolean local lpegmatch = lpeg.match local sql = require("util-sql") -- utilities.sql local users = { } sql.users = users local trace_sql = false trackers.register("sql.users.trace", function(v) trace_sql = v end) local report = logs.reporter("sql","users") local split = lpeg.splitat(":") local valid = nil local hash = function(s) return "MD5:" .. sumHEXA(s) end if LUAVERSION >= 5.3 then local sha2 = require("util-sha") local HASH224 = sha2.HASH224 local HASH256 = sha2.HASH256 local HASH384 = sha2.HASH384 local HASH512 = sha2.HASH512 valid = { MD5 = hash, SHA224 = function(s) return "SHA224:" .. HASH224(s) end, SHA256 = function(s) return "SHA256:" .. HASH256(s) end, SHA384 = function(s) return "SHA384:" .. HASH384(s) end, SHA512 = function(s) return "SHA512:" .. HASH512(s) end, } else valid = { MD5 = hash, SHA224 = hash, SHA256 = hash, SHA384 = hash, SHA512 = hash, } end local function encryptpassword(str,how) if not str or str == "" then return "" end local prefix, rest = lpegmatch(split,str) if prefix and rest and valid[prefix] then return str end return (how and valid[how] or valid.MD5)(str) end local function cleanuppassword(str) local prefix, rest = lpegmatch(split,str) if prefix and rest and valid[prefix] then return rest end return str end local function samepasswords(one,two) if not one or not two then return false end return encryptpassword(one) == encryptpassword(two) end local function validaddress(address,addresses) if address and addresses and address ~= "" and addresses ~= "" then if find(address,topattern(addresses,true,true)) then return true, "valid remote address" end return false, "invalid remote address" else return true, "no remote address check" end end users.encryptpassword = encryptpassword users.cleanuppassword = cleanuppassword users.samepasswords = samepasswords users.validaddress = validaddress -- print(users.encryptpassword("test")) -- MD5:098F6BCD4621D373CADE4E832627B4F6 local function checkeddb(presets,datatable) return sql.usedatabase(presets,datatable or presets.datatable or "users") end users.usedb = checkeddb local groupnames = { } local groupnumbers = { } local function registergroup(name) local n = #groupnames + 1 groupnames [n] = name groupnames [tostring(n)] = name groupnames [name] = name groupnumbers[n] = n groupnumbers[tostring(n)] = n groupnumbers[name] = n return n end registergroup("superuser") registergroup("administrator") registergroup("user") registergroup("guest") users.groupnames = groupnames users.groupnumbers = groupnumbers -- password 'test': -- -- INSERT insert into users (`name`,`password`,`group`,`enabled`) values ('...','MD5:098F6BCD4621D373CADE4E832627B4F6',1,1) ; -- -- MD5:098F6BCD4621D373CADE4E832627B4F6 -- SHA224:90A3ED9E32B2AAF4C61C410EB925426119E1A9DC53D4286ADE99A809 -- SHA256:9F86D081884C7D659A2FEAA0C55AD015A3BF4F1B2B0B822CD15D6C15B0F00A08 -- SHA384:768412320F7B0AA5812FCE428DC4706B3CAE50E02A64CAA16A782249BFE8EFC4B7EF1CCB126255D196047DFEDF17A0A9 -- SHA512:EE26B0DD4AF7E749AA1A8EE3C10AE9923F618980772E473F8819A5D4940E0DB27AC185F8A0E1D5F84F88BC887FD67B143732C304CC5FA9AD8E6F57F50028A8FF -- old values (a name can have utf and a password a long hash): -- -- name 80, fullname 80, password 50 local template = [[ CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, `fullname` varchar(100) NOT NULL, `password` varchar(200) DEFAULT NULL, `group` int(11) NOT NULL, `enabled` int(11) DEFAULT '1', `email` varchar(80) DEFAULT NULL, `address` varchar(256) DEFAULT NULL, `theme` varchar(50) DEFAULT NULL, `data` longtext, PRIMARY KEY (`id`), UNIQUE KEY `name_unique` (`name`) ) DEFAULT CHARSET = utf8 ; ]] local sqlite_template = [[ CREATE TABLE `users` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `name` TEXT NOT NULL, `fullname` TEXT NOT NULL, `password` TEXT DEFAULT NULL, `group` INTEGER NOT NULL, `enabled` INTEGER DEFAULT '1', `email` TEXT DEFAULT NULL, `address` TEXT DEFAULT NULL, `theme` TEXT DEFAULT NULL, `data` TEXT DEFAULT NULL ) ; ]] local converter, fields = sql.makeconverter { { name = "id", type = "number" }, { name = "name", type = "string" }, { name = "fullname", type = "string" }, { name = "password", type = "string" }, { name = "group", type = groupnames }, { name = "enabled", type = "boolean" }, { name = "email", type = "string" }, { name = "address", type = "string" }, { name = "theme", type = "string" }, { name = "data", type = "deserialize" }, } function users.createdb(presets,datatable) local db = checkeddb(presets,datatable) db.execute { template = db.usedmethod == "sqlite" and sqlite_template or template, variables = { basename = db.basename, }, } report("datatable %a created in %a",db.name,db.base) return db end local template =[[ SELECT %fields% FROM %basename% WHERE `name` = '%[name]%' AND `password` = '%[password]%' ; ]] local template =[[ SELECT %fields% FROM %basename% WHERE `name` = '%[name]%' ; ]] function users.valid(db,username,password,address) local data = db.execute { template = template, converter = converter, variables = { basename = db.basename, fields = fields, name = username, }, } local data = data and data[1] if not data then return false, "unknown user" elseif not data.enabled then return false, "disabled user" elseif data.password ~= encryptpassword(password) then return false, "wrong password" elseif not validaddress(address,data.address) then return false, "invalid address" else data.password = nil return data, "okay" end end local template =[[ INSERT INTO %basename% ( `name`, `fullname`, `password`, `group`, `enabled`, `email`, `address`, `theme`, `data` ) VALUES ( '%[name]%', '%[fullname]%', '%[password]%', '%[group]%', '%[enabled]%', '%[email]%', '%[address]%', '%[theme]%', '%[data]%' ) ; ]] function users.add(db,specification) local name = specification.username or specification.name if not name or name == "" then return end local data = specification.data db.execute { template = template, variables = { basename = db.basename, name = name, fullname = name or fullname, password = encryptpassword(specification.password or ""), group = groupnumbers[specification.group] or groupnumbers.guest, enabled = toboolean(specification.enabled) and "1" or "0", email = specification.email, address = specification.address, theme = specification.theme, data = type(data) == "table" and db.serialize(data,"return") or "", }, } end local template =[[ SELECT %fields% FROM %basename% WHERE `name` = '%[name]%' ; ]] function users.getbyname(db,name) local data = db.execute { template = template, converter = converter, variables = { basename = db.basename, fields = fields, name = name, }, } return data and data[1] or nil end local template =[[ SELECT %fields% FROM %basename% WHERE `id` = '%id%' ; ]] local function getbyid(db,id) local data = db.execute { template = template, converter = converter, variables = { basename = db.basename, fields = fields, id = id, }, } return data and data[1] or nil end users.getbyid = getbyid local template =[[ UPDATE %basename% SET `fullname` = '%[fullname]%', `password` = '%[password]%', `group` = '%[group]%', `enabled` = '%[enabled]%', `email` = '%[email]%', `address` = '%[address]%', `theme` = '%[theme]%', `data` = '%[data]%' WHERE `id` = '%id%' ; ]] function users.save(db,id,specification) id = tonumber(id) if not id then return end local user = getbyid(db,id) if tonumber(user.id) ~= id then return end local fullname = specification.fullname == nil and user.fulname or specification.fullname local password = specification.password == nil and user.password or specification.password local group = specification.group == nil and user.group or specification.group local enabled = specification.enabled == nil and user.enabled or specification.enabled local email = specification.email == nil and user.email or specification.email local address = specification.address == nil and user.address or specification.address local theme = specification.theme == nil and user.theme or specification.theme local data = specification.data == nil and user.data or specification.data db.execute { template = template, variables = { basename = db.basename, id = id, fullname = fullname, password = encryptpassword(password), group = groupnumbers[group], enabled = toboolean(enabled) and "1" or "0", email = email, address = address, theme = theme, data = type(data) == "table" and db.serialize(data,"return") or "", }, } return getbyid(db,id) end local template =[[ DELETE FROM %basename% WHERE `id` = '%id%' ; ]] function users.remove(db,id) db.execute { template = template, variables = { basename = db.basename, id = id, }, } end local template =[[ SELECT %fields% FROM %basename% ORDER BY `name` ; ]] function users.collect(db) -- maybe also an id/name only variant local records, keys = db.execute { template = template, converter = converter, variables = { basename = db.basename, fields = fields, }, } return records, keys end
-- Generator general menu --- @author Alexandr Mikhailenko a.k.a. Alex M.A.K. <alex-m.a.k@yandex.kz> local menugen = require("core.modules.menugen") mythememenu = {} function removeOldTheme() local cfg_path = _Awesome.config local cmd = "ls -1 " .. cfg_path .. "/themes/.usedTheme/" local f = io.popen(cmd) for l in f:lines() do _Awesome.awful.util.spawn("rm " .. cfg_path .. "/themes/.usedTheme/"..l) end f:close() end function theme_load(theme) _Awesome._settings.themes = theme _Awesome.String2File(_Awesome.config .. '/config.json', _Awesome._settings) _Awesome.awful.util.spawn("xrdb -load " .. _Awesome.config .. "/themes/"..theme..'/Xdefaults') awesome.restart() end function theme_menu() -- List your theme files and feed the menu table local cmd = "ls -1 " .. _Awesome.config .. "/themes/" local f = io.popen(cmd) for l in f:lines() do if l ~= 'icons' and l ~= 'init.lua' and not string.find(l, 'Xdefaults') then table.insert( mythememenu, { l, function () theme_load(l) end } ) end end f:close() end -- Generate your table at startup or restart theme_menu() -- {{{ Auto-genereate menu from Awesome configs and plugins local function createEditConfigurationsFileFromAwesome(name) local i, t, popen = 0, {}, io.popen for filename in popen ('ls '..name):lines() do i = i + 1 t[i] = { [filename] = name.."/"..filename } end return t end local ConfigFiles,ThemesFiles, UserWidgetsFiles, GlobalWidgetsFiles = {}, {}, {}, {} local function genMenu(array, path, prefix, exe) for k, v in pairs(createEditConfigurationsFileFromAwesome(path)) do for kk, vv in pairs(v) do if prefix ~= nil and string.find(vv, prefix) then if string.find(vv, ".png") then command = "sxiv " .. vv else command = _Awesome.applications.editor .. " " .. vv end table.insert( array, { kk, command, _Awesome.beautiful.file } ) elseif prefix == nil and prefix == '' and exe ~= nil and exe ~= '' then local command = _Awesome.applications.editor .. " " .. vv .. '/init.lua' table.insert( array, { kk, command, _Awesome.beautiful.file } ) else if string.find(vv, ".png") then command = "sxiv " .. vv else command = _Awesome.applications.editor .. " " .. vv end table.insert( array, { kk, command, _Awesome.beautiful.file } ) end end end return array end function generateMenu() -- Autogen Menu mymainmenu = _Awesome.awful.menu.new( { theme = { height = 22, width = 240, border_width = 3, border_color = '#7788af' }, { "Awesome", { { "Manual from Awesome", 'urxvt', --_Awesome.userConfig.terminal.command .. " -e man awesome", _Awesome.beautiful.awesomeManual }, { "", }, { "Edit Base Config", genMenu( ConfigFiles, _Awesome.config ..'/core/root' ), _Awesome.beautiful.sourceEdit }, { "Edit Theme Config", genMenu( ThemesFiles, _Awesome.config ..'/themes/' .._Awesome.themename ..'/', '.lua' ), _Awesome.beautiful.sourceEdit }, { "Edit User Widgets Config", genMenu( UserWidgetsFiles, _Awesome.config ..'/core/widgets/', nil, true ), _Awesome.beautiful.sourceEdit }, { "Edit Global Widgets Config", genMenu( GlobalWidgetsFiles, _Awesome.config ..'/core/modules/lain/widgets/' ), _Awesome.beautiful.sourceEdit }, { "", }, { "Update MultiColor", 'cd ' .. _Awesome.config .. '; git pull;', _Awesome.beautiful.updateAwesome }, { "", }, { "Awesome Themes", mythememenu, _Awesome.beautiful.themesAwesome }, { "Awesome Restart", awesome.restart, _Awesome.beautiful.restart } }, _Awesome.beautiful.awesomewm }, { "" }, { "Browser", _Awesome.applications.browser--_Awesome.applications.browser .. ' https://duckduckgo.com/', _Awesome.beautiful.browser, }, { "Terminal", _Awesome.applications.terminal, --_Awesome.userConfig.terminal.command, _Awesome.beautiful.console, }, { "IM Client", _Awesome.applications.im, --_Awesome.userConfig.imclient.command, _Awesome.beautiful.im }, {}, { "Music Online", { { "Yandex.Radio", { { "Main", _Awesome.applications.browser .. ' "https://radio.yandex.kz"', nil, }, { "Metal", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/metal"', nil, }, { "Alternative", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/alternative"', nil, }, { "Blues", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/blues"', nil, }, { "SKA", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/ska"', nil, }, { "Estrada", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/estrada"', nil, }, { "Shanson", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/shanson"', nil, }, { "Country", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/country"', nil, }, { "Children", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/children"', nil, }, { "Electronics", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/electronics"', nil, }, { "Dubstep", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/dubstep"', nil, }, { "Industrial", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/industrial"', nil, }, { "Experimental", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/experimental"', nil, }, { "Dance", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/dance"', nil, }, { "House", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/house"', nil, }, { "Techno", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/techno"', nil, }, { "Trance", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/trance"', nil, }, { "DNB", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/dnb"', nil, }, { "Relax", _Awesome.applications.browser .. ' "https://radio.yandex.kz/genre/relax"', nil, }, }, _Awesome.beautiful.radio_yandex }, { "Yandex.Music", _Awesome.applications.browser .. ' "https://music.yandex.kz"', _Awesome.beautiful.music_yandex, }, { "101", _Awesome.applications.browser .. ' "https://101.ru"', _Awesome.beautiful.ru101, }, { "DI", _Awesome.applications.browser .. ' "https://di.fm"', _Awesome.beautiful.di, }, }, _Awesome.beautiful.music }, { "", }, { "Applications", menugen.build_menu(), _Awesome.beautiful.applications }, { "Google Applications", { { "Create spreadsheet", _Awesome.applications.browser .. ' "https://docs.google.com/spreadsheet/ccc?new"', _Awesome.beautiful.play_sheets }, { "Create document", _Awesome.applications.browser .. ' "https://docs.google.com/document/create"', _Awesome.beautiful.play_docs }, { "Create presentation", _Awesome.applications.browser .. ' "https://docs.google.com/presentation/create"', _Awesome.beautiful.play_slides }, { "Create draw", _Awesome.applications.browser .. ' "https://docs.google.com/drawings/create?usp=drive_web"', _Awesome.beautiful.play_drawings }, { "Create form", _Awesome.applications.browser .. ' "https://docs.google.com/forms/create"', _Awesome.beautiful.play_forms }, { "", }, { "Google Sheets", _Awesome.applications.browser .. ' "https://docs.google.com/spreadsheets/u/0/"', _Awesome.beautiful.play_sheets }, { "Google Docs", _Awesome.applications.browser .. ' "https://docs.google.com/document/u/0/"', _Awesome.beautiful.play_docs }, { "Google Disk", _Awesome.applications.browser .. ' "https://drive.google.com/drive/u/0/"', _Awesome.beautiful.play_drive }, { "Google Hangouts", _Awesome.applications.browser .. ' "https://hangouts.google.com/"', _Awesome.beautiful.play_hangouts }, { "Google Calendar", _Awesome.applications.browser .. ' "https://calendar.google.com/calendar/"', _Awesome.beautiful.play_calendar }, { "Google Contacts", _Awesome.applications.browser .. ' "https://contacts.google.com/u/0/preview/all"', _Awesome.beautiful.play_contacts }, { "Google Books", _Awesome.applications.browser .. ' "https://play.google.com/books?source=gbs_lp_bookshelf_list"', _Awesome.beautiful.play_books }, { "Google News", _Awesome.applications.browser .. ' "https://news.google.com/nwshp?hl=ru"', _Awesome.beautiful.play_news }, { "Google Inbox", _Awesome.applications.browser .. ' "https://inbox.google.com/u/0/"', _Awesome.beautiful.play_inbox } }, _Awesome.beautiful.google_apps }, { "Develop", { { "AwesomeWM ApiDoc", _Awesome.applications.browser .. "http://new.awesomewm.org/apidoc/" }, { "Lua Functions", { { "5.1", _Awesome.applications.browser .. ' "http://www.lua.org/manual/5.1/index.html#index"' }, { "5.2", _Awesome.applications.browser .. ' "http://www.lua.org/manual/5.2/index.html#index"' }, { "5.3", _Awesome.applications.browser .. ' "http://www.lua.org/manual/5.3/index.html#index"' } }, _Awesome.beautiful.lualogo }, { "A curated list of quality Lua packages and resources", _Awesome.applications.browser .. ' "https://github.com/LewisJEllis/awesome-lua"', _Awesome.beautiful.lualogo }, { "Cloud9", _Awesome.applications.browser .. ' "https://ide.c9.io/"', _Awesome.beautiful.cloud9 } }, _Awesome.beautiful.develop }, { "", }, { "Backup configuration", awesome.restart, }, { "Restart", 'systemctl restart -i', _Awesome.beautiful.restart }, { "Poweroff", 'systemctl poweroff -i', _Awesome.beautiful.poweroff }, } ) mylauncher = _Awesome.awful.widget.launcher( { icon = _Awesome.beautiful.awesome_icon, menu = mymainmenu } ) return mymainmenu, mylauncher end -- }}}
-- Jambo animations -- Performance bindings local newImage = love.graphics.newImage -- Imports local Media = require("scripts.media") -- Sprite geometry local sprite_width = 26 local sprite_height = 22 -- Resources path file local path = "res/gfx/SpriteSheets/player/" -- Animation spritesheets local idle = "john_idle_ng.png" local run = "john_run_ng.png" local crouch = "john_crouch_ng.png" local jump = "john_jump_ng.png" local looking_up = "john_stand_looking_up.png" local running_updiag = "john_run_up_diag.png" local looking_downdiag = "john_stand_looking_down_diag.png" local jump_aimdiagdown = "john_jump_ng_aimdiagdown.png" local jump_aimdiagup = "john_jump_ng_aimdiagup.png" local jump_aimdown = "john_jump_ng_aimdown.png" local jump_aimup = "john_jump_ng_aimup.png" -- Load images local jambo_idle = newImage(path .. idle) local jambo_run = newImage(path .. run) local jambo_crouch = newImage(path .. crouch) local jambo_jump = newImage(path .. jump) local jambo_lookup = newImage(path .. looking_up) local jambo_runupdiag = newImage(path .. running_updiag) local jambo_lookdowndiag = newImage(path .. looking_downdiag) local jambo_jumpaimdiagdown = newImage(path .. jump_aimdiagdown) local jambo_jumpaimdiagup = newImage(path .. jump_aimdiagup) local jambo_jumpaimdown = newImage(path .. jump_aimdown) local jambo_jumpaimup = newImage(path .. jump_aimup) -- Animations return { idle_animation = Media.newAnimation(jambo_idle, sprite_width, sprite_height, 1, false), run_animation = Media.newAnimation(jambo_run, sprite_width, sprite_height, 1, false), crouch_animation = Media.newAnimation(jambo_crouch, sprite_width, sprite_height, 0.1, true), jump_animation = Media.newAnimation(jambo_jump, sprite_width, sprite_height, 0.8, true), lookup_animation = Media.newAnimation(jambo_lookup, sprite_width, sprite_height, 1, false), runupdiag_animation = Media.newAnimation(jambo_runupdiag, sprite_width, sprite_height, 1, false), lookdowndiag_animation = Media.newAnimation(jambo_lookdowndiag, sprite_width, sprite_height, 1, false), jumpaimdiagdown_animation = Media.newAnimation(jambo_jumpaimdiagdown, sprite_width, 26, 1, true), -- Non-standard height jumpaimdiagup_animation = Media.newAnimation(jambo_jumpaimdiagup, sprite_width, sprite_height, 1, true), jumpaimdown_animation = Media.newAnimation(jambo_jumpaimdown, sprite_width, 26, 0.5, true), -- Non-standard height jumpaimup_animation = Media.newAnimation(jambo_jumpaimup, sprite_width, 26, 1, true), -- Non-standard height }
function UITextField() local self = UIElement() self.options.multiline = false self.options.template = [[ <input <% if (typeof hideinput != 'undefined' && hideinput == true) { %>type="password"<% } %> id="<%- id %>" class="ui-framework-parent textfield" spellcheck="false" value="<%- value %>" placeholder="<%- placeholder %>" style="<% if (typeof css != 'undefined') { %><%- css %><% } %>"> ]] function self.setHideInput(value) self.options.hideinput = value end function self.setPlaceholder(placeholder) self.options.placeholder = placeholder end function self.getPlaceholder() return self.options.placeholder; end return self end
--[[ File : /lua/AI/AIBuilders/DilliFactoryBuilders.lua Author : Softles Summary : Factory Builders for Dilli. If a factory is making units, that behaviour is controlled here. ]] local UCBC = '/lua/editor/UnitCountBuildConditions.lua' local TBC = '/lua/editor/ThreatBuildConditions.lua' local EBC = '/lua/editor/EconomyBuildConditions.lua' local SIBC = '/lua/editor/SorianInstantBuildConditions.lua' local SBC = '/lua/editor/SorianBuildConditions.lua' BuilderGroup { BuilderGroupName = 'DilliT1GenericFactory', BuildersType = 'FactoryBuilder', --[[ Initial T1 Engineer Builders ]] Builder { BuilderName = 'DilliFactoryInitialT1Engineer', PlatoonTemplate = 'T1BuildEngineer', Priority = 2000, BuilderConditions = { { UCBC, 'HaveLessThanUnitsWithCategory', { 2, categories.ENGINEER - categories.COMMAND } }, }, BuilderType = 'All', }, Builder { BuilderName = 'DilliFactorySecondaryT1Engineer', PlatoonTemplate = 'T1BuildEngineer', Priority = 1800, BuilderConditions = { { UCBC, 'HaveLessThanUnitsWithCategory', { 5, categories.ENGINEER - categories.COMMAND } }, }, BuilderType = 'All', }, Builder { BuilderName = 'DilliFactoryT1LandEngineer', PlatoonTemplate = 'T1BuildEngineer', Priority = 1500, BuilderConditions = { { UCBC, 'HaveUnitRatio', { 0.05, categories.ENGINEER, '<=', categories.LAND * categories.MOBILE - categories.ENGINEER } }, }, BuilderType = 'All', }, Builder { BuilderName = 'DilliFactoryT1LandEngineerAlt', PlatoonTemplate = 'T1BuildEngineer', Priority = 1500, BuilderConditions = { { UCBC, 'HaveUnitRatio', { 2.0, categories.ENGINEER, '<', categories.FACTORY * categories.LAND } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 1, categories.LAND * categories.ENGINEER } }, }, BuilderType = 'All', } } BuilderGroup { BuilderGroupName = 'DilliT2GenericFactory', BuildersType = 'FactoryBuilder', --[[ Initial T2 Engineer Builders ]] Builder { BuilderName = 'DilliFactoryInitialT2Engineer', PlatoonTemplate = 'T2BuildEngineer', Priority = 3000, BuilderConditions = { { UCBC, 'HaveLessThanUnitsWithCategory', { 1, categories.ENGINEER * categories.TECH2 - categories.COMMAND } }, }, BuilderType = 'All', }, } --[[ Land Factory Builders ]] BuilderGroup { BuilderGroupName = 'DilliT1LandFactory', BuildersType = 'FactoryBuilder', --[[ Initial Land Builders ]] Builder { BuilderName = 'DilliFactoryInitialT1Tanks', PlatoonTemplate = 'T1LandDFTank', Priority = 1900, BuilderConditions = { { UCBC, 'HaveLessThanUnitsWithCategory', { 3, categories.LAND * categories.DIRECTFIRE - categories.SCOUT } }, }, BuilderType = 'Land', }, Builder { BuilderName = 'DilliFactoryInitialT1Scouts', PlatoonTemplate = 'T1LandScout', Priority = 1950, BuilderConditions = { { UCBC, 'HaveLessThanUnitsWithCategory', { 3, categories.LAND * categories.SCOUT } }, { UCBC, 'HaveUnitRatio', { 0.5, categories.LAND * categories.SCOUT, '<', categories.LAND * categories.DIRECTFIRE * categories.MOBILE - categories.SCOUT } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 1, categories.LAND * categories.SCOUT } }, { UCBC, 'HaveGreaterThanUnitsWithCategory', { 1, categories.LAND * categories.DIRECTFIRE - categories.SCOUT } }, }, BuilderType = 'Land', }, --[[ High Priority Builders ]] Builder { BuilderName = 'DilliFactoryHiPriT1AA', PlatoonTemplate = 'T1LandAA', Priority = 2100, BuilderConditions = { { TBC, 'EnemyThreatGreaterThanValueAtBase', { 'LocationType', 0, 'Air', 1 } }, { UCBC, 'HaveLessThanUnitsWithCategory', { 4, categories.LAND * categories.ANTIAIR * categories.MOBILE } }, }, BuilderType = 'Land', }, --[[ Regular Spam Builders ]] Builder { BuilderName = 'DilliFactorySpamT1Tank', PlatoonTemplate = 'T1LandDFTank', Priority = 1000, BuilderConditions = { { SIBC, 'GreaterThanEconIncome', { 6, 70 } }, { SIBC, 'HaveGreaterThanUnitsWithCategory', { 0, 'FACTORY TECH2' } }, }, BuilderType = 'Land' }, Builder { BuilderName = 'DilliFactorySpamT1TankAlt', PlatoonTemplate = 'T1LandDFTank', Priority = 1000, BuilderConditions = { { SIBC, 'HaveLessThanUnitsWithCategory', { 1, 'FACTORY TECH2' } }, }, BuilderType = 'Land' }, Builder { BuilderName = 'DilliFactorySpamT1AA', PlatoonTemplate = 'T1LandAA', Priority = 1500, BuilderConditions = { { TBC, 'EnemyThreatGreaterThanValueAtBase', { 'LocationType', 0, 'Air', 1 } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 2, categories.LAND * categories.ANTIAIR * categories.MOBILE } }, { UCBC, 'HaveUnitRatio', { 0.15, categories.LAND * categories.ANTIAIR * categories.MOBILE, '<', categories.LAND * categories.DIRECTFIRE * categories.MOBILE - categories.SCOUT } }, }, BuilderType = 'Land' }, Builder { BuilderName = 'DilliFactorySpamT1Arty', PlatoonTemplate = 'T1LandArtillery', Priority = 1500, BuilderConditions = { { UCBC, 'HaveUnitRatio', { 0.22, categories.LAND * categories.INDIRECTFIRE * categories.MOBILE, '<', categories.LAND * categories.DIRECTFIRE * categories.MOBILE - categories.SCOUT } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 2, categories.LAND * categories.INDIRECTFIRE * categories.MOBILE } }, { UCBC, 'HaveGreaterThanUnitsWithCategory', { 8, categories.LAND * categories.MOBILE * categories.DIRECTFIRE } }, }, BuilderType = 'Land', }, Builder { BuilderName = 'DilliFactorySpamT1Scout', PlatoonTemplate = 'T1LandScout', Priority = 1500, BuilderConditions = { { UCBC, 'HaveUnitRatio', { 0.075, categories.LAND * categories.SCOUT, '<', categories.LAND * categories.DIRECTFIRE * categories.MOBILE - categories.SCOUT } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 1, categories.LAND * categories.SCOUT } }, }, BuilderType = 'Land', }, Builder { BuilderName = 'DilliFactorySpamT1Scout', PlatoonTemplate = 'T1LandScout', Priority = 1500, BuilderConditions = { { UCBC, 'HaveUnitRatio', { 0.25, categories.LAND * categories.SCOUT, '<', categories.LAND * categories.DIRECTFIRE * categories.MOBILE - categories.SCOUT } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 1, categories.LAND * categories.SCOUT } }, { UCBC, 'HaveLessThanUnitsWithCategory', { 30, categories.LAND * categories.MOBILE * categories.DIRECTFIRE } }, }, BuilderType = 'Land', }, } BuilderGroup { BuilderGroupName = 'DilliT2LandFactory', BuildersType = 'FactoryBuilder', --[[ High Priority Builders ]] Builder { BuilderName = 'DilliFactoryHiPriT1AA', PlatoonTemplate = 'T2LandAA', Priority = 2200, BuilderConditions = { { TBC, 'EnemyThreatGreaterThanValueAtBase', { 'LocationType', 0, 'Air', 1 } }, { UCBC, 'HaveLessThanUnitsWithCategory', { 4, categories.LAND * categories.ANTIAIR * categories.MOBILE } }, }, BuilderType = 'Land' }, --[[ Regular Spam Builders ]] Builder { BuilderName = 'DilliFactorySpamT2Tank', PlatoonTemplate = 'T2LandDFTank', Priority = 1100, BuilderConditions = { }, BuilderType = 'Land' }, Builder { BuilderName = 'DilliFactorySpamT2AA', PlatoonTemplate = 'T2LandAA', Priority = 1600, BuilderConditions = { { TBC, 'EnemyThreatGreaterThanValueAtBase', { 'LocationType', 0, 'Air', 1 } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 2, categories.LAND * categories.ANTIAIR * categories.MOBILE } }, { UCBC, 'HaveUnitRatio', { 0.1, categories.LAND * categories.ANTIAIR * categories.MOBILE, '<', categories.LAND * categories.SCOUT } }, }, BuilderType = 'Land' }, Builder { BuilderName = 'DilliFactorySpamT2Arty', PlatoonTemplate = 'T2LandArtillery', Priority = 1600, BuilderConditions = { { UCBC, 'HaveUnitRatio', { 0.05, categories.LAND * categories.INDIRECTFIRE * categories.MOBILE * categories.TECH2, '<', categories.LAND * categories.DIRECTFIRE * categories.MOBILE * categories.TECH2 } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 2, categories.LAND * categories.INDIRECTFIRE * categories.MOBILE } }, }, BuilderType = 'Land', }, } --[[ Land Factory Upgrades ]] BuilderGroup { BuilderGroupName = 'DilliUpgradeLandFactory', BuildersType = 'PlatoonFormBuilder', Builder { BuilderName = 'DilliFactoryInitialUpgradeLand', PlatoonTemplate = 'T1LandFactoryUpgrade', InstanceCount = 1, Priority = 2100, BuilderConditions = { { SIBC, 'GreaterThanEconIncome', { 6, 50 } }, { UCBC, 'HaveLessThanUnitsInCategoryBeingBuilt', { 1, 'FACTORY TECH2' } }, { SIBC, 'HaveGreaterThanUnitsWithCategory', { 2, 'MASSEXTRACTION TECH2' } }, { SIBC, 'HaveGreaterThanUnitsWithCategory', { 5, 'FACTORY TECH1' } }, }, BuilderType = 'Any', }, Builder { BuilderName = 'DilliFactoryMainUpgradeLand', PlatoonTemplate = 'T1LandFactoryUpgrade', InstanceCount = 1, Priority = 2000, BuilderConditions = { { SIBC, 'GreaterThanEconIncome', { 6, 50 } }, { SIBC, 'HaveGreaterThanUnitsWithCategory', { 2, 'MASSEXTRACTION TECH2' } }, { SIBC, 'HaveGreaterThanUnitsWithCategory', { 0, 'FACTORY TECH2' } }, }, BuilderType = 'Any', }, } --[[ Air Factory Builders ]] BuilderGroup { BuilderGroupName = 'DilliT1AirFactory', BuildersType = 'FactoryBuilder', --[[ Initial T1 Air Builders ]] Builder { BuilderName = 'DilliFactoryInitialT1AirScouts', PlatoonTemplate = 'T1AirScout', Priority = 1950, BuilderConditions = { { UCBC, 'HaveLessThanUnitsWithCategory', { 3, categories.AIR * categories.SCOUT } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 1, categories.AIR * categories.SCOUT } }, }, BuilderType = 'Air', }, Builder { BuilderName = 'DilliFactoryT1Bombers', PlatoonTemplate = 'T1AirBomber', Priority = 100, BuilderConditions = { { EBC, 'GreaterThanEconStorageRatio', { 0.0, 0.7}}, }, BuilderType = 'Air', }, --[[ Regular Spam Builders ]] Builder { BuilderName = 'DilliFactoryT1Inties', PlatoonTemplate = 'T1AirFighter', Priority = 200, BuilderConditions = { { SBC, 'HaveRatioUnitsWithCategoryAndAlliance', { false, 1.5, categories.AIR * categories.ANTIAIR, categories.AIR * categories.MOBILE, 'Enemy'}}, { EBC, 'GreaterThanEconStorageRatio', { 0.0, 0.7}}, }, BuilderType = 'Air', }, Builder { BuilderName = 'DilliFactoryT1AirScouts', PlatoonTemplate = 'T1AirScout', Priority = 250, BuilderConditions = { { UCBC, 'HaveGreaterThanUnitsWithCategory', { 8, categories.AIR } }, { UCBC, 'HaveLessThanUnitsWithCategory', { 6, categories.AIR * categories.SCOUT } }, { UCBC, 'LocationFactoriesBuildingLess', { 'LocationType', 1, categories.AIR * categories.SCOUT } }, }, BuilderType = 'Air', }, }
require "Items/SuburbsDistributions" require "Items/ProceduralDistributions" -- ITEMS --- CocoLiquidOverhaulItems.Coco_LargeEmptyPetrolCan --- CocoLiquidOverhaulItems.Coco_LargePetrolCan -- LOCATIONS --- all --- shed --- garagestorage --- garage --- storageunit --- gasstore --- gasstorage --- armyhanger --- armyhanger --- ProceduralDistributions -- StoreShelfMechanics table.insert(ProceduralDistributions.list.StoreShelfMechanics.items, "CocoLiquidOverhaulItems.Coco_LargeEmptyPetrolCan") table.insert(ProceduralDistributions.list.StoreShelfMechanics.items, 5) -- GarageMechanic table.insert(ProceduralDistributions.list.GarageMechanic.items, "CocoLiquidOverhaulItems.Coco_LargeEmptyPetrolCan") table.insert(ProceduralDistributions.list.GarageMechanic.items, 3) --- SuburbsDistributions -- all table.insert(SuburbsDistributions["all"]["bin"].items, "CocoLiquidOverhaulItems.Coco_LargeEmptyPetrolCan") table.insert(SuburbsDistributions["all"]["bin"].items, 0.5) -- storageunit table.insert(SuburbsDistributions["storageunit"]["all"].items, "CocoLiquidOverhaulItems.Coco_LargeEmptyPetrolCan") table.insert(SuburbsDistributions["storageunit"]["all"].items, 2) table.insert(SuburbsDistributions["storageunit"]["all"].items, "CocoLiquidOverhaulItems.Coco_LargePetrolCan") table.insert(SuburbsDistributions["storageunit"]["all"].items, 1.5) -- armyhanger table.insert(SuburbsDistributions["armyhanger"]["metal_shelves"].items, "CocoLiquidOverhaulItems.Coco_LargePetrolCan") table.insert(SuburbsDistributions["armyhanger"]["metal_shelves"].items, 1)
local say say = function(text) local espeak_cmd = [[espeak --stdout -s250 -k18 -a50 -v female2 | play -t wav - \ gain 10 ]] do local _with_0 = io.popen(espeak_cmd, "w") _with_0:write(text) _with_0:close() return _with_0 end end return { say = say }
-- Crafting recipes for pipes minetest.register_craft( { output = "pipeworks:pipe_1_empty 12", recipe = { { "default:steel_ingot", "default:steel_ingot", "default:steel_ingot" }, { "", "", "" }, { "default:steel_ingot", "default:steel_ingot", "default:steel_ingot" } }, }) minetest.register_craft( { output = "pipeworks:straight_pipe_empty 3", recipe = { { "pipeworks:pipe_1_empty", "pipeworks:pipe_1_empty", "pipeworks:pipe_1_empty" }, }, }) minetest.register_craft( { output = "pipeworks:spigot 3", recipe = { { "pipeworks:pipe_1_empty", "" }, { "", "pipeworks:pipe_1_empty" }, }, }) minetest.register_craft( { output = "pipeworks:entry_panel_empty 2", recipe = { { "", "default:steel_ingot", "" }, { "", "pipeworks:pipe_1_empty", "" }, { "", "default:steel_ingot", "" }, }, }) -- Various ancillary pipe devices minetest.register_craft( { output = "pipeworks:pump_off 2", recipe = { { "default:stone", "default:steel_ingot", "default:stone" }, { "default:copper_ingot", "default:mese_crystal_fragment", "default:copper_ingot" }, { "default:steel_ingot", "default:steel_ingot", "default:steel_ingot" } }, }) minetest.register_craft( { output = "pipeworks:valve_off_empty 2", recipe = { { "", "group:stick", "" }, { "default:steel_ingot", "default:steel_ingot", "default:steel_ingot" }, { "", "default:steel_ingot", "" } }, }) minetest.register_craft( { output = "pipeworks:storage_tank_0 2", recipe = { { "", "default:steel_ingot", "default:steel_ingot" }, { "default:steel_ingot", "default:glass", "default:steel_ingot" }, { "default:steel_ingot", "default:steel_ingot", "" } }, }) minetest.register_craft( { output = "pipeworks:grating 2", recipe = { { "default:steel_ingot", "", "default:steel_ingot" }, { "", "pipeworks:pipe_1_empty", "" }, { "default:steel_ingot", "", "default:steel_ingot" } }, }) minetest.register_craft( { output = "pipeworks:flow_sensor_empty 2", recipe = { { "pipeworks:pipe_1_empty", "mesecons:mesecon", "pipeworks:pipe_1_empty" }, }, }) minetest.register_craft( { output = "pipeworks:fountainhead 2", recipe = { { "pipeworks:pipe_1_empty" }, { "pipeworks:pipe_1_empty" } }, })
local skynet = require "skynet" local sc = require "skynet.socketchannel" local socket = require "skynet.socket" local cluster = require "skynet.cluster.core" local channel local session = 1 local node, nodename = ... local command = {} local waiting = {} local function send_request(addr, msg, sz) -- msg is a local pointer, cluster.packrequest will free it local current_session = session local request, new_session, padding = cluster.packrequest(addr, session, msg, sz) session = new_session local tracetag = skynet.tracetag() if tracetag then if tracetag:sub(1,1) ~= "(" then -- add nodename local newtag = string.format("(%s-%s-%d)%s", nodename, node, session, tracetag) skynet.tracelog(tracetag, string.format("session %s", newtag)) tracetag = newtag end skynet.tracelog(tracetag, string.format("cluster %s", node)) channel:request(cluster.packtrace(tracetag)) end return channel:request(request, current_session, padding) end local function wait() local co = coroutine.running() table.insert(waiting, co) skynet.wait(co) end function command.req(...) if channel == nil then wait() end local ok, msg = pcall(send_request, ...) if ok then if type(msg) == "table" then skynet.ret(cluster.concat(msg)) else skynet.ret(msg) end else skynet.error(msg) skynet.response()(false) end end function command.push(addr, msg, sz) if channel == nil then wait() end local request, new_session, padding = cluster.packpush(addr, session, msg, sz) if padding then -- is multi push session = new_session end channel:request(request, nil, padding) end local function read_response(sock) local sz = socket.header(sock:read(2)) local msg = sock:read(sz) return cluster.unpackresponse(msg) -- session, ok, data, padding end function command.changenode(host, port) local c = sc.channel { host = host, port = tonumber(port), response = read_response, nodelay = true, } local succ, err = pcall(c.connect, c, true) if channel then channel:close() end if succ then channel = c for k, co in ipairs(waiting) do waiting[k] = nil skynet.wakeup(co) end skynet.ret(skynet.pack(nil)) else channel = nil -- reset channel skynet.response()(false) end end skynet.start(function() skynet.dispatch("lua", function(session , source, cmd, ...) local f = assert(command[cmd]) f(...) end) end)
-- See LICENSE for terms -- local some globals local type = type local UIL_Measure = UIL.MeasureImage -- called below, image should be a string path that we can validate (otherwise return as is) local function FixPath(image) -- not everything sent from below is an image str (in-game paths all use tga, mods can use png but it can't hurt to check) if not image or type(image) == "string" and not (image:find_lower(".tga") or image:find_lower(".png")) then -- send back it return image end -- If w and h are over 0 then it's a valid image local w, h = UIL_Measure(image) if w > 0 and h > 0 then return image end -- need to reverse string so it finds the last one, since find looks ltr local last = image:reverse():find("/IU/", 1, true) if last then -- we need a neg number for sub + 1 to remove the slash return "UI/" .. image:sub((last * -1) + 1) end -- make sure we don't blank out the icon... If there's some weird issue (Sir McKaby, Destroyer of Mods) return image end function OnMsg.ModsReloaded() -- of course ClassTemplates... local ct = ClassTemplates.Building for _, item in pairs(ct) do item.icon = FixPath(item.icon) item.display_icon = FixPath(item.display_icon) item.encyclopedia_image = FixPath(item.encyclopedia_image) item.upgrade1_icon = FixPath(item.upgrade1_icon) item.upgrade2_icon = FixPath(item.upgrade2_icon) item.upgrade3_icon = FixPath(item.upgrade3_icon) end -- loop through all the mods and test all the icon paths local ModsLoaded = ModsLoaded for i = 1, #ModsLoaded do local mod_def = ModsLoaded[i] -- no items, no paths to fix up (though my mods are probably the only ones with no items) local items = mod_def.items if items then for j = 1, #items do local item = items[j] if item then -- start fixing paths item.icon = FixPath(item.icon) item.display_icon = FixPath(item.display_icon) item.encyclopedia_image = FixPath(item.encyclopedia_image) item.upgrade1_icon = FixPath(item.upgrade1_icon) item.upgrade2_icon = FixPath(item.upgrade2_icon) item.upgrade3_icon = FixPath(item.upgrade3_icon) -- It can happen (I check if it's an image path above) item.value = FixPath(item.value) -- sponsors for k = 1, 5 do local image = "goal_image_" .. k item[image] = FixPath(item[image]) end for k = 1, 5 do local image = "goal_pin_image_" .. k item[image] = FixPath(item[image]) end end end end end end
local L = BigWigs:NewBossLocale("The Black Morass Trash", "itIT") if not L then return end if L then --L.wave = "Wave Warnings" --L.wave_desc = "Announce approximate warning messages for the waves." L.medivh = "Medivh" end
local count = 0 while true do local val = redis.call("LPOP", KEYS[1]) if val then count = count + 1 redis.call("RPUSH", KEYS[2], val) else return count end end
-- -- Created by IntelliJ IDEA. -- User: Noneatme -- Date: 09.02.2015 -- Time: 23:33 -- To change this template use File | Settings | File Templates. -- -- -- Created by IntelliJ IDEA. -- User: Noneatme -- Date: 09.02.2015 -- Time: 23:31 -- To change this template use File | Settings | File Templates. -- cAirBreak = {}; --[[ ]] -- /////////////////////////////// -- ///// New ////// -- ///// Returns: Object ////// -- /////////////////////////////// function cAirBreak:new(...) local obj = setmetatable({}, {__index = self}); if obj.constructor then obj:constructor(...); end return obj; end -- /////////////////////////////// -- ///// ToggleAirbreak ////// -- ///// Returns: void ////// -- /////////////////////////////// function cAirBreak:toggleAirbreak() self.m_bAirbreakEnabled = not(self.m_bAirbreakEnabled); if(self.m_bAirbreakEnabled) then addEventHandler("onClientRender", getRootElement(), self.m_funcRender); for index, ctrl in pairs(self.m_tblControlsToBind) do bindKey(ctrl, "both", self.m_funcRegisterKey) self.m_tblStates[ctrl] = "false" end self.startTick = getTickCount() if(getControlState("forwards")) then self.m_tblStates["forwards"] = "down" end if(getControlState("accelerate")) then self.m_tblStates["accelerate"] = "down" end else removeEventHandler("onClientRender", getRootElement(), self.m_funcRender); for index, ctrl in pairs(self.m_tblControlsToBind) do unbindKey(ctrl, "both", self.m_funcRegisterKey) end local uElement = localPlayer if(isPedInVehicle(localPlayer)) then uElement = getPedOccupiedVehicle(localPlayer) end setElementFrozen(uElement, false) setElementCollisionsEnabled(uElement, true) local x, y = self.lastVX/1.5, self.lastVY/1.5 setElementVelocity(uElement, x*1/getGameSpeed(), y*1/getGameSpeed(), self.lastVZ/1000) end end -- /////////////////////////////// -- ///// registerKey ////// -- ///// Returns: void ////// -- /////////////////////////////// function cAirBreak:registerKey(key, state) self.m_tblStates[key] = state; end -- /////////////////////////////// -- ///// isAnyKeyPressed ////// -- ///// Returns: void ////// -- /////////////////////////////// function cAirBreak:isAnyKeyPressed() for index, state in pairs(self.m_tblStates) do if(state == "down") then return true; end end return false; end -- /////////////////////////////// -- ///// render ////// -- ///// Returns: void ////// -- /////////////////////////////// function cAirBreak:render() if(self.m_bAirbreakEnabled) then local uElement = localPlayer if(isPedInVehicle(localPlayer)) then uElement = getPedOccupiedVehicle(localPlayer) end local x, y, z = getElementPosition(uElement); local rx, ry, rot = getElementRotation(getCamera()) local addx, addy = 0, 0; local value = 5 if not(self:isAnyKeyPressed()) then self.startTick = getTickCount() end local val = (getTickCount()-self.startTick)/1000; if(val > 1) then val = 1 end local progress = getEasingValue(val, "OutQuad"); if(progress > 1) then progress = 1 end value = value*progress; if(self.m_tblStates["forwards"] == "down") or (self.m_tblStates["accelerate"] == "down") then local x1, y1 = getPointFromDistanceRotation(x, y, value, (rot*-1)+180) addx, addy = addx+x-x1, addy+y-y1; end if(self.m_tblStates["backwards"] == "down") or (self.m_tblStates["brake_reverse"] == "down") then local x1, y1 = getPointFromDistanceRotation(x, y, -value, (rot*-1)+180) addx, addy = addx+x-x1, addy+y-y1; end if(self.m_tblStates["left"] == "down") or (self.m_tblStates["vehicle_left"] == "down") then local x1, y1 = getPointFromDistanceRotation(x, y, value, (rot*-1)+90) addx, addy = addx+x-x1, addy+y-y1; end if(self.m_tblStates["right"] == "down") or (self.m_tblStates["vehicle_right"] == "down") then local x1, y1 = getPointFromDistanceRotation(x, y, value, (rot*-1)+270) addx, addy = addx+x-x1, addy+y-y1; end if(self.m_tblStates["lshift"] == "down") then z = z+value end if(self.m_tblStates["lctrl"] == "down") then z = z-value end x, y = x+addx, y+addy setElementFrozen(uElement, true) setElementPosition(uElement, x, y, z) if(getElementType(uElement) == "player") then setElementRotation(uElement, 0, 0, (rot*-1)) else setElementRotation(uElement, 0, 0, rot) end self.lastVX, self.lastVY, self.lastVZ = addx, addy, z -- setElementCollisionsEnabled(uElement, false) else self:toggleAirbreak(); end end -- /////////////////////////////// -- ///// Constructor ////// -- ///// Returns: void ////// -- /////////////////////////////// function cAirBreak:constructor(...) -- Klassenvariablen -- addEvent("onAirbreakToggle", true) self.m_bAirbreakEnabled = false; self.m_tblStates = {} self.m_tblControlsToBind = { "forwards", "backwards", "left", "right", "lshift", "lctrl", "accelerate", "brake_reverse", "vehicle_left", "vehicle_right" } -- Funktionen -- self.m_funcToggleAirbreak = function(...) self:toggleAirbreak(...) end self.m_funcRender = function(...) self:render(...) end -- KEYS -- self.m_funcRegisterKey = function(key, state) self:registerKey(key, state) end -- Events -- addEventHandler("onAirbreakToggle", getLocalPlayer(), self.m_funcToggleAirbreak) end -- EVENT HANDLER --
local E, L, V, P, G, _ = unpack(select(2, ...)); --Inport: Engine, Locales, PrivateDB, ProfileDB, GlobalDB, Localize Underscore local DT = E:GetModule('DataTexts') local LO = E:GetModule('Layout'); local floor = math.floor local join = string.join local IsInRaid = IsInRaid local IsInGroup = IsInGroup local SendChatMessage = SendChatMessage local UnitName = UnitName local UnitHealth = UnitHealth local UnitHealthMax = UnitHealthMax local GetRealZoneText = GetRealZoneText local ToggleFrame = ToggleFrame local displayString = "" local inRestrictedArea = false local function Click(self, button) if button == 'LeftButton' then local chattype = "SAY" if IsInRaid() then chattype = "RAID" elseif IsInGroup() then chattype = "PARTY" end local targetStr, current = '', ''; if UnitName('target') then targetStr = UnitName('target').. '@ ' current = E:GetFormattedText('CURRENT_PERCENT', UnitHealth('target'), UnitHealthMax('target')) end local msg = targetStr.. GetRealZoneText()..": ".. self.loc.. " - ".. current; if ChatFrame1EditBox:IsShown() then ChatFrame1EditBox:Insert(msg); else SendChatMessage(msg, chattype) end elseif button == 'RightButton' then ToggleFrame(WorldMapFrame) end end local function OnEnter(self) DT:SetupTooltip(self) DT.tooltip:AddDoubleLine(L["Left button:"], L["Send player's coord to chatframe"], 0.69, 0.31, 0.31,0.84, 0.75, 0.65) DT.tooltip:AddDoubleLine(L["Right button:"], L["Open world map"], 0.69, 0.31, 0.31,0.84, 0.75, 0.65) DT.tooltip:Show() end local function OnLeave(self) DT.tooltip:Hide() end local function Update(self, elapsed) if inRestrictedArea or not E.MapInfo.coordsWatching then return end self.timeSinceUpdate = (self.timeSinceUpdate or 0) + elapsed if self.timeSinceUpdate > 0.2 then self.text:SetFormattedText(displayString, E.MapInfo.xText or 0, E.MapInfo.yText or 0) self.timeSinceUpdate = 0 end end local function OnEvent(self) E:MapInfo_Update() if E.MapInfo.x and E.MapInfo.y then inRestrictedArea = false self.text:SetFormattedText(displayString, E.MapInfo.xText or 0, E.MapInfo.yText or 0) else inRestrictedArea = true self.text:SetText("N/A") end end local function ValueColorUpdate(hex) displayString = join("", hex, "%.0f|r", " , ", hex, "%.0f|r") end E['valueColorUpdateFuncs'][ValueColorUpdate] = true DT:RegisterDatatext('E_Coord', {"ZONE_CHANGED","ZONE_CHANGED_INDOORS","ZONE_CHANGED_NEW_AREA"}, OnEvent, Update, Click, OnEnter, OnLeave)
local basexx = require 'basexx' local utils = require 'jwt.utils' local pkey = utils.pkey local json = utils.json local HMAC = utils.HMAC local DIGEST = utils.DIGEST local data = {} local function tohex(s) local result = "" for i = 1, #s do result = result..string.format("%.2x", string.byte(s, i)) end return result end data.sign = { ['HS256'] = function(data, key) return HMAC.SHA256(key, data, true) end, ['HS384'] = function(data, key) return HMAC.SHA384(key, data, true) end, ['HS512'] = function(data, key) return HMAC.SHA512(key, data, true) end, ['RS256'] = function(data, key) assert(type(key) == "string") local ok, result = pcall(function() return pkey.sign('SHA256', key, data) end) if not ok then return nil, result end return result end, } data.verify = { ['HS256'] = function(data, signature, key) return signature == HMAC.SHA256(key, data, true) end, ['HS384'] = function(data, signature, key) return signature == HMAC.SHA384(key, data, true) end, ['HS512'] = function(data, signature, key) return signature == HMAC.SHA512(key, data, true) end, ['RS256'] = function(data, signature, key) assert(type(key) == "string") local ok, result = pcall(function() return pkey.verify('SHA256', key, signature, data) end) if not ok then return nil, result end return result end, } function data:encode(header, claims, options) if not options then error("options are required") end if not options.keys then error("keys are required") end local envelope = basexx.to_url64(json.encode(header)).."."..basexx.to_url64(json.encode(claims)) local signature, err = self.sign[header.alg](envelope, options.keys.private) if not signature then error('failed to generate signature') end return envelope ..'.'..basexx.to_url64(signature) end function data:decode(header, str, options) local dotFirst = str:find(".", nil, true) local signature local bodyStr local rawHeader = str:sub(1, dotFirst-1) local str = str:sub(dotFirst+1) local dotSecond = str:find(".", nil, true) if dotSecond then bodyStr = str:sub(1, dotSecond-1) if options and options.keys and options.keys.public then signature = basexx.from_url64(str:sub(dotSecond+1)) end else if options and options.keys and options.keys.public then return nil, "Invalid token" end bodyStr = str end local message = basexx.from_url64(bodyStr) if signature then if not self.verify[header.alg](rawHeader.."."..bodyStr, signature, options.keys.public) then return nil, "Invalid token" end end return json.decode(message) end return data
--[[ luapoly by David Gayerie ]]-- require "circular_table" local new_poly = require "poly" local msg = "" local shape = {} local function parse_args(args) local vertices_chain={} if args[2] then local f = io.open(args[2]) if io.type(f) == "file" then for line in f:lines() do for t in string.gmatch(line, "([%d%.]+)[,%w]?") do table.insert(vertices_chain, tonumber(t)) end end f:close() else for t in string.gmatch(args[2], "([%d%.]+)[,]?") do table.insert(vertices_chain, tonumber(t)) end end end return vertices_chain end function love.load(args) love.graphics.setBackgroundColor(250,250,250) love.graphics.setColor(60,60,60) shape.poly = new_poly(parse_args(args)) end function love.mousepressed(x, y, button) if button == 'l' and shape.is_cw_winding == nil then shape.poly:push_coord(x, y) elseif button == 'r' then shape.poly:close() if shape.poly:is_closed() then shape.is_convex = shape.poly:is_convex() shape.is_cw_winding = shape.poly:is_cw() shape.triangles = shape.poly:get_triangles() print("triangulation of (".. table.concat(shape.poly, ",")..")") for _,triangle in ipairs(shape.triangles) do print("("..table.concat(triangle,",")..")") end end end end function love.keypressed(key, isrepeat) if key == "backspace" or key == "delete" then shape.poly:pop_coord() shape.is_convex = nil shape.is_cw_winding = nil shape.triangles = nil end end function love.update(dt) if shape.is_cw_winding == nil then msg = "Add points (left click)" if shape.poly:get_coord_count() > 2 then msg = msg .. " or close the polygon (right click to close)" end else msg = shape.is_convex and "Convex polygon" or "Concave polygon" msg = msg .. (shape.is_cw_winding and " (clockwise winding)" or " (counterclockwise winding)") end end local color_components = to_circular_table{255,0,0, 125, 125, 0, 80, 175, 0} function love.draw() if shape.triangles then local color = {love.graphics.getColor()} local color_index=1 for _,triangle in ipairs(shape.triangles) do love.graphics.setColor(color_components[color_index], color_components[color_index+1], color_components[color_index+2], 150) color_index = color_index + 1 local x1, y1 = shape.poly:get_coord(triangle[1]) local x2, y2 = shape.poly:get_coord(triangle[2]) local x3, y3 = shape.poly:get_coord(triangle[3]) love.graphics.polygon("fill", x1, y1, x2, y2, x3, y3) end love.graphics.setColor(color) end local coord_count = shape.poly:get_coord_count() if coord_count == 1 then love.graphics.point(shape.poly:get_coord(1)) elseif coord_count > 1 then love.graphics.line(shape.poly) end love.graphics.print(msg, 10, 10) end
local Entity = FindMetaTable 'Entity' local encode = util.TableToJSON -- Can be spon.encode, pon2.encode or some other encoding method ( table to string ) local decode = util.JSONToTable -- Can be spon.decode, pon2.decode or some other decoding method ( string to table ) function Entity:SetNWTable( key, tbl ) self:SetNWString( key, encode( tbl ) ) end function Entity:GetNWTable( key ) return decode( self:GetNWString( key ) ) or {} end function Entity:SetNW2Table( key, tbl ) self:SetNW2String( key, encode( tbl ) ) end function Entity:GetNW2Table( key ) return decode( self:GetNW2String( key ) ) or {} end function SetGlobalTable( index, tbl ) SetGlobalString( index, encode( tbl ) ) end function GetGlobalTable( index ) return decode( GetGlobalString( index ) ) or {} end
-- Run all unit tests in 'unit' directory local telescope = require "telescope" require "rspamd_assertions" local loaded, luacov = pcall(require, 'luacov.runner') if not loaded then luacov = { init = function() end, shutdown = function() end, run_report = function() end } end luacov.init() local contexts = {} for _,t in ipairs(tests_list) do telescope.load_contexts(t, contexts) end local function test_filter(test) return test.name:match(test_pattern) end if not test_pattern then test_filter = function(_) return true end end local buffer = {} local results = telescope.run(contexts, callbacks, test_filter) local summary, data = telescope.summary_report(contexts, results) table.insert(buffer, telescope.test_report(contexts, results)) table.insert(buffer, summary) local report = telescope.error_report(contexts, results) if report then table.insert(buffer, "") table.insert(buffer, report) end if #buffer > 0 then print(table.concat(buffer, "\n")) end for _, v in pairs(results) do if v.status_code == telescope.status_codes.err or v.status_code == telescope.status_codes.fail then os.exit(1) end end luacov:shutdown() luacov:run_report()
-- local M = {} local copy = require('mx_py.copy') local ctypes = require('ctypes') local base = require('mx.base') local _LIB, mx_uint, NDArrayHandle, ExecutorHandle, py_str, mx_int, check_call, c_handle_array, c_array_buf, c_str_array = base._LIB, base.mx_uint, base.NDArrayHandle, base.ExecutorHandle, base.py_str, base.mx_int, base.check_call, base.c_handle_array, base.c_array_buf, base.c_str_array local __ndarray = require('mx.ndarray.__init__') local NDArray = __ndarray.NDArray local _ndarray_cls = __ndarray._ndarray_cls local function _monitor_callback_wrapper(callback) return function(name, array, _) callback(name, array) end end ---@class mx.executor.Executor ---@field arg_dict table<string, mx.ndarray.NDArray> ---@field grad_dict table<string, mx.ndarray.NDArray> ---@field aux_dict table<string, mx.ndarray.NDArray> ---@field output_dict table<string, mx.ndarray.NDArray> local Executor = class('mx.executor.Executor') M.Executor = Executor function Executor:ctor(handle, symbol, ctx, grad_req, group2ctx) --if not isinstance(handle, ExecutorHandle) then if not ctypes.is_ctype(handle) then print(handle, type(handle), type(handle.value)) raise('TypeError', 'Handle type error') end self.handle = handle self.arg_arrays = {} self.grad_arrays = {} self.aux_arrays = {} self.outputs = self:_get_outputs() self._symbol = copy.deepcopy(symbol) self._optimized_symbol = None self._arg_dict = None self._grad_dict = None self._aux_dict = None self._output_dict = None self._monitor_callback = None self._ctx = copy.deepcopy(ctx) self._grad_req = copy.deepcopy(grad_req) self._group2ctx = copy.deepcopy(group2ctx) end function Executor:dtor() check_call(_LIB.MXExecutorFree(self.handle)) end function Executor._get_dict(names, ndarrays) local nset = {} for _, nm in ipairs(names) do if nset[nm] then raise('ValueError', 'Duplicate names detected: ' .. nm) end nset[nm] = true end local ret = {} for i = 1, #names do ret[names[i]] = ndarrays[i] end return ret end function Executor:_get_outputs() local out_size = mx_uint() local handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorOutputs(self.handle, ctypes.byref(out_size), ctypes.byref(handles))) local num_output = out_size.value local outputs = {} for i = 1, num_output do table.insert(outputs, _ndarray_cls(NDArrayHandle(handles[i - 1]))) end return outputs end function Executor:forward(is_train, kwargs) is_train = default(is_train, false) if kwargs and not table.empty(kwargs) then local arg_dict = self.arg_dict for name, array in pairs(kwargs) do if not isinstance(array, NDArray) then raise('ValueError', 'only accept keyword argument of NDArrays') end if not arg_dict[name] then raise('TypeError', 'Unknown argument ' .. name) end if not table.equal(arg_dict[name], array.shape) then raise('ValueError', 'shape not match') end arg_dict[name][{}] = array end end check_call(_LIB.MXExecutorForward( self.handle, ctypes.c_int(is_train))) self.outputs = self:_get_outputs() return self.outputs end function Executor:backward(out_grads, is_train) is_train = default(is_train, true) if isnone(out_grads) then out_grads = {} elseif isinstance(out_grads, NDArray) then out_grads = { out_grads } elseif #out_grads == 0 then -- is dict local tmp = {} for _, k in ipairs(self._symbol:list_outputs()) do table.insert(tmp, out_grads[k]) end out_grads = tmp end for _, v in ipairs(out_grads) do if not isinstance(v, NDArray) then raise('TypeError', 'inputs must be NDArray') end end local arr = c_handle_array(out_grads) check_call(_LIB.MXExecutorBackwardEx( self.handle, mx_uint(len(out_grads)), arr, ctypes.c_int(is_train))) end function Executor:set_monitor_callback(callback, monitor_all) monitor_all = default(monitor_all, false) --cb_type = ctypes.CFUNCTYPE(None, ctypes.c_char_p, NDArrayHandle, ctypes.c_void_p) --self._monitor_callback = cb_type(_monitor_callback_wrapper(callback)) self._monitor_callback = ffi.cast('void(*)(const char*, void*, void*)', _monitor_callback_wrapper(callback)) check_call(_LIB.MXExecutorSetMonitorCallbackEX( self.handle, self._monitor_callback, nil, ctypes.c_int(monitor_all))) end function Executor:__arg_dict() if isnone(self._arg_dict) then self._arg_dict = Executor._get_dict( self._symbol:list_arguments(), self.arg_arrays) end return self._arg_dict end function Executor:__grad_dict() if isnone(self._grad_dict) then self._grad_dict = Executor._get_dict( self._symbol:list_arguments(), self.grad_arrays) end return self._grad_dict end function Executor:__aux_dict() if isnone(self._aux_dict) then self._aux_dict = Executor._get_dict( self._symbol:list_auxiliary_states(), self.aux_arrays) end return self._aux_dict end function Executor:__output_dict() if isnone(self._output_dict) then self._output_dict = Executor._get_dict( self._symbol:list_outputs(), self.outputs) end return self._output_dict end function Executor:copy_params_from(arg_params, aux_params, allow_extra_params) allow_extra_params = default(allow_extra_params, false) for name, array in pairs(arg_params) do if self.arg_dict[name] then local dst = self.arg_dict[name] array:astype(dst.dtype):copyto(dst) elseif not allow_extra_params then raise('ValueError', ('name %s is not in the arguments'):format(name)) end end if isnone(aux_params) then return end for name, array in pairs(aux_params) do if self.aux_dict[name] then local dst = self.aux_dict[name] array:astype(dst.dtype):copyto(dst) elseif not allow_extra_params then raise('ValueError', ('name %s is not in the auxiliary states'):format(name)) end end end function Executor:reshape(partial_shaping, allow_up_sizing, kwargs) partial_shaping, allow_up_sizing, kwargs = default( partial_shaping, false, allow_up_sizing, false, kwargs, {}) local provided_arg_shape_data = {} -- shape data -- argument shape index in sdata, -- e.g. [sdata[indptr[0]], sdata[indptr[1]]) is the shape of the first arg local provided_arg_shape_idx = { 0 } local provided_arg_shape_names = {} -- provided argument names for k, v in pairs(kwargs) do if islist(v) then table.insret(provided_arg_shape_names, k) table.append(provided_arg_shape_data, v) table.insret(provided_arg_shape_idx, #provided_arg_shape_data) end end local ctx_map_keys = {} local ctx_map_dev_types = {} local ctx_map_dev_ids = {} if self._group2ctx then for key, val in pairs(self._group2ctx) do table.insret(ctx_map_keys, key) table.insret(ctx_map_dev_types, val.device_typeid) table.insret(ctx_map_dev_ids, val.device_id) end end local handle = ExecutorHandle() local shared_handle = self.handle local num_in_args = ctypes.c_uint() local in_arg_handles = ctypes.POINTER(NDArrayHandle)() local arg_grad_handles = ctypes.POINTER(NDArrayHandle)() local num_aux_states = ctypes.c_uint() local aux_state_handles = ctypes.POINTER(NDArrayHandle)() check_call(_LIB.MXExecutorReshapeEx(ctypes.c_int(partial_shaping), ctypes.c_int(allow_up_sizing), ctypes.c_int(self._ctx.device_typeid), ctypes.c_int(self._ctx.device_id), mx_uint(len(ctx_map_keys)), c_str_array(ctx_map_keys), c_array_buf(ctypes.c_int, ctx_map_dev_types), c_array_buf(ctypes.c_int, ctx_map_dev_ids), mx_uint(len(provided_arg_shape_names)), c_str_array(provided_arg_shape_names), c_array_buf(mx_int, provided_arg_shape_data), c_array_buf(mx_uint, provided_arg_shape_idx), ctypes.byref(num_in_args), ctypes.byref(in_arg_handles), ctypes.byref(arg_grad_handles), ctypes.byref(num_aux_states), ctypes.byref(aux_state_handles), shared_handle, ctypes.byref(handle))) local arg_arrays = table.arange(function(i) return _ndarray_cls(NDArrayHandle(in_arg_handles[i - 1])) end, num_in_args.value) local grad_arrays = table.arange(function(i) local hdl = arg_grad_handles[i] if ffi.isnullptr(hdl) then return None else return _ndarray_cls(hdl) end end, num_in_args.value) local aux_arrays = table.arange(function(i) return _ndarray_cls(NDArrayHandle(aux_state_handles[i - 1])) end, num_aux_states.value) local executor = Executor(handle, self._symbol, self._ctx, self._grad_req, self._group2ctx) executor.arg_arrays = arg_arrays executor.grad_arrays = grad_arrays executor.aux_arrays = aux_arrays return executor end function Executor:debug_str() local debug_str = ctypes.c_char_p() check_call(_LIB.MXExecutorPrint( self.handle, ctypes.byref(debug_str))) return py_str(debug_str.value) end local _field = { arg_dict = Executor.__arg_dict, grad_dict = Executor.__grad_dict, aux_dict = Executor.__aux_dict, output_dict = Executor.__output_dict, } function Executor:__index(k) local tk = type(k) if tk == 'string' then if _field[k] then return _field[k](self) elseif not isnone(Executor[k]) then return Executor[k] end end return rawget(self, k) end return M
local _ = require "lib.lume" local Entity = require "core.entity" local Tile = Entity:extend() local TileMap = Entity:extend() function Tile:new(filename, tilesize, index, cache) Tile.super.new(self) if cache then self.image = cache.image self.frames = cache.frames self.width, self.height = tilesize, tilesize else self:loadImage(filename, tilesize, tilesize) end self.frame = index self.solid = true self.moves = false end TileMap.Tile = Tile function TileMap:new() TileMap.super.new(self) self.solid = false end function TileMap:loadArray(array, width, imageFile, tileSize) if #array % width ~= 0 then error("expected array to be divisible by width") end self.data = _.clone(array) self.widthInTiles = width self.heightInTiles = #array / width self.tileSize = tileSize self.tiles = {} local cache = Tile(imageFile, tileSize, 1) for i = 1, math.huge do local tile = Tile(imageFile, tileSize, i, cache) table.insert(self.tiles, tile) if i == #tile.frames then break end end self.width = self.widthInTiles * self.tileSize self.height = self.heightInTiles * self.tileSize end function TileMap:loadTMX(filename, imageFile) local text = sol.fs.read(filename) local ptn = '"csv">(.-)<' local s = text:match(ptn) print(s) assert(s, "tile layer does not exist") local data = _.map(_.split(s, ","), tonumber) local width = tonumber(text:match('width="(.-)"')) local tileSize = tonumber(text:match('tilewidth="(.-)"')) if not imageFile then imageFile = text:match('image source="(.-)"'):gsub("%.%.", "data") end self:loadArray(data, width, imageFile, tileSize) return self end function TileMap:getTile(x, y) local t = self.tiles[self.data[x + y * self.widthInTiles + 1]] if t then t.x, t.y = x * self.tileSize + self.x, y * self.tileSize + self.y return t end end function TileMap:eachOverlappingTile(r, fn, revx, revy, ...) local sx = math.floor((r:left() - self.x) / self.tileSize) local sy = math.floor((r:top() - self.y) / self.tileSize) local ex = math.floor((r:right() - self.x) / self.tileSize) local ey = math.floor((r:bottom() - self.y) / self.tileSize) sx, sy = math.max(sx, 0), math.max(sy, 0) ex = math.min(ex, self.widthInTiles - 1) ey = math.min(ey, self.heightInTiles - 1) if revx then sx, ex = ex, sx end if revy then sy, ey = ey, sy end for y = sy, ey, (revy and -1 or 1) do for x = sx, ex, (revx and -1 or 1) do local t = self:getTile(x, y) if t then fn(t, ...) end end end end function TileMap:update(dt) TileMap.super.update(self, dt) _.each(self.tiles, "update", dt) end function TileMap:draw() -- self:eachOverlappingTile(Tile.draw) end return TileMap
-- KEYS[1]: the job data hash -- KEYS[2]: the active job list -- KEYS[3]: the signal list -- ARGV[1]: the job ID -- ARGV[2]: the serialized job data -- Returns: 1 if the job was newly enqueued, 0 if it already exists -- Set job data in hash local set = redis.call("hsetnx", KEYS[1], ARGV[1], ARGV[2]) if set == 1 then -- If it was set, push the job on to the active list redis.call("rpush", KEYS[2], ARGV[1]) -- Signal that there are jobs in the queue redis.call("del", KEYS[3]) redis.call("lpush", KEYS[3], 1) end return set
function foo() for i = 1, 10 do print(i) coroutine.wait(1) end end local co= coroutine.start(foo)
-- this file is generated by xresloader, please don't edit it. return { [1] = { count = 5, data_source = { { file = "资源转换示例.xlsx", sheet = "test_oneof", }, }, data_ver = "1.0.0.0", description = "Test event_cfg with oneof fields", hash_code = "no hash code", xres_ver = "2.10.2", }, [2] = "event_cfg", event_cfg = { { item = { item_id = 1511, item_count = 1512, nested_note = "啦啦啦", }, process = 1, id = 50001, rule = { nested_note = "内嵌one of文本", rule_id = 511, rule_param = 512, }, specify_field = { nested_enum_type = 10001, }, test_arr = { { nested_note = "内嵌one of文本", rule_id = 711, rule_param = 712, }, }, }, { process = 2, id = 50002, rule = { rule_id = 521, rule_param = 522, nested_enum_type = 10001, }, specify_field = { nested_enum_type = 10001, }, test_arr = { { rule_id = 721, rule_param = 722, nested_enum_type = 10001, }, { rule_id = 821, rule_param = 822, nested_enum_type = 10101, }, { nested_note = "数组嵌套one of", rule_param = 822, rule_id = 921, }, }, user_exp = 1473624235014785965, }, { process = 3, enum_type = 10001, id = 50003, rule = { rule_id = 531, rule_param = 532, nested_enum_type = 10101, }, specify_field = { nested_enum_type = 10101, }, }, { note = "", process = 4, id = 50004, rule = { rule_id = 541, rule_param = 542, }, }, { process = 5, id = 50005, rule = { rule_id = 551, rule_param = 552, }, }, }, }
local spacing = 60 local bar_height = 8 local bar_width = 45 local flow_height = 48 local flow_width = 600 local nps_baseline = 600 local nps_scale = -0.09 local flow_baseline = 0 local flow_scale = 1 local flow_mark = 12 local bound_mark = 4 local arrow_offset = 20 local data_width = (30 + bar_width + 40 + bar_width) local text_width = 300 FlowDJ.flow_width = flow_width FlowDJ.NpsScale = function(x) return (x * nps_scale + 1) * flow_width end return Def.ActorFrame { Name = "song list item", InitCommand = function(self) self.SetSelection = function(self, sel, n, f, flow, current) self:xy(0, n*spacing) self:visible(true) local brightness = 0.5 if current then brightness = 1 end local x = flow_width local y = -spacing * 0.2 x = x + 30 local meter_text = self:GetChild("meter text") meter_text:settext(sel.meter) meter_text:xy(x - meter_text:GetWidth()*0.5, y) x = x + 5 local meter_bar = self:GetChild("meter bar") meter_bar:setsize(sel.meter / 15 * bar_width, bar_height) meter_bar:xy(x + sel.meter / 15 * bar_width / 2, y) x = x + bar_width x = flow_width y = spacing * 0.2 x = x + 55 local nps_text = self:GetChild("nps text") nps_text:settextf("%0.1f", sel.nps) nps_text:xy(x - nps_text:GetWidth()*0.5, y) x = x + 5 local nps_bar = self:GetChild("nps bar") nps_bar:setsize(sel.nps / 10 * bar_width, bar_height) nps_bar:xy(x + sel.nps / 10 * bar_width / 2, y) x = x + bar_width x = 0 y = -spacing * 0.2 local title = self:GetChild("title") title:settext(sel.song:GetDisplayFullTitle()) title:xy(x + 10 + title:GetWidth()*0.5, y) x = 10 y = spacing * 0.2 local artist = self:GetChild("artist") artist:settext(sel.song:GetDisplayArtist()) artist:xy(x + 10 + artist:GetWidth()*0.5, y) x = -50 y = -spacing * 0.2 local group = self:GetChild("group") group:settext(sel.song:GetGroupName()) group:xy(x + 10 - group:GetWidth()*0.5, y) x = -60 y = spacing * 0.2 local author = self:GetChild("step author") author:settext(sel.steps:GetAuthorCredit()) author:xy(x + 10 - author:GetWidth()*0.5, y) local flow_backdrop = self:GetChild("flow backdrop") flow_backdrop:setsize(flow_width, flow_height) if SL then flow_backdrop:diffuserightedge(Alpha(Color.White, 0.4)) flow_backdrop:diffuseleftedge(Alpha(Color.White, 0.1)) else if current then flow_backdrop:diffuserightedge(Alpha(Color.Black, 0.8)) flow_backdrop:diffuseleftedge(Alpha(Color.Black, 0.2)) else flow_backdrop:diffuserightedge(Alpha(Color.Black, 0.5)) flow_backdrop:diffuseleftedge(Alpha(Color.Black, 0.1)) end end local group_backdrop = self:GetChild("group backdrop") group_backdrop:setsize(flow_width, flow_height) if SL then group_backdrop:diffuserightedge(Alpha(Color.Black, 0.4)) group_backdrop:diffuseleftedge(Alpha(Color.Black, 0.00)) else if current then group_backdrop:diffuserightedge(Alpha(Color.Black, 0.8)) group_backdrop:diffuseleftedge(Alpha(Color.Black, 0.0)) else group_backdrop:diffuserightedge(Alpha(Color.Black, 0.5)) group_backdrop:diffuseleftedge(Alpha(Color.Black, 0.0)) end end local left_arrow = self:GetChild("left wiggle") local flow_range = self:GetChild("flow range") if left_arrow:GetVisible() then flow_range:visible(true) local range_left = flow.wiggle_base(f) * flow_width local range_right = (flow.wiggle_base(f) + flow.wiggle_range(f)) * flow_width flow_range:setsize(range_right - range_left, flow_height) flow_range:xy(range_left + (range_right - range_left)/2, 0) flow_range:diffuse(Brightness(Color.White, 0.5 * brightness)) if current then flow_range:glowshift() flow_range:effectcolor1(Brightness(Color.White, 0.6)) flow_range:effectcolor2(Brightness(Color.White, 0.8)) flow_range:effectperiod(2) end left_arrow:xy(range_right - arrow_offset, 0) local right_arrow = self:GetChild("right wiggle") right_arrow:xy(range_right + arrow_offset, 0) else flow_range:visible(false) end local score_bound = self:GetChild("score bound") score_bound:setsize(bound_mark, flow_height) score_bound:xy(flow.score_bound(f) * flow_width, 0) score_bound:diffuse(Brightness(Color.White, 0.5 * brightness)) if current then score_bound:glowshift() score_bound:effectcolor1(Brightness(Color.White, 0.6)) score_bound:effectcolor2(Brightness(Color.White, 0.8)) score_bound:effectperiod(2) end local nps_mark = self:GetChild("nps lower bound") if nps_mark:GetVisible() and sel.nps_bottom and sel.nps_top then nps_mark:setsize(bound_mark, flow_height) local x = FlowDJ.NpsScale(flow.nps_lower_bound(f)) nps_mark:xy(x, 0) nps_mark:diffuse(Brightness(Color.Red, brightness)) if current then nps_mark:glowshift() nps_mark:effectcolor1(Brightness(Color.Red, 0.8)) nps_mark:effectcolor2(Brightness(Color.Red, 1.0)) nps_mark:effectperiod(2) end local left_arrow = self:GetChild("left slowest") left_arrow:xy(x - arrow_offset, 0) local right_arrow = self:GetChild("right slowest") right_arrow:xy(x + arrow_offset, 0) end --[[ local nps_mark = self:GetChild("nps upper bound") nps_mark:setsize(bound_mark, flow_height) nps_mark:xy(FlowDJ.NpsScale(flow.nps_upper_bound(f)), 0) nps_mark:diffuse(Brightness(Color.Red, brightness)) if current then nps_mark:glowshift() nps_mark:effectcolor1(Brightness(Color.Red, 0.8)) nps_mark:effectcolor2(Brightness(Color.Red, 1.0)) nps_mark:effectperiod(2) end ]] local nps_mark = self:GetChild("nps mark") nps_mark:setsize(flow_mark, flow_height) nps_mark:xy(FlowDJ.NpsScale(sel.nps), 0) nps_mark:diffuse(Brightness(Color.Red, brightness)) if current then nps_mark:glowshift() nps_mark:effectcolor1(Brightness(Color.Red, 0.8)) nps_mark:effectcolor2(Brightness(Color.Red, 1.0)) nps_mark:effectperiod(2) end local predicted_score = self:GetChild("predicted score") predicted_score:setsize(flow_mark, flow_height) predicted_score:xy(sel.predicted_score * flow_width, 0) predicted_score:diffuse(Brightness(Color.Blue, brightness)) if current then predicted_score:glowshift() predicted_score:effectcolor1(Brightness(Color.Blue, 0.8)) predicted_score:effectcolor2(Brightness(Color.Blue, 1.0)) predicted_score:effectperiod(2) end if sel.score ~= 0 then local actual_score = self:GetChild("actual score") actual_score:setsize(flow_mark, flow_height) actual_score:xy(sel.score * flow_width, 0) actual_score:diffuse(Brightness(Color.White, brightness)) if current then actual_score:glowshift() actual_score:effectcolor1(Brightness(Color.White, 0.8)) actual_score:effectcolor2(Brightness(Color.White, 1.0)) actual_score:effectperiod(2) end end local score_text = self:GetChild("score text") score_text:settextf("%2d", math.floor(sel.effective_score * 100)) score_text:xy(flow_width - 10 - score_text:GetWidth()*0.5, 0) end self.DifficultyArrowsOn = function(self, flow, range) local left_arrow = self:GetChild("left arrow") left_arrow:xy((flow - range * 2) * flow_width, 0) left_arrow:visible(true) local right_arrow = self:GetChild("right arrow") right_arrow:xy((flow + range * 2) * flow_width, 0) right_arrow:visible(true) end self.DifficultyArrowsOff = function(self) local left_arrow = self:GetChild("left arrow") left_arrow:visible(false) local right_arrow = self:GetChild("right arrow") right_arrow:visible(false) end self.ScoreMarkOn = function(self) local score_bound = self:GetChild("score bound") score_bound:visible(true) end self.ScoreMarkOff = function(self) local score_bound = self:GetChild("score bound") score_bound:visible(false) end self.WiggleArrowsOn = function(self, flow) local left_arrow = self:GetChild("left wiggle") left_arrow:visible(true) local right_arrow = self:GetChild("right wiggle") right_arrow:visible(true) end self.WiggleArrowsOff = function(self) local left_arrow = self:GetChild("left wiggle") left_arrow:visible(false) local right_arrow = self:GetChild("right wiggle") right_arrow:visible(false) end self.StagesArrowsOn = function(self) local up_arrow = self:GetChild("up arrow") up_arrow:xy(flow_width, -spacing) up_arrow:visible(true) local down_arrow = self:GetChild("down arrow") down_arrow:xy(flow_width, spacing) down_arrow:visible(true) end self.StagesArrowsOff = function(self) local up_arrow = self:GetChild("up arrow") up_arrow:visible(false) local down_arrow = self:GetChild("down arrow") down_arrow:visible(false) end self.SlowestArrowsOn = function(self, flow) --local left_arrow = self:GetChild("left slowest") --left_arrow:visible(true) --local right_arrow = self:GetChild("right slowest") --right_arrow:visible(true) local nps_mark = self:GetChild("nps lower bound") nps_mark:visible(true) end self.SlowestArrowsOff = function(self) local left_arrow = self:GetChild("left slowest") left_arrow:visible(false) local right_arrow = self:GetChild("right slowest") right_arrow:visible(false) local nps_mark = self:GetChild("nps lower bound") nps_mark:visible(false) end end, Def.Quad{ Name= "flow backdrop", InitCommand = function(self) self:setsize(0, 0) self:xy(flow_width/2, 0) end, }, Def.Quad{ Name= "group backdrop", InitCommand = function(self) self:setsize(0, 0) self:xy(-flow_width/2 - 30, 0) end, }, Def.BitmapText{ Name = "up arrow", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENUUP;") self:zoom(2) end, }, Def.BitmapText{ Name = "down arrow", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENUDOWN;") self:zoom(2) end, }, Def.Quad{ Name= "flow range" }, Def.Quad{ Name= "score bound" }, Def.Quad{ Name= "nps lower bound" }, Def.Quad{ Name= "nps upper bound" }, Def.BitmapText{ Name = "left arrow", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENULEFT;") end, }, Def.BitmapText{ Name = "right arrow", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENURIGHT;") end, }, Def.Quad{ Name= "nps mark" }, Def.Quad{ Name= "predicted score" }, Def.Quad{ Name= "actual score" }, Def.BitmapText{ Name = "left wiggle", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENULEFT;") end, }, Def.BitmapText{ Name = "right wiggle", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENURIGHT;") end, }, Def.BitmapText{ Name = "left slowest", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENULEFT;") end, }, Def.BitmapText{ Name = "right slowest", Font = "Common Normal", InitCommand = function(self) self:visible(false) self:settext("&MENURIGHT;") end, }, Def.BitmapText{ Name = "title", Font = "Common Normal" }, Def.BitmapText{ Name = "artist", Font = "Common Normal" }, Def.BitmapText{ Name = "group", Font = "Common Normal" }, Def.BitmapText{ Name = "step author", Font = "Common Normal" }, Def.BitmapText{ Name = "score text", Font = "Common Normal" }, Def.BitmapText{ Name = "meter text", Font = "Common Normal" }, Def.Quad{ Name= "meter bar" }, Def.BitmapText{ Name = "nps text", Font = "Common Normal" }, Def.Quad{ Name= "nps bar" }, }
return { second = 1, minute = 60, hour = 3600, day = 86400, month = 2592000, year = 31536000, }
object_static_structure_dathomir_biohazard_sign_03 = object_static_structure_dathomir_shared_biohazard_sign_03:new { } ObjectTemplates:addTemplate(object_static_structure_dathomir_biohazard_sign_03, "object/static/structure/dathomir/biohazard_sign_03.iff")
local skynet = require "skynet" local cls = class("online") function cls:ctor(context, ... ) -- body cls.super.ctor(self, context) return self end function cls:login() -- body local uid = self.context.uid local subid = self.context.subid local ok = skynet.call(".ONLINE_MGR", "lua", "login", uid, subid, skynet.self()) end function cls:logout() -- body local uid = self.context.uid local subid = self.context.subid skynet.call(".ONLINE_MGR", "lua", "logout", uid, subid) end function cls:authed(args) -- body local fd = assert(args.client) local uid = self.context.uid local subid = self.context.subid skynet.call(".ONLINE_MGR", "lua", "authed", uid, subid, fd) end function cls:afk( ... ) -- body local uid = self.context.uid local subid = self.context.subid skynet.call(".ONLINE_MGR", "lua", "afk", uid, subid) end return cls
local CorePackages = game:GetService("CorePackages") local CoreGui = game:GetService("CoreGui") local Players = game:GetService("Players") local GuiService = game:GetService("GuiService") local RunService = game:GetService("RunService") local Roact = require(CorePackages.Roact) local RoactRodux = require(CorePackages.RoactRodux) local Components = script.Parent.Parent local PlayerList = Components.Parent local ClosePlayerDropDown = require(PlayerList.Actions.ClosePlayerDropDown) local SetPlayerListVisibility = require(PlayerList.Actions.SetPlayerListVisibility) local isNewInGameMenuEnabled = require(CoreGui.RobloxGui.Modules.isNewInGameMenuEnabled) local FFlagXboxReportPlayerLocFix = require(CoreGui.RobloxGui.Modules.Flags.FFlagXboxReportPlayerLocFix) local RobloxGui = CoreGui:WaitForChild("RobloxGui") local TenFootSideBar = Roact.PureComponent:extend("TenFootSideBar") local function openPlatformProfileUI(platformId) pcall(function() local platformService = game:GetService("PlatformService") if platformId and #platformId > 0 then platformService:PopupProfileUI(Enum.UserInputType.Gamepad1, platformId) end end) end function TenFootSideBar:init() self.sideBar = nil end function TenFootSideBar:render() return nil end function TenFootSideBar:shouldShowSidebar(player, platformId) if RunService:IsStudio() then --Don't show sidebar in xbox emulator in studio. return false, false end local addReportItem = false if player ~= Players.LocalPlayer then addReportItem = true end local addGamerCardItem = false if platformId and #platformId > 0 then addGamerCardItem = true end return addReportItem, addGamerCardItem end function TenFootSideBar:openSidebar(player) local platformId pcall(function() local platformService = game:GetService("PlatformService") platformId = platformService:GetPlatformId(player.UserId) end) local addReportItem, addGamerCardItem = self:shouldShowSidebar(player, platformId) if not (addReportItem or addGamerCardItem) then self.props.closeSideBar() return end local savedSelectedGuiObject = GuiService.SelectedCoreObject local screenManagerModule = RobloxGui.Modules:FindFirstChild("ScreenManager") or RobloxGui.Modules.Shell.ScreenManager local ScreenManager = require(screenManagerModule) local stringsModule = RobloxGui.Modules:FindFirstChild("LocalizedStrings") or RobloxGui.Modules.Shell.LocalizedStrings local Strings = require(stringsModule) self.sideBar:RemoveAllItems() if addGamerCardItem then self.sideBar:AddItem(Strings:LocalizedString("ViewGamerCardWord"), function() openPlatformProfileUI(platformId) end) end --Remove with FIntNewInGameMenuPercentRollout local ReportAbuseMenu = require(RobloxGui.Modules.Settings.Pages.ReportAbuseMenu) --We can't report guests/localplayer if addReportItem then local loc_text = FFlagXboxReportPlayerLocFix and Strings:LocalizedString("ReportPlayer") or Strings:LocalizedString("Report Player") self.sideBar:AddItem(loc_text, function() --Force closing player list before open the report tab self.props.closePlayerList() GuiService.SelectedCoreObject = nil if isNewInGameMenuEnabled() then -- todo: move InGameMenu to a script global when removing isNewInGameMenuEnabled local InGameMenu = require(RobloxGui.Modules.InGameMenu) InGameMenu.openReportDialog(player) else ReportAbuseMenu:ReportPlayer(player) end end) end local closedCon = nil --Will fire when sidebar closes, fires before the item callback closedCon = self.sideBar.Closed:connect(function() closedCon:disconnect() self.props.closeSideBar() if self.props.playerListVisible then if savedSelectedGuiObject and savedSelectedGuiObject.Parent then GuiService.SelectedCoreObject = savedSelectedGuiObject else --Toogle menu to reselect local players frame. self.props.closePlayerList() self.props.openPlayerList() end end end) ScreenManager:OpenScreen(self.sideBar, false) end function TenFootSideBar:didMount() if not RunService:IsStudio() then local sideBarModule = RobloxGui.Modules:FindFirstChild("SideBar") or RobloxGui.Modules.Shell.SideBar local createSideBarFunc = require(sideBarModule) self.sideBar = createSideBarFunc() end if self.props.sideBarVisible then self:openSidebar(self.props.selectedPlayer) end end function TenFootSideBar:didUpdate(prevProps) if self.props.sideBarVisible and self.props.sideBarVisible ~= prevProps.sideBarVisible then self:openSidebar(self.props.selectedPlayer) end end local function mapStateToProps(state) return { selectedPlayer = state.playerDropDown.selectedPlayer, sideBarVisible = state.displayOptions.isTenFootInterface and state.playerDropDown.isVisible, playerListVisible = state.displayOptions.isVisible, } end local function mapDispatchToProps(dispatch) return { closeSideBar = function() return dispatch(ClosePlayerDropDown()) end, closePlayerList = function() return dispatch(SetPlayerListVisibility(false)) end, openPlayerList = function() return dispatch(SetPlayerListVisibility(true)) end, } end return RoactRodux.UNSTABLE_connect2(mapStateToProps, mapDispatchToProps)(TenFootSideBar)
local helpers = require "spec.helpers" local admin_api = require "spec.fixtures.admin_api" local cjson = require "cjson" for _, strategy in helpers.each_strategy() do describe("Plugin: upstream-basic-auth (invalidations) [#" .. strategy .. "]", function() local admin_client local proxy_client local db lazy_setup(function() _, db = helpers.get_db_utils(strategy, { "routes", "services", "consumers", "plugins", "basicauth_credentials", "upstreambasicauth_credentials", }, {"upstream-basic-auth"}) assert(helpers.start_kong({ database = strategy, plugins = "bundled,upstream-basic-auth", nginx_conf = "spec/fixtures/custom_nginx.template", })) end) lazy_teardown(function() helpers.stop_kong() end) local service local route local basic_auth_plugin local upstream_basic_auth_plugin local consumer local credential local upstream_credential before_each(function() proxy_client = helpers.proxy_client() admin_client = helpers.admin_client() if not service then service = admin_api.services:insert { path = "/request", } end if not route then route = admin_api.routes:insert { hosts = { "basic-auth.com" }, service = { id = service.id }, } end if not basic_auth_plugin then basic_auth_plugin = admin_api.plugins:insert { name = "basic-auth", route = { id = route.id }, } end if not upstream_basic_auth_plugin then upstream_basic_auth_plugin = admin_api.plugins:insert { name = "upstream-basic-auth", route = { id = route.id }, } end if not consumer then consumer = admin_api.consumers:insert { username = "bob", } end if not credential then credential = admin_api.basicauth_credentials:insert { username = "bob", password = "kong", consumer = { id = consumer.id }, } end if not upstream_credential then upstream_credential = assert(db.upstreambasicauth_credentials:insert { username = "king", password = "kong", consumer = { id = consumer.id }, }) -- NOTE: since 1) Kong caches negative responses -- and 2) direct DB manipulations from this unit test don't trigger cache invalidation, -- we have to explicitly invalidate cache helpers.wait_until(function() local cache_key = db.upstreambasicauth_credentials:cache_key(consumer.id) local res = assert(admin_client:send { method = "DELETE", path = "/cache/" .. cache_key }) res:read_body() return res.status == 204 end) end end) after_each(function() if admin_client and proxy_client then admin_client:close() proxy_client:close() end end) it("invalidates credentials when the Consumer is deleted", function() -- populate cache local res = assert(proxy_client:send { method = "GET", path = "/", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) local consumer_id = json.headers["x-consumer-id"] -- ensure cache is populated local cache_key = db.upstreambasicauth_credentials:cache_key(consumer_id) res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) assert.res_status(200, res) -- delete Consumer entity res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob" }) assert.res_status(204, res) consumer = nil credential = nil upstream_credential = nil -- ensure cache is invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) res:read_body() return res.status == 404 end) res = assert(proxy_client:send { method = "GET", path = "/", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth.com" } }) assert.res_status(403, res) end) it("invalidates credentials from cache when deleted", function() -- populate cache local res = assert(proxy_client:send { method = "GET", path = "/", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) local consumer_id = json.headers["x-consumer-id"] -- ensure cache is populated local cache_key = db.upstreambasicauth_credentials:cache_key(consumer_id) res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) local body = assert.res_status(200, res) local credential = cjson.decode(body) -- delete credential entity res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/upstream-basic-auth/" .. credential.id }) assert.res_status(204, res) upstream_credential = nil -- ensure cache is invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) res:read_body() return res.status == 404 end) res = assert(proxy_client:send { method = "GET", path = "/", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth.com" } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "no basic auth credentials available for consumer" }, json) end) it("invalidated credentials from cache when updated", function() -- populate cache local res = assert(proxy_client:send { method = "GET", path = "/", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) local consumer_id = json.headers["x-consumer-id"] -- ensure cache is populated local cache_key = db.upstreambasicauth_credentials:cache_key(consumer_id) res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) local body = assert.res_status(200, res) local credential = cjson.decode(body) -- delete credential entity res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/upstream-basic-auth/" .. credential.id, body = { username = "king", password = "kong-updated" }, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(200, res) upstream_credential = nil -- ensure cache is invalidated helpers.wait_until(function() local res = assert(admin_client:send { method = "GET", path = "/cache/" .. cache_key }) res:read_body() return res.status == 404 end) res = assert(proxy_client:send { method = "GET", path = "/", headers = { ["Authorization"] = "Basic Ym9iOmtvbmc=", ["Host"] = "basic-auth.com" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.is_string(json.headers["x-consumer-id"]) assert.equal("bob", json.headers["x-consumer-username"]) assert.equal("Basic a2luZzprb25nLXVwZGF0ZWQ=", json.headers["authorization"]) end) end) end
-- Heavily derived from `diffview.nvim`: -- https://github.com/sindrets/diffview.nvim/blob/main/lua/diffview/file-entry.lua local config = require "octo.config" local gh = require "octo.gh" local graphql = require "octo.gh.graphql" local signs = require "octo.ui.signs" local utils = require "octo.utils" local M = {} ---@type table M._null_buffer = {} ---@class GitStats ---@field additions integer ---@field deletions integer ---@field changes integer ---@class FileEntry ---@field path string ---@field previous_path string ---@field basename string ---@field extension string ---@field pull_request PullRequest ---@field status string ---@field patch string ---@field stats GitStats ---@field left_binary boolean|nil ---@field right_binary boolean|nil ---@field left_bufid integer ---@field right_bufid integer ---@field left_lines string[] ---@field right_lines string[] ---@field left_winid number ---@field right_winid number ---@field left_comment_ranges table ---@field right_comment_ranges table ---@field associated_bufs integer[] ---@field diffhunks string[] ---@field viewed_state string local FileEntry = {} FileEntry.__index = FileEntry FileEntry.winopts = { foldmethod = "diff", foldlevel = 0, } ---FileEntry constructor ---@param opt table ---@return FileEntry function FileEntry:new(opt) local pr = opt.pull_request local diffhunks, left_ranges, right_ranges if opt.patch then diffhunks, left_ranges, right_ranges = utils.process_patch(opt.patch) end local this = { path = opt.path, previous_path = opt.previous_path, patch = opt.patch, basename = utils.path_basename(opt.path), extension = utils.path_extension(opt.path), pull_request = pr, status = opt.status, stats = opt.stats, left_comment_ranges = left_ranges, right_comment_ranges = right_ranges, left_binary = opt.left_binary, right_binary = opt.right_binary, diffhunks = diffhunks, associated_bufs = {}, viewed_state = pr.files[opt.path], } if not this.status then this.status = " " end setmetatable(this, self) return this end ---FileEntry toggle_viewed function FileEntry:toggle_viewed() local query, next_state if self.viewed_state == "VIEWED" then query = graphql("unmark_file_as_viewed_mutation", self.path, self.pull_request.id) next_state = "UNVIEWED" elseif self.viewed_state == "UNVIEWED" then query = graphql("mark_file_as_viewed_mutation", self.path, self.pull_request.id) next_state = "VIEWED" elseif self.viewed_state == "DISMISSED" then query = graphql("mark_file_as_viewed_mutation", self.path, self.pull_request.id) next_state = "VIEWED" end gh.run { args = { "api", "graphql", "-f", string.format("query=%s", query) }, cb = function(output, stderr) if stderr and not utils.is_blank(stderr) then vim.api.nvim_err_writeln(stderr) elseif output then --local resp = vim.fn.json_decode(output) self.viewed_state = next_state local current_review = require("octo.reviews").get_current_review() if current_review then current_review.layout.file_panel:render() current_review.layout.file_panel:redraw() end end end, } end ---FileEntry finalizer function FileEntry:destroy() self:detach_buffers() for _, bn in ipairs(self.associated_bufs) do pcall(vim.api.nvim_buf_delete, bn, { force = true }) end end ---Get the window id for the alternative side of the provided buffer ---@param split string ---@return integer function FileEntry:get_alternative_win(split) if split:lower() == "left" then return self.right_winid elseif split:lower() == "right" then return self.left_winid end end ---Get the buffer id for the alternative side of the provided buffer ---@param split string ---@return integer function FileEntry:get_alternative_buf(split) if split:lower() == "left" then return self.right_bufid elseif split:lower() == "right" then return self.left_bufid end end ---Get the window id for the side of the provided buffer ---@param split string ---@return integer function FileEntry:get_win(split) if split:lower() == "left" then return self.left_winid elseif split:lower() == "right" then return self.right_winid end end ---Get the buffer id for the side of the provided buffer ---@param split string ---@return integer function FileEntry:get_buf(split) if split:lower() == "left" then return self.left_bufid elseif split:lower() == "right" then return self.right_bufid end end ---Fetch file content locally or from GitHub. function FileEntry:fetch() local right_path = self.path local left_path = self.path local current_review = require("octo.reviews").get_current_review() local right_sha = current_review.layout.right.commit local left_sha = current_review.layout.left.commit local right_abbrev = current_review.layout.right:abbrev() local left_abbrev = current_review.layout.left:abbrev() -- handle renamed files if self.status == "R" and self.previous_path then left_path = self.previous_path end -- fetch right version if self.pull_request.local_right then utils.get_file_at_commit(right_path, right_sha, function(lines) self.right_lines = lines end) else utils.get_file_contents(self.pull_request.repo, right_abbrev, right_path, function(lines) self.right_lines = lines end) end -- fetch left version if self.pull_request.local_left then utils.get_file_at_commit(left_path, left_sha, function(lines) self.left_lines = lines end) else utils.get_file_contents(self.pull_request.repo, left_abbrev, left_path, function(lines) self.left_lines = lines end) end -- wait until we have both versions return vim.wait(5000, function() return self.left_lines and self.right_lines end) end ---Load the buffers. ---@param left_winid integer ---@param right_winid integer function FileEntry:load_buffers(left_winid, right_winid) local empty_files = #self.left_lines == 0 and #self.right_lines == 0 local splits = { { winid = left_winid, bufid = self.left_bufid, lines = self.left_lines, pos = "left", binary = self.left_binary == true or empty_files, }, { winid = right_winid, bufid = self.right_bufid, lines = self.right_lines, pos = "right", binary = self.right_binary == true or empty_files, }, } -- configure diff buffers for _, split in ipairs(splits) do if not split.bufid or not vim.api.nvim_buf_is_loaded(split.bufid) then local use_local = false if split.pos == "right" and utils.in_pr_branch(self.pull_request.bufnr) then use_local = true end -- create buffer split.bufid = M._create_buffer { status = self.status, show_diff = self.patch ~= nil, path = self.path, split = split.pos, binary = split.binary, lines = split.lines, repo = self.pull_request.repo, use_local = use_local, } -- register new buffer table.insert(self.associated_bufs, split.bufid) self[split.pos .. "_bufid"] = split.bufid self[split.pos .. "_winid"] = split.winid end M._configure_buffer(split.bufid) vim.api.nvim_win_set_buf(split.winid, split.bufid) end -- show thread signs and virtual text self:place_signs() -- configure windows M._configure_windows(left_winid, right_winid) -- activate diff for _, split in ipairs(splits) do vim.api.nvim_buf_call(split.bufid, function() vim.cmd [[filetype detect]] vim.cmd [[doau BufEnter]] vim.cmd [[diffthis]] -- Scroll to trigger the scrollbind and sync the windows. This works more -- consistently than calling `:syncbind`. vim.cmd [[exec "normal! \<c-y>"]] end) end end function FileEntry:attach_buffers() if self.left_bufid then M._configure_buffer(self.left_bufid) end if self.right_bufid then M._configure_buffer(self.right_bufid) end end function FileEntry:detach_buffers() if self.left_bufid then M._detach_buffer(self.left_bufid) end if self.right_bufid then M._detach_buffer(self.right_bufid) end end ---Compare against another FileEntry. ---@param other FileEntry ---@return boolean function FileEntry:compare(other) if self.stats and not other.stats then return false end if not self.stats and other.stats then return false end if self.stats and other.stats then if self.stats.additions ~= other.stats.additions or self.stats.deletions ~= other.stats.deletions then return false end end return (self.path == other.path and self.status == other.status) end ---Update thread signs in diff buffers. function FileEntry:place_signs() local current_review = require("octo.reviews").get_current_review() local review_level = current_review:get_level() local splits = { { bufnr = self.left_bufid, comment_ranges = self.left_comment_ranges, commit = current_review.layout.left:abbrev(), }, { bufnr = self.right_bufid, comment_ranges = self.right_comment_ranges, commit = current_review.layout.right:abbrev(), }, } for _, split in ipairs(splits) do signs.unplace(split.bufnr) -- place comment range signs if split.comment_ranges then for _, range in ipairs(split.comment_ranges) do for line = range[1], range[2] do signs.place("octo_comment_range", split.bufnr, line - 1) end end end -- place thread comments signs and virtual text local threads = vim.tbl_values(current_review.threads) for _, thread in ipairs(threads) do local line = thread.line if review_level == "COMMIT" then line = thread.originalLine end local sign = "octo_thread" if thread.isOutdated then sign = sign .. "_outdated" elseif thread.isResolved then sign = sign .. "_resolved" end for _, comment in ipairs(thread.comments.nodes) do if comment.state == "PENDING" then sign = sign .. "_pending" end if review_level == "PR" and utils.is_thread_placed_in_buffer(thread, split.bufnr) or review_level == "COMMIT" and split.commit == comment.originalCommit.abbreviatedOid then -- sign signs.place(sign, split.bufnr, line - 1) -- virtual text local last_date = comment.lastEditedAt ~= vim.NIL and comment.lastEditedAt or comment.createdAt local vt_msg = string.format(" %d comments (%s)", #thread.comments.nodes, utils.format_date(last_date)) vim.api.nvim_buf_set_virtual_text(split.bufnr, -1, line - 1, { { vt_msg, "Comment" } }, {}) end end end end end function M._create_buffer(opts) local current_review = require("octo.reviews").get_current_review() local bufnr --if opts.use_local then -- TODO: should we use the file from the file system -- Pros: LSP powered -- Cons: we need to change to the commit branch -- For now, lets just load the contents from git object (`git show commit:path`) --bufnr = vim.fn.bufadd(opts.path) --else bufnr = vim.api.nvim_create_buf(false, false) local bufname = string.format( "octo://%s/review/%s/file/%s/%s", opts.repo, current_review.id, string.upper(opts.split), opts.path ) vim.api.nvim_buf_set_name(bufnr, bufname) if opts.binary then vim.api.nvim_buf_set_option(bufnr, "modifiable", true) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { "Binary file" }) elseif opts.status == "R" and not opts.show_diff then vim.api.nvim_buf_set_option(bufnr, "modifiable", true) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, { "Renamed" }) elseif opts.lines then vim.api.nvim_buf_set_option(bufnr, "modifiable", true) vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, opts.lines) end --end vim.api.nvim_buf_set_option(bufnr, "modified", false) vim.api.nvim_buf_set_option(bufnr, "modifiable", false) vim.api.nvim_buf_set_var(bufnr, "octo_diff_props", { path = opts.path, split = string.upper(opts.split), }) return bufnr end function M.load_null_buffers(left_winid, right_winid) M.load_null_buffer(left_winid) M.load_null_buffer(right_winid) end function M.load_null_buffer(winid) local bn = M._get_null_buffer() if vim.api.nvim_win_is_valid(winid) then vim.api.nvim_win_set_buf(winid, bn) end M._configure_buffer(bn) end function M._get_null_buffer() local msg = "Loading ..." local bn = M._null_buffer[msg] if not bn or vim.api.nvim_buf_is_loaded(bn) then local nbn = vim.api.nvim_create_buf(false, false) vim.api.nvim_buf_set_lines(nbn, 0, -1, false, { msg }) local bufname = utils.path_join { "octo", "null" } vim.api.nvim_buf_set_option(nbn, "modified", false) vim.api.nvim_buf_set_option(nbn, "modifiable", false) local ok = pcall(vim.api.nvim_buf_set_name, nbn, bufname) if not ok then utils.wipe_named_buffer(bufname) vim.api.nvim_buf_set_name(nbn, bufname) end M._null_buffer[msg] = nbn end return M._null_buffer[msg] end function M._configure_windows(left_winid, right_winid) for _, id in ipairs { left_winid, right_winid } do for k, v in pairs(FileEntry.winopts) do vim.api.nvim_win_set_option(id, k, v) end end end function M._configure_buffer(bufid) local conf = config.get_config() for action, value in pairs(conf.mappings.review_diff) do local mappings = require "octo.mappings" local mapping_opts = { silent = true, noremap = true, buffer = bufid, desc = value.desc } vim.keymap.set("n", value.lhs, mappings[action], mapping_opts) end -- TODO: use vim.keymap.set vim.cmd(string.format("nnoremap %s :OctoAddReviewComment<CR>", conf.mappings.review_thread.add_comment)) vim.cmd(string.format("vnoremap %s :OctoAddReviewComment<CR>", conf.mappings.review_thread.add_comment)) vim.cmd(string.format("nnoremap %s :OctoAddReviewSuggestion<CR>", conf.mappings.review_thread.add_suggestion)) vim.cmd(string.format("vnoremap %s :OctoAddReviewSuggestion<CR>", conf.mappings.review_thread.add_suggestion)) end function M._detach_buffer(bufid) local conf = config.get_config() for _, lhs in pairs(conf.mappings.review_diff) do pcall(vim.keymap.del, "n", lhs, { buffer = bufid }) end end M.FileEntry = FileEntry return M
require("bufferline").setup({ options = { show_close_icon = true, diagnostics = "nvim_lsp", always_show_bufferline = true, diagnostics_indicator = function(_, _, diagnostics_dict) local s = " " for e, n in pairs(diagnostics_dict) do local sym = e == "error" and " " or (e == "warning" and " " or "") s = s .. sym .. n end return s end, }, })
isStarting = true default = "Assets/New UI/checkbox_a_default.png" checked = "Assets/New UI/checkbox_a_checked_1.png" image1 = default image2 = default image3 = default -- Called each loop iteration function UpdateUI(dt) if (gameObject.active == true) then if (isStarting == true) then image2 = checked pos1 = Find("30 Button") pos2 = Find("60 Button") pos3 = Find("120 Button") sb1 = Find("FPS SB 1") sb2 = Find("FPS SB 2") sb3 = Find("FPS SB 3") pos1:GetButton():SetIdleTexture(image1) pos2:GetButton():SetIdleTexture(image2) pos3:GetButton():SetIdleTexture(image3) isStarting = false end if (sb1:GetButton():IsPressed() == true) then image1 = checked image2 = default image3 = default SetFPS(30) pos1:GetButton():SetIdleTexture(image1) pos2:GetButton():SetIdleTexture(image2) pos3:GetButton():SetIdleTexture(image3) elseif (sb2:GetButton():IsPressed() == true) then image1 = default image2 = checked image3 = default SetFPS(60) pos1:GetButton():SetIdleTexture(image1) pos2:GetButton():SetIdleTexture(image2) pos3:GetButton():SetIdleTexture(image3) elseif (sb3:GetButton():IsPressed() == true) then image1 = default image2 = default image3 = checked SetFPS(120) pos1:GetButton():SetIdleTexture(image1) pos2:GetButton():SetIdleTexture(image2) pos3:GetButton():SetIdleTexture(image3) end end end print("UI_FPS.lua compiled succesfully")
--------------------------------------------------------------------------- -- Find connected regions in a Mesh --------------------------------------------------------------------------- -- Load a point cloud local pointCloud = PointCloud.load("resources/Box.ply") -- Reconstruct a mesh local mesh = Mesh.createFromPointCloud(pointCloud) print("Complete mesh: " .. mesh:toString()) -- Separate meshes local components = Mesh.findConnected(mesh) print("Number of separate meshes found:" .. #components) -- View result decoration1 = View.MeshDecoration.create() decoration1:setSurfaceColor(200, 100, 30) decoration2 = View.MeshDecoration.create() decoration2:setSurfaceColor(100, 200, 30) decoration3 = View.MeshDecoration.create() decoration3:setSurfaceColor(30, 100, 200) local viewer = View.create() viewer:clear() viewer:addMesh(components[1], decoration1) viewer:addMesh(components[2], decoration2) viewer:addMesh(components[3], decoration3) viewer:present()
local screenWidth = 800 local screenHeight = 450 rl.SetConfigFlags(rl.FLAG_VSYNC_HINT) rl.InitWindow(screenWidth, screenHeight, "raylua [models] example - geometric shapes") local camera = rl.new("Camera", { position = rl.new("Vector3", 0, 10, 10), target = rl.new("Vector3", 0, 0, 0), up = rl.new("Vector3", 0, 1, 0), fovy = 45, type = rl.CAMERA_PERSPECTIVE }) while not rl.WindowShouldClose() do rl.BeginDrawing() rl.ClearBackground(rl.RAYWHITE) rl.BeginMode3D(camera) -- Ideally, you should cache Vector3 structures to avoid reallocating them -- over and over. For readability here, they are inlined to the code. rl.DrawCube(rl.new("Vector3", -4, 0, 2), 2, 5, 2, rl.RED) rl.DrawCubeWires(rl.new("Vector3", -4, 0, 2), 2, 5, 2, rl.GOLD) rl.DrawCubeWires(rl.new("Vector3", -4, 0, -2), 3, 6, 2, rl.MAROON) rl.DrawSphere(rl.new("Vector3", 1, 0, -2), 1, rl.GREEN) rl.DrawSphereWires(rl.new("Vector3", 1, 0, 2), 2, 16, 16, rl.LIME) rl.DrawCylinder(rl.new("Vector3", 4, 0, -2), 1, 2, 3, 4, rl.SKYBLUE) rl.DrawCylinderWires(rl.new("Vector3", 4, 0, -2), 1, 2, 3, 4, rl.DARKBLUE) rl.DrawCylinderWires(rl.new("Vector3", 4.5, -1, 2), 1, 1, 2, 6, rl.BROWN) rl.DrawCylinder(rl.new("Vector3", 1, 0, -4), 0, 1.5, 3, 8, rl.GOLD) rl.DrawCylinderWires(rl.new("Vector3", 1, 0, -4), 0, 1.5, 3, 8, rl.PINK) rl.DrawGrid(10, 1) rl.EndMode3D() rl.DrawFPS(10, 10) rl.EndDrawing() end rl.CloseWindow()
return {'afwaaien','afwaarderen','afwaardering','afwaarts','afwachten','afwachting','afwaggelen','afwandelen','afwas','afwasautomaat','afwasbaar','afwasbak','afwasborstel','afwaskom','afwaskwast','afwasmachine','afwasmiddel','afwassen','afwasser','afwassing','afwaswater','afwateren','afwatering','afwateringsgaatje','afwateringskanaal','afwateringsput','afwateringsputten','afwateringssysteem','afweegfactor','afweer','afweerapparaat','afweerbaar','afweerder','afweergeschut','afweerkanon','afweermechanisme','afweermiddel','afweerraket','afweerreactie','afweerstof','afweersysteem','afweervuur','afwegen','afweging','afwegingsproces','afweiden','afweken','afweking','afwenden','afwending','afwennen','afwenning','afwentelen','afwenteling','afweren','afwering','afwerken','afwerker','afwerkfase','afwerking','afwerkingen','afwerklaag','afwerkplaats','afwerkplamuur','afwerkplek','afwerkster','afwerkstroken','afwerkstrook','afwerpen','afwerping','afweten','afwezen','afwezend','afwezende','afwezendheid','afwezig','afwezige','afwezigheid','afwijken','afwijking','afwijkingsmogelijkheid','afwijzen','afwijzend','afwijzing','afwijzingsbeslissing','afwijzingsbrief','afwijzingsgesprek','afwikkelen','afwikkeling','afwikkelingskosten','afwimpelen','afwimpeling','afwinden','afwinding','afwinnen','afwippen','afwisselen','afwisselend','afwisseling','afwissen','afwonen','afwrijven','afwringen','afwasteil','afweerhouding','afwezigheidslijst','afwerkvloer','afwijzingsgrond','afwikkelingsvergoeding','afweerstelsel','afwegingskader','afwerkingskwaliteit','afwerkingslaag','afwerkingsniveau','afwerkingsfase','afwezigheidstoezicht','afwashulp','afwijkingsbevoegdheid','afwikkelingsdatum','afwaai','afwaaide','afwaaiden','afwaait','afwaartse','afwacht','afwachtend','afwachtende','afwachtte','afwachtten','afwandel','afwandelde','afwandelden','afwandelt','afwasautomaten','afwasbakken','afwasbare','afwaskwasten','afwasmachines','afwasmiddelen','afwassingen','afwast','afwaste','afwasten','afwater','afwaterde','afwaterden','afwaterend','afwaterende','afwateringen','afwateringsgaatjes','afwateringskanalen','afwatert','afweeg','afweegt','afweek','afweekt','afweerde','afweerden','afweerkanonnen','afweermechanismen','afweermiddelen','afweerstoffen','afweert','afwees','afwegend','afwegingen','afweidt','afwen','afwend','afwendde','afwendden','afwende','afwendingen','afwendt','afwent','afwentel','afwentelde','afwentelden','afwentelt','afwerend','afwerende','afwerk','afwerkers','afwerklagen','afwerksters','afwerkt','afwerkte','afwerkten','afwerp','afwerpt','afwezigen','afwierp','afwierpen','afwies','afwijk','afwijkend','afwijkende','afwijkingen','afwijkt','afwijs','afwijst','afwijzende','afwijzingen','afwijzingsgesprekken','afwikkel','afwikkelde','afwikkelden','afwikkelt','afwimpel','afwimpelde','afwimpelden','afwimpelt','afwindt','afwint','afwipt','afwis','afwissel','afwisselde','afwisselden','afwisselende','afwisselender','afwisselendere','afwisselendst','afwisselendste','afwisselingen','afwisselt','afwist','afwiste','afwisten','afwoei','afwogen','afwon','afwond','afwoog','afwoon','afwoonde','afwoonden','afwoont','afwreef','afwrijf','afwrijft','afwrijvingen','afwaarderingen','afwassers','afweerraketten','afweerreacties','afwegende','afwerkplaatsen','afwerkplekken','afwezigheden','afwijzingsbrieven','afwikkelingen','afwasteiltje','afwasborstels','afwasborsteltje','afwasteilen','afwezigheidslijsten','afweersystemen','afwasbakje','afwegingskaders','afwateringssystemen','afwijzingsgronden','afwerkingsniveaus','afwegingsprocessen','afwerkvloeren'}
local comm = require "comm" local ldap = require "ldap" local nmap = require "nmap" local shortport = require "shortport" local stdnse = require "stdnse" local string = require "string" description = [[ Retrieves the LDAP root DSA-specific Entry (DSE) ]] --- -- -- @usage -- nmap -p 389 --script ldap-rootdse <host> -- -- @output -- PORT STATE SERVICE -- 389/tcp open ldap -- | ldap-rootdse: -- | currentTime: 20100112092616.0Z -- | subschemaSubentry: CN=Aggregate,CN=Schema,CN=Configuration,DC=cqure,DC=net -- | dsServiceName: CN=NTDS Settings,CN=LDAPTEST001,CN=Servers,CN=Default-First-Site,CN=Sites,CN=Configuration,DC=cqure,DC=net -- | namingContexts: DC=cqure,DC=net -- | namingContexts: CN=Configuration,DC=cqure,DC=net -- | namingContexts: CN=Schema,CN=Configuration,DC=cqure,DC=net -- | namingContexts: DC=DomainDnsZones,DC=cqure,DC=net -- | namingContexts: DC=ForestDnsZones,DC=cqure,DC=net -- | namingContexts: DC=TAPI3Directory,DC=cqure,DC=net -- | defaultNamingContext: DC=cqure,DC=net -- | schemaNamingContext: CN=Schema,CN=Configuration,DC=cqure,DC=net -- | configurationNamingContext: CN=Configuration,DC=cqure,DC=net -- | rootDomainNamingContext: DC=cqure,DC=net -- | supportedControl: 1.2.840.113556.1.4.319 -- | . -- | . -- | supportedControl: 1.2.840.113556.1.4.1948 -- | supportedLDAPVersion: 3 -- | supportedLDAPVersion: 2 -- | supportedLDAPPolicies: MaxPoolThreads -- | supportedLDAPPolicies: MaxDatagramRecv -- | supportedLDAPPolicies: MaxReceiveBuffer -- | supportedLDAPPolicies: InitRecvTimeout -- | supportedLDAPPolicies: MaxConnections -- | supportedLDAPPolicies: MaxConnIdleTime -- | supportedLDAPPolicies: MaxPageSize -- | supportedLDAPPolicies: MaxQueryDuration -- | supportedLDAPPolicies: MaxTempTableSize -- | supportedLDAPPolicies: MaxResultSetSize -- | supportedLDAPPolicies: MaxNotificationPerConn -- | supportedLDAPPolicies: MaxValRange -- | highestCommittedUSN: 126991 -- | supportedSASLMechanisms: GSSAPI -- | supportedSASLMechanisms: GSS-SPNEGO -- | supportedSASLMechanisms: EXTERNAL -- | supportedSASLMechanisms: DIGEST-MD5 -- | dnsHostName: EDUSRV011.cqure.local -- | ldapServiceName: cqure.net:edusrv011$@CQURE.NET -- | serverName: CN=EDUSRV011,CN=Servers,CN=Default-First-Site,CN=Sites,CN=Configuration,DC=cqure,DC=net -- | supportedCapabilities: 1.2.840.113556.1.4.800 -- | supportedCapabilities: 1.2.840.113556.1.4.1670 -- | supportedCapabilities: 1.2.840.113556.1.4.1791 -- | isSynchronized: TRUE -- | isGlobalCatalogReady: TRUE -- | domainFunctionality: 0 -- | forestFunctionality: 0 -- |_ domainControllerFunctionality: 2 -- -- -- The root DSE object may contain a number of different attributes as described in RFC 2251 section 3.4: -- * namingContexts: naming contexts held in the server -- * subschemaSubentry: subschema entries (or subentries) known by this server -- * altServer: alternative servers in case this one is later unavailable. -- * supportedExtension: list of supported extended operations. -- * supportedControl: list of supported controls. -- * supportedSASLMechanisms: list of supported SASL security features. -- * supportedLDAPVersion: LDAP versions implemented by the server. -- -- The above example, which contains a lot more information is from Windows 2003 accessible without authentication. -- The same request against OpenLDAP will result in significantly less information. -- -- The ldap-search script queries the root DSE for the namingContexts and/or defaultNamingContexts, which it sets as base -- if no base object was specified -- -- Credit goes out to Martin Swende who provided me with the initial code that got me started writing this. -- -- Version 0.3 -- Created 01/12/2010 - v0.1 - created by Patrik Karlsson <patrik@cqure.net> -- Revised 01/20/2010 - v0.2 - added SSL support -- Revised 04/09/2016 - v0.3 - added support for LDAP over UDP - Tom Sellers author = "Patrik Karlsson" copyright = "Patrik Karlsson" license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"discovery", "safe"} dependencies = {"ldap-brute"} -- Map domainControllerFunctionality to OS - https://msdn.microsoft.com/en-us/library/cc223272.aspx -- Tested to be valid even when Active Directory functional level is lower than target ADC's OS version DC_FUNCT_ID = {} DC_FUNCT_ID["0"] = "Windows 2000" DC_FUNCT_ID["2"] = "Windows 2003" DC_FUNCT_ID["3"] = "Windows 2008" DC_FUNCT_ID["4"] = "Windows 2008 R2" DC_FUNCT_ID["5"] = "Windows 2012" DC_FUNCT_ID["6"] = "Windows 2012 R2" portrule = shortport.port_or_service({389,636}, {"ldap","ldapssl"},{'tcp','udp'}) function action(host,port) local status, searchResEntries, req, result, opt if port.protocol == 'tcp' then local socket = nmap.new_socket() -- In order to discover what protocol to use (SSL/TCP) we need to send a few bytes to the server -- An anonymous bind should do it local ldap_anonymous_bind = "\x30\x0c\x02\x01\x01\x60\x07\x02\x01\x03\x04\x00\x80\x00" local _ socket, _, opt = comm.tryssl( host, port, ldap_anonymous_bind, nil ) if not socket then return end -- We close and re-open the socket so that the anonymous bind does not distract us socket:close() status = socket:connect(host, port, opt) socket:set_timeout(10000) -- Searching for an empty argument list against LDAP on W2K3 returns all attributes -- This is not the case for OpenLDAP, so we do a search for an empty attribute list -- Then we compare the results against some known and expected returned attributes req = { baseObject = "", scope = ldap.SCOPE.base, derefPolicy = ldap.DEREFPOLICY.default } status, searchResEntries = ldap.searchRequest( socket, req ) if not status then socket:close() return stdnse.format_output(false, searchResEntries) end -- Check if we were served all the results or not? if not ldap.extractAttribute( searchResEntries, "namingContexts" ) and not ldap.extractAttribute( searchResEntries, "supportedLDAPVersion" ) then -- The namingContexts was not there, try to query all attributes instead -- Attributes extracted from Windows 2003 and complemented from RFC local attribs = {"_domainControllerFunctionality","configurationNamingContext","currentTime","defaultNamingContext", "dnsHostName","domainFunctionality","dsServiceName","forestFunctionality","highestCommittedUSN", "isGlobalCatalogReady","isSynchronized","ldap-get-baseobject","ldapServiceName","namingContexts", "rootDomainNamingContext","schemaNamingContext","serverName","subschemaSubentry", "supportedCapabilities","supportedControl","supportedLDAPPolicies","supportedLDAPVersion", "supportedSASLMechanisms", "altServer", "supportedExtension"} req = { baseObject = "", scope = ldap.SCOPE.base, derefPolicy = ldap.DEREFPOLICY.default, attributes = attribs } status, searchResEntries = ldap.searchRequest( socket, req ) end socket:close() else -- Port protocol is UDP, indicating that this is an Active Directory Controller LDAP service req = { baseObject = "", scope = ldap.SCOPE.base, derefPolicy = ldap.DEREFPOLICY.default} status, searchResEntries = ldap.udpSearchRequest( host, port, req ) end if not status or not searchResEntries then return stdnse.format_output(false, searchResEntries) end result = ldap.searchResultToTable( searchResEntries ) -- if taken a way and ldap returns a single result, it ain't shown.... result.name = "LDAP Results" local scriptResult = stdnse.format_output(true, result ) -- Start extracting target information -- The following works on Windows AD LDAP as well as VMware's LDAP, VMware uses lower case cn vs AD ucase CN local serverName = scriptResult:match("serverName: [cC][nN]=([^,]+),[cC][nN]=Servers,[cC][nN]=") if serverName then port.version.hostname = serverName end -- Check to see if this is Active Directory vs some other product or ADAM -- https://msdn.microsoft.com/en-us/library/cc223359.aspx if string.match(scriptResult,"1.2.840.113556.1.4.800") then port.version.product = 'Microsoft Windows Active Directory LDAP' port.version.name_confidence = 10 -- Determine Windows version if not port.version.ostype or port.version.ostype == 'Windows' then local DC_Func = string.match(scriptResult,"domainControllerFunctionality: (%d)") if DC_FUNCT_ID[DC_Func] then port.version.ostype = DC_FUNCT_ID[DC_Func] else port.version.ostype = 'Windows' stdnse.debug(1,"Unmatched OS lookup for domainControllerFunctionality: %d", DC_Func) end end local siteName = string.match(scriptResult,"serverName: CN=[^,]+,CN=Servers,CN=([^,]+),CN=Sites,") local domainName = string.match(scriptResult,"rootDomainNamingContext: ([^\n]*)") domainName = string.gsub(domainName,",DC=",".") domainName = string.gsub(domainName,"DC=","") if domainName and siteName then port.version.extrainfo = string.format("Domain: %s, Site: %s", domainName, siteName) end end -- Set port information port.version.name = "ldap" nmap.set_port_version(host, port, "hardmatched") nmap.set_port_state(host, port, "open") return scriptResult end
local IItemRangedWeapon = require("mod.elona.api.aspect.IItemRangedWeapon") local ItemRangedWeaponAspect = class.class("ItemRangedWeaponAspect", IItemRangedWeapon) function ItemRangedWeaponAspect:init(item, params) self.dice_x = params.dice_x or 0 self.dice_y = params.dice_y or 0 self.pierce_rate = params.pierce_rate or 0 self.skill = params.skill or "elona.throwing" self.effective_range = params.effective_range or {} end return ItemRangedWeaponAspect
AddCSLuaFile('cl_init.lua') AddCSLuaFile('shared.lua') include('shared.lua') ENT.health = 200 function ENT:Initialize() self:machineInitialize('models/props_wasteland/laundry_washer001a.mdl') end
-------------------------------- --// Icicle. -------------------------------- local addon = {} local addonName = "Icicle" _G[addonName] = addon -------------------------------- -------------------------------- local IcicleOpts local G = _G Icicle.fonts = {} local LSM = LibStub("LibSharedMedia-3.0") LSM:Register("font", "Hooge0655", [[Interface\AddOns\Icicle\Hooge0655.ttf]]) local function updateMedia(event, mediatype, key) if mediatype == "font" then Icicle.fonts[key] = SML:Fetch(mediaType, key) end end -------------------------------- --// Defaults. -------------------------------- local Settings = { font = "Interface\\AddOns\\Icicle\\Hooge0655.ttf", fontX = 1, fontY = -7, fontName = "Hooge0655", fontSize = 10, iconsize = 22, xoff = -60, yoff = 25, borderCol = {1, 1, 1}, interCol = {1, .35, 0}, trinketCol = {.5, 1, 0}, } local cooldowns = { ["Misc"] = { [59752] = 120, --Every Man for Himself [42292] = 120, --PvP Trinket }, ["Deathknight"] = { [108200] = 60, --"Remorseless Winter", [108194] = 30, --"Asphyxiate", [108199] = 60, --"Gorefiend's Grasp", [115989] = 90, --"Unholy Blight", [49039] = 120, --"Lichborne", [47476] = 60, --"Strangulate", [48707] = 45, --"Anti-Magic Shell", [49576] = 25, --"Death Grip", [47528] = 15, --"Mind Freeze", [49222] = 60, --"Bone Shield", [51271] = 60, --"Pillar of Frost", [49206] = 180, --"Summon Gargoyle", [48792] = 180, --"Icebound Fortitude", }, ["Mage"] = { [108839] = 45, --"Ice Floes", [102051] = 20, --"Frostjaw", [2139] = 24, --"Counterspell", [44572] = 30, --"Deep Freeze", [11958] = 180, --"Cold Snap", [45438] = 300, --"Ice Block", [12042] = 90, --"Arcane Power", [122] = 25, --"Frost Nova", [11426] = 25, --"Ice Barrier", [12472] = 180, --"Icy Veins", [113724] = 45, --"Ring of Frost", [12043] = 90, --"Presence of Mind", [11129] = 45, --"Combustion", [31661] = 20, --"Dragon's Breath", }, ["Priest"] = { [108921] = 45, --"Psyfiend", [108920] = 30, --"Void Tendrils", [89485] = 45, --"Inner Focus", [64044] = 45, --"Psychic Horror", [8122] = 30, --"Psychic Scream", [15487] = 45, --"Silence", [47585] = 120, --"Dispersion", [33206] = 180, --"Pain Suppression", [10060] = 120, --"Power Infusion", [88625] = 30, --"Holy Word: Chastise", [73325] = 90, --"Leap of Faith", }, ["Druid"] = { [124974] = 90, --"Nature's Vigil", [102359] = 30, --"Mass Entanglement", [99] = 30, --"Disorienting Roar", [102280] = 30, --"Displacer Beast", [5211] = 50, --"Mighty Bash", [22812] = 60, --"Barkskin", [132158] = 60, --"Nature's Swiftness", [61336] = 180, --"Survival Instincts", [50334] = 180, --"Berserk", [132469] = 30, --"Typhoon", [78675] = 60, --"Solar Beam", [5211] = 50, --"Bash", [80964] = 15, --"Skull Bash", [80965] = 15, --"Skull Bash", [29166] = 180, --"Innervate", }, ["Paladin"] = { [115750] = 120, --"Blinding Light", [85499] = 45, --"Speed of Light", [105593] = 30, --"Fist of Justice", [1044] = 25, --"Hand of Freedom", [31884] = 180, --"Avenging Wrath", [853] = 60, --"Hammer of Justice", [31935] = 15, --"Avenger's Shield", [96231] = 15, --"Rebuke", [633] = 600, --"Lay on Hands", [1022] = 300, --"Hand of Protection", [642] = 300, --"Divine Shield", [6940] = 120, --"Hand of Sacrifice", [31821] = 180, --"Devotion Aura", [20066] = 15, --"Repentance", }, ["Rogue"] = { [121471] = 180, --"Shadow Blades", [2094] = 120, --"Blind", [1766] = 15, --"Kick", [14185] = 300, --"Preparation", [31224] = 60, --"Cloak of Shadows", [1856] = 120, --"Vanish", [36554] = 20, --"Shadowstep", [76577] = 180, --"Smoke Bomb", [51690] = 120, --"Killing Spree", [51713] = 60, --"Shadow Dance", [79140] = 120, --"Vendetta", }, ["Monk"] = { [123904] = 180, --"Invoke Xuen, the White Tiger", [101643] = 45, --"Transcendence", [119996] = 25, --"Transcendence: Transfer", [115176] = 180, --"Zen Meditation", [115310] = 180, --"Revival", [122278] = 90, --"Dampen Harm", [122783] = 90, --"Diffuse Magic", [119381] = 45, --"Leg Sweep", [116844] = 45, --"Ring of Peace", [116849] = 120, --"Life Cocoon", [115078] = 15, --"Paralysis", [116705] = 15, --"Spear Hand Strike", [137562] = 120, --"Nimble Brew", [122470] = 90, --"Touch of Karma", [116841] = 30, --"Tiger's Lust", [113656] = 25, --"Fists of Fury", [116705] = 15, --"Spear Hand Strike", }, ["Warlock"] = { [111397] = 30, --"Blood Horror", [110913] = 180, --"Dark Bargain", [108482] = 60, --"Unbound Will", [108359] = 120, --"Dark Regeneration", [108416] = 60, --"Sacrificial Pact", [30283] = 30, --"Shadowfury", [6789] = 45, --"Mortal Coil", [5484] = 40, --"Howl of Terror", [48020] = 25, --"Demonic Circle: Teleport", [104773] = 180, --Unending Resolve }, ["Hunter"] = { [120697] = 90, --"Lynx Rush", [120679] = 30, --"Dire Beast", [109248] = 45, --"Binding Shot", [1499] = 30, --"Freezing Trap", [19386] = 45, --"Wyvern Sting", [3045] = 180, --"Rapid Fire", [53271] = 45, --"Master's Call", [19263] = 120, --"Deterrence", --[19503] = 30, --"Scatter Shot", --[34490] = 24, --"Silencing Shot", [147362] = 24, --"Counter Shot", [19574] = 60, --"Bestial Wrath", }, ["Shaman"] = { [108269] = 45, --"Capacitor Totem", [108270] = 60, --"Stone Bulwark Totem", [108280] = 180, --"Healing Tide Totem", [98008] = 180, --"Spirit Link Totem", [8177] = 25, --"Grounding Totem", [57994] = 12, --"Wind Shear", [51533] = 120, --"Feral Spirit", [16190] = 180, --"Mana Tide Totem", [30823] = 60, --"Shamanistic Rage", [51490] = 45, --"Thunderstorm", [2484] = 30, --"Earthbind Totem", [8143] = 60, --"Tremor Totem", [51514] = 45, --"Hex", [79206] = 120, --"Spiritwalker's Grace", [16166] = 90, --"Elemental Mastery", }, ["Warrior"] = { [107574] = 180, --"Avatar", [12292] = 60, --"Bloodbath", [6552] = 15, --"Pummel", [102060] = 40, --"Disrupting Shot", [23920] = 25, --"Spell Reflection", [5246] = 90, --"Intimidating Shout", [871] = 180, --"Shield Wall", [118038] = 120, --"Die by the Sword", [1719] = 180, --"Recklessness", [64382] = 300, --"Shattering Throw", [12975] = 180, --"Last Stand", [46924] = 60, --"Bladestorm", [46968] = 40, --"Shockwave", }, ["Hunter Pet"] = { [50479] = 40, --Nether Shock [50245] = 40, --Pin [26090] = 30, --Pummel [50318] = 60, --Serenity Dust [4167] = 40, --Web }, } -------------------------------- --// Local functions. -------------------------------- local function orderednext(t, n) local key = t[t.__next] if not key then return end t.__next = t.__next + 1 return key, t.__source[key] end local function orderedpairs(t, f) local keys, kn = {__source = t, __next = 1}, 1 for k in pairs(t) do keys[kn], kn = k, kn + 1 end table.sort(keys, f) return orderednext, keys end --// Create tooltip local function AddTooltip(Parent, tooltipText) Parent:SetScript('OnEnter', function(self) if ( self.OnEnter ) then self:OnEnter() else GameTooltip:SetOwner(self, 'ANCHOR_RIGHT') GameTooltip:SetText(tooltipText, nil, nil, nil, nil, true) GameTooltip:Show() end end) Parent:SetScript('OnLeave', function(self) if self.OnLeave then self:OnLeave() else GameTooltip:Hide() end end) end --// Create options frame. local OptionsGen = CreateFrame("Frame", nil, InterfaceOptionsFrame) OptionsGen.name = addonName --OptionsGen.okay = function (self) refreshCooldowns() end OptionsGen:Hide() local function createLabel(frame, name) local label = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlight") label:SetText(name) return label end local function createSlider(name, x, y, min, max, step) local sliderOpt = CreateFrame("Slider", "Icicle" .. name, OptionsGen, "OptionsSliderTemplate") sliderOpt:SetWidth(x) sliderOpt:SetHeight(y) sliderOpt:SetMinMaxValues(min, max) sliderOpt:SetValueStep(step) G[sliderOpt:GetName() .. "Low"]:SetText('') G[sliderOpt:GetName() .. "High"]:SetText('') G[sliderOpt:GetName() .. 'Text']:SetText(name) return sliderOpt end local function createCheck(frame, key, wth, hgt, displayname, tooltipText) local chkOpt = CreateFrame("CheckButton", "Icicle" .. key, frame, "OptionsCheckButtonTemplate") chkOpt:SetWidth(wth) chkOpt:SetHeight(hgt) getglobal(chkOpt:GetName() .. 'Text'):SetText(displayname); if ( tooltipText ) then AddTooltip(chkOpt, tooltipText) end return chkOpt end local function createIcon(key, size) local icon = CreateFrame("frame", nil, nil) icon:SetHeight(size) icon:SetWidth(size) icon.background = icon:CreateTexture(nil, "BORDER") icon.background:SetAllPoints(icon) icon.background:SetTexture(1, 1, 1) icon.texture = icon:CreateTexture(nil, "ARTWORK") icon.texture:SetHeight(size - 2) icon.texture:SetWidth(size - 2) icon.texture:SetTexture(select(3, GetSpellInfo(key))) icon.texture:SetPoint("CENTER", icon) icon.cooldown = icon:CreateFontString(nil, "OVERLAY") icon.cooldown:SetPoint("CENTER", icon, 0, -6) icon.cooldown:SetHeight(size + 4) icon.cooldown:SetWidth(size + 4) icon.cooldown:SetFont(Icicle.Settings.font , Icicle.Settings.fontSize, "OUTLINE") icon.cooldown:SetTextColor(0.7, 1, 0) return icon end local function fontInit(fontOpt) local function dropClick(info) UIDropDownMenu_SetSelectedValue(fontOpt, info.value) for key, val in ipairs(LSM:List("font")) do if (LSM:Fetch("font", val) == info.value) then UIDropDownMenu_SetText(fontOpt, val) IcicleVars.Settings.fontName = val end end IcicleVars.Settings.font = info.value end local info = {} for key, val in ipairs(LSM:List("font")) do info.text = val info.value = LSM:Fetch("font", val) info.func = dropClick UIDropDownMenu_AddButton(info) end UIDropDownMenu_SetText(fontOpt, IcicleVars.Settings.fontName) UIDropDownMenu_SetSelectedValue(fontOpt, IcicleVars.Settings.font) end -------------------------------- --// Create options menu. -------------------------------- local function showOpts(OptionsGen) local dummy local sizeSldr = createSlider("Icon Size", 140, 15, 16, 30, 1) sizeSldr:SetValue(IcicleVars.Settings.iconsize) sizeSldr:SetPoint("TOPLEFT", 30, -34) sizeSldr:SetScript("OnValueChanged", function(self, value) IcicleVars.Settings.iconsize = value dummy.icon:SetHeight(value) dummy.icon:SetWidth(value) dummy.icon.texture:SetHeight(value - 2) dummy.icon.texture:SetWidth(value - 2) end) local xoffSldr = createSlider("Icon X", 150 , 15, -115, 120, 5) xoffSldr:SetValue(IcicleVars.Settings.xoff) xoffSldr:SetPoint("CENTER", 0, 160) xoffSldr:SetScript("OnValueChanged", function(self, value) IcicleVars.Settings.xoff = value dummy.icon:SetPoint("CENTER", dummy, value, IcicleVars.Settings.yoff) end) local yoffSldr = createSlider("Icon Y", 15, 100, -65, 55, 5) yoffSldr:SetOrientation("VERTICAL") yoffSldr:SetValue(IcicleVars.Settings.yoff) yoffSldr:SetPoint("LEFT", 70, 20) yoffSldr:SetScript("OnValueChanged", function(self, value) IcicleVars.Settings.yoff = value dummy.icon:SetPoint("CENTER", dummy, IcicleVars.Settings.xoff, value) end) local fntsSldr = createSlider("Font Size", 150 , 15, 6, 30, 1) fntsSldr:SetValue(IcicleVars.Settings.fontSize) fntsSldr:SetPoint("TOPRIGHT", -30, -34) fntsSldr:SetScript("OnValueChanged", function(self, value) IcicleVars.Settings.fontSize = value dummy.cooldown:SetFont(Icicle.Settings.font , value, "OUTLINE") end) local fntySldr = createSlider("Font Y", 15 , 100, -15, 15, 1) fntySldr:SetOrientation("VERTICAL") fntySldr:SetValue(IcicleVars.Settings.fontY) fntySldr:SetPoint("RIGHT", -70, 20) fntySldr:SetScript("OnValueChanged", function(self, value) IcicleVars.Settings.fontY = value dummy.cooldown:SetPoint("CENTER", dummy.icon, IcicleVars.Settings.fontX, value) end) local fntxSldr = createSlider("Font X", 150 , 15, -15, 15, 1) fntxSldr:SetValue(IcicleVars.Settings.fontX) fntxSldr:SetPoint("CENTER", 0, -120) fntxSldr:SetScript("OnValueChanged", function(self, value) IcicleVars.Settings.fontX = value dummy.cooldown:SetPoint("CENTER", dummy.icon, value, IcicleVars.Settings.fontY) end) dummy = CreateFrame("Frame") dummy:SetHeight(36) dummy:SetWidth(130) dummy:SetScale(1.5) dummy:SetParent(OptionsGen) dummy:SetPoint("CENTER", 0, 20) dummy.background = dummy:CreateTexture(nil, "BORDER") dummy.background:SetPoint("BOTTOMLEFT", dummy, 3, 3.5) dummy.background:SetHeight(12) dummy.background:SetWidth(130) dummy.background:SetTexture(1, 1, 1) dummy.foreground = dummy:CreateTexture(nil, "ARTWORK") dummy.foreground:SetPoint("BOTTOMLEFT", dummy, 4, 4.5) dummy.foreground:SetHeight(10) dummy.foreground:SetWidth(128) dummy.foreground:SetTexture(.5, .5, 1) dummy.lab = createLabel(dummy, '*Default nameplate.') dummy.lab:SetPoint("BOTTOM", 0, 4) dummy.icon = createIcon(42292, IcicleVars.Settings.iconsize) dummy.icon:SetParent(dummy) dummy.icon:SetPoint("CENTER", IcicleVars.Settings.xoff, IcicleVars.Settings.yoff) dummy.cooldown = dummy:CreateFontString(nil, "OVERLAY") dummy.cooldown:SetParent(dummy.icon) dummy.cooldown:SetPoint("CENTER", dummy.icon, IcicleVars.Settings.fontX, IcicleVars.Settings.fontY) dummy.cooldown:SetHeight(50) dummy.cooldown:SetWidth(50) dummy.cooldown:SetFont(Icicle.Settings.font , Icicle.Settings.fontSize, "OUTLINE") dummy.cooldown:SetTextColor(0.7, 1, 0) dummy.cooldown:SetText(30) local fontOpt = CreateFrame("Frame", "Iciclefont", OptionsGen, "UIDropDownMenuTemplate") fontOpt.lab = createLabel(fontOpt, "Font Face") fontOpt:SetWidth(200) fontOpt:SetPoint("TOP", 15, -30) UIDropDownMenu_Initialize(fontOpt, fontInit) --CLASS OPTIONS for key, val in orderedpairs(cooldowns) do if (key ~= "Misc") then local classOpt = CreateFrame("Frame") classOpt.name = key classOpt.parent = addonName InterfaceOptions_AddCategory(classOpt) local ind = 1 local xOffset=0 for key, val in pairs(val) do if (ind==12) then ind=13 end ---SET TO 13 for 1 modulo 12 =1 if (ind>12) then xOffset = 250 end classOpt.Abi = createIcon(key, 36) classOpt.Abi:Show() classOpt.Abi:SetParent(classOpt) classOpt.Abi:SetPoint("TOPLEFT", xOffset+15, (ind % 12) * -45 + 35) classOpt.Abi:SetScript("OnEnter", function() GameTooltip:SetOwner(classOpt.Abi, "ANCHOR_CURSOR"); GameTooltip:SetSpellByID(key) GameTooltip:Show() end) classOpt.Abi:SetScript("OnLeave", function() GameTooltip:Hide() end) --classOpt.lab = createLabel(classOpt, select(1, GetSpellInfo(key))) --classOpt.lab:SetPoint("TOPLEFT", xOffset+60, (ind % 12) * -45 + 12) classOpt.chk = createCheck(classOpt, key, 20, 20, select(1, GetSpellInfo(key)), "Enable this if you DO NOT want to track it") classOpt.chk:SetPoint("TOPLEFT", xOffset+60, (ind % 12) * -45 + 25) if (IcicleVars.CooldownsMD[key]) then classOpt.chk:SetChecked() end classOpt.chk:SetScript("OnClick", function() if (IcicleVars.CooldownsMD[key]) then IcicleVars.CooldownsMD[key] = false Icicle.Cooldowns[key].enabled = false else IcicleVars.CooldownsMD[key] = true Icicle.Cooldowns[key].enabled = true end end) ind = ind + 1 end end end --PVP TRINKET ICONS local ind = 1 for key, val in pairs(cooldowns.Misc) do OptionsGen.Abi = createIcon(key, 36) OptionsGen.Abi:Show() OptionsGen.Abi:SetParent(OptionsGen) OptionsGen.Abi:SetPoint("BOTTOMLEFT", 15, ind * 60 - 35) OptionsGen.Abi:SetScript("OnEnter", function() GameTooltip:SetOwner(OptionsGen.Abi, "ANCHOR_CURSOR"); GameTooltip:SetSpellByID(key) GameTooltip:Show() end) OptionsGen.Abi:SetScript("OnLeave", function() GameTooltip:Hide() end) OptionsGen.lab = createLabel(OptionsGen, select(1, GetSpellInfo(key))) OptionsGen.lab:SetPoint("BOTTOMLEFT", 60, ind * 60 - 34) OptionsGen.chk = createCheck(OptionsGen, key, 20, 20) OptionsGen.chk:SetPoint("BOTTOMLEFT", 60, ind * 60 - 18) if (IcicleVars.CooldownsMD[key]) then OptionsGen.chk:SetChecked() end OptionsGen.chk:SetScript("OnClick", function() if (IcicleVars.CooldownsMD[key]) then IcicleVars.CooldownsMD[key] = false Icicle.Cooldowns[key].enabled = false else IcicleVars.CooldownsMD[key] = true Icicle.Cooldowns[key].enabled = true end end) ind = ind + 1 end end InterfaceOptions_AddCategory(OptionsGen) -------------------------------- --// Initialize icicle. -------------------------------- local function refreshCooldowns() for key, val in pairs(cooldowns) do for key, val in pairs(val) do local t={} t.enabled = IcicleVars.CooldownsMD[key] t.cd=val tinsert(Icicle.Cooldowns, key, t) end end end local function initCore() Icicle.Core.enAble() end local function initVars() if not IcicleVars then IcicleVars = {} IcicleVars.Settings = {} IcicleVars.Settings = Settings end if not IcicleVars.CooldownsMD then --migrate old saved vars IcicleVars.CooldownsMD = {} end for key, val in pairs(cooldowns) do for key, val in pairs(val) do if IcicleVars.CooldownsMD[key]==nil then tinsert(IcicleVars.CooldownsMD, key, true) end end end Icicle.Settings = IcicleVars.Settings Icicle.Cooldowns = {} refreshCooldowns() end local function onEvent(frame, event, arg) if (event == "ADDON_LOADED") then if (arg ~= "Icicle") then return end initVars() frame:UnregisterEvent("ADDON_LOADED") elseif (event == "VARIABLES_LOADED") then initCore() for key, val in ipairs(LSM:List("font")) do tinsert(Icicle.fonts, val) end table.sort(Icicle.fonts) LSM.RegisterCallback(frame, "LibSharedMedia_Registered", updateMedia) showOpts(OptionsGen) end end IcicleOpts = CreateFrame("Frame") IcicleOpts:SetScript("OnEvent", onEvent) IcicleOpts:RegisterEvent("ADDON_LOADED") IcicleOpts:RegisterEvent("VARIABLES_LOADED") -------------------------------- -------------------------------- SlashCmdList["ICICLE"] = function() InterfaceOptionsFrame_OpenToCategory(addonName) end SLASH_ICICLE1 = "/icicle"
local posses = {} function API.createPosse(charid, name) local User = API.getUserFromCharId(charid) local teste = 0 local members = { [charid] = 1, [teste] = 0, } --[[ for k, v in pairs(members) do if v == 1 then end end ]] --[[ local rows = API_Database.query('CKF_/CreatePosse', {charid = charid, name = name, members = json.encode(members)}) if #rows > 0 then local id = rows[1].id User:setPosse(id) local Posse = API.Posse(id, charid, name, nil) posses[id] = Posse end ]] end function API.getPosse(id) if id ~= nil then if posses[id] ~= nil then return posses[id] else local rows = API_Database.query('CKF_/GetPosseById', {id = id}) if #rows > 0 then local Posse = API.Posse(id, rows[1].charid, rows[1].name, json.decode(rows[1].members)) posses[id] = Posse return Posse end end end return nil end function API.deletePosse(id) posses[id] = nil end
-- Copyright (C) Kong Inc. local policies = require "kong.plugins.rate-limiting.policies" local timestamp = require "kong.tools.timestamp" local responses = require "kong.tools.responses" local BasePlugin = require "kong.plugins.base_plugin" local ngx_log = ngx.log local pairs = pairs local tostring = tostring local ngx_timer_at = ngx.timer.at local RATELIMIT_LIMIT = "X-RateLimit-Limit" local RATELIMIT_REMAINING = "X-RateLimit-Remaining" local RateLimitingHandler = BasePlugin:extend() RateLimitingHandler.PRIORITY = 901 RateLimitingHandler.VERSION = "0.1.0" local function get_identifier(conf) local identifier -- Consumer is identified by ip address or authenticated_credential id if conf.limit_by == "consumer" then identifier = ngx.ctx.authenticated_consumer and ngx.ctx.authenticated_consumer.id if not identifier and ngx.ctx.authenticated_credential then -- Fallback on credential identifier = ngx.ctx.authenticated_credential.id end elseif conf.limit_by == "credential" then identifier = ngx.ctx.authenticated_credential and ngx.ctx.authenticated_credential.id end if not identifier then identifier = ngx.var.remote_addr end return identifier end local function get_usage(conf, api_id, identifier, current_timestamp, limits) local usage = {} local stop for name, limit in pairs(limits) do local current_usage, err = policies[conf.policy].usage(conf, api_id, identifier, current_timestamp, name) if err then return nil, nil, err end -- What is the current usage for the configured limit name? local remaining = limit - current_usage -- Recording usage usage[name] = { limit = limit, remaining = remaining } if remaining <= 0 then stop = name end end return usage, stop end function RateLimitingHandler:new() RateLimitingHandler.super.new(self, "rate-limiting") end function RateLimitingHandler:access(conf) RateLimitingHandler.super.access(self) local current_timestamp = timestamp.get_utc() -- Consumer is identified by ip address or authenticated_credential id local identifier = get_identifier(conf) local api_id = ngx.ctx.api.id local policy = conf.policy local fault_tolerant = conf.fault_tolerant -- Load current metric for configured period local limits = { second = conf.second, minute = conf.minute, hour = conf.hour, day = conf.day, month = conf.month, year = conf.year } local usage, stop, err = get_usage(conf, api_id, identifier, current_timestamp, limits) if err then if fault_tolerant then ngx_log(ngx.ERR, "failed to get usage: ", tostring(err)) else return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end end if usage then -- Adding headers if not conf.hide_client_headers then for k, v in pairs(usage) do ngx.header[RATELIMIT_LIMIT .. "-" .. k] = v.limit ngx.header[RATELIMIT_REMAINING .. "-" .. k] = math.max(0, (stop == nil or stop == k) and v.remaining - 1 or v.remaining) -- -increment_value for this current request end end -- If limit is exceeded, terminate the request if stop then return responses.send(429, "API rate limit exceeded") end end local incr = function(premature, conf, limits, api_id, identifier, current_timestamp, value) if premature then return end policies[policy].increment(conf, limits, api_id, identifier, current_timestamp, value) end -- Increment metrics for configured periods if the request goes through local ok, err = ngx_timer_at(0, incr, conf, limits, api_id, identifier, current_timestamp, 1) if not ok then ngx_log(ngx.ERR, "failed to create timer: ", err) end end return RateLimitingHandler
local ffi = require ("ffi") ffi.cdef[[ /// <summary> /// The measuring method used for text layout. /// </summary> typedef enum DWRITE_MEASURING_MODE { /// <summary> /// Text is measured using glyph ideal metrics whose values are independent to the current display resolution. /// </summary> DWRITE_MEASURING_MODE_NATURAL, /// <summary> /// Text is measured using glyph display compatible metrics whose values tuned for the current display resolution. /// </summary> DWRITE_MEASURING_MODE_GDI_CLASSIC, /// <summary> /// Text is measured using the same glyph display metrics as text measured by GDI using a font /// created with CLEARTYPE_NATURAL_QUALITY. /// </summary> DWRITE_MEASURING_MODE_GDI_NATURAL } DWRITE_MEASURING_MODE; ]]
-- Copyright 2014-2015 Greentwip. All Rights Reserved. local block = class("block", cc.Node) function block:ctor(position, size) self:setup(position, size) end function block:setup(position, size) self:setPosition(cc.p(position.x, position.y)) local body = cc.PhysicsBody:create() body:setDynamic (false) body:setRotationEnable (false) body:setVelocityLimit (400) -- polygon shape local material = cc.PhysicsMaterial(0, 0, 0) local polygon = { cc.p( size.width * 0.5, size.height * 0.5), cc.p( size.width * 0.5, -size.height * 0.5), cc.p(-size.width * 0.5, -size.height * 0.5), cc.p(-size.width * 0.5, size.height * 0.5) } local shape = cc.PhysicsShapePolygon:create(polygon, material, cc.p(0,0)) shape:setTag (cc.tags.block) shape.size_ = size body:addShape(shape) --apply physicsBody to the block self:setPhysicsBody(body) end return block
slot0 = class("NissinFoodPage", import("...base.BaseActivityPage")) slot0.OnInit = function (slot0) slot0.bg = slot0:findTF("AD") slot0.helpBtn = slot0:findTF("help_btn", slot0.bg) slot0.startBtn = slot0:findTF("start_btn", slot0.bg) slot0.cupList = slot0:findTF("cup_list", slot0.bg) end slot0.OnFirstFlush = function (slot0) slot0.hubID = slot0.activity:getConfig("config_id") slot0.drop_list = slot0.activity:getConfig("config_client") onButton(slot0, slot0.helpBtn, function () pg.MsgboxMgr.GetInstance():ShowMsgBox({ type = MSGBOX_TYPE_HELP, helps = i18n("chazi_tips") }) end, SFX_PANEL) onButton(slot0, slot0.startBtn, function () pg.m02:sendNotification(GAME.GO_MINI_GAME, 29) end, SFX_PANEL) end slot0.OnUpdateFlush = function (slot0) eachChild(slot0.cupList, function (slot0) slot1 = tonumber(slot0.name) setActive(slot0:findTF("lock", slot0), slot1 > slot1.count + slot1.usedtime) setActive(slot0:findTF("got", slot0), slot1 <= slot1.usedtime) updateDrop(setActive, slot1 <= slot1.usedtime) onButton(slot0, slot0:findTF("mask/award", slot0), function () slot0:emit(BaseUI.ON_DROP, slot0) end, SFX_PANEL) end) if getProxy(MiniGameProxy).GetHubByHubId(slot1, slot0.hubID).ultimate == 0 and slot2.getConfig(slot2, "reward_need") <= slot2.usedtime then pg.m02:sendNotification(GAME.SEND_MINI_GAME_OP, { hubid = slot2.id, cmd = MiniGameOPCommand.CMD_ULTIMATE, args1 = {} }) end end return slot0
IP_record="0.0.0.0"
smoke = {} smoke.list = {} smoke.toRemove = {} function smoke.new(posX, posY, scale) local newSmoke = { x = posX, y = posY, r = math.random() * math.twopi, s = math.random() * (scale / 2) + (scale / 2), frame = 1, frameCounter = 0, } table.insert(smoke.list, newSmoke) end function smoke.draw() for i, smokeObj in ipairs(smoke.list) do local image = animations.smoke.frames[smokeObj.frame] local ox = image:getWidth() / 2 local oy = image:getHeight() / 2 love.graphics.setColor(1, 1, 1, 1 - (smokeObj.frame * .05)) love.graphics.draw(image, smokeObj.x, smokeObj.y, smokeObj.r, smokeObj.s, smokeObj.s, ox, oy) end love.graphics.setColor(1, 1, 1, 1) end function smoke.update() for i, smokeObj in ipairs(smoke.list) do smokeObj.frameCounter = smokeObj.frameCounter + love.math.random() if smokeObj.frameCounter >= animations.smoke.speed then smokeObj.frameCounter = 0 smokeObj.frame = smokeObj.frame + 1 if smokeObj.frame > #animations.smoke.frames then smoke.remove(smokeObj) end end end if #smoke.toRemove > 0 then for i, toRem in ipairs(smoke.toRemove) do local foundIndex = -1 for j, sObj in ipairs(smoke.list) do if sObj == toRem then foundIndex = j break end end if foundIndex ~= -1 then table.remove(smoke.list, foundIndex) end end smoke.toRemove = {} end end function smoke.remove(smokeObj) table.insert(smoke.toRemove, smokeObj) end function smoke.removeAll() smoke.list = {} smoke.toRemove = {} end
AetheriusBadgeFilter:RegisterGuild(AetheriusBadgeFilter.SERVER_EU, "Tamriel Stock Exchange", { { name = "Social", badges = { { name = "Elder", description = "Is since min. 200 days member of the guild.", }, { name = "Veteran", description = "Is since min. 100 days member of the guild.", }, { name = "Donator", description = "Donated over 100k.", }, { name = "Generous Donator", description = "Donated over 250k.", }, { name = "Patron", description = "Donated over 500k.", }, { name = "Generous Patron", description = "Donated over 1kk.", }, } }, { name = "Trading", badges = { { name = "Aspirant", description = "Reached 500k sales/week. Can be awarded multiple times.", limit = false, }, { name = "Glorious", description = "Reached 1kk sales/week. Can be awarded multiple times.", limit = false, }, { name = "Master Trader", description = "Has been Top-Trader in one trading week. Can be awarded multiple times.", limit = 10, turnsInto = "Trading Monster" }, { name = "Trading Monster", description = "Has been 10 times Top-Trader. Can be awarded multiple times.", limit = false, }, } }, { name = "Crafting", badges = { { name = "Master Crafter", description = "Mastered Alchemy, Enchanting, Provisioning, Backsmithing, Clothing and Woodworking", relations = {"Alchemist", "Provisioner", "Woodworker", "Tailor", "Blacksmith", "Enchanter"}, }, { name = "Set-Provider", description = "Has following Crafting-Stations in his house accessible for everyone in this guild.", }, { name = "Alchemist", description = "Knows all ingredients and reached lvl 50 in Alchemy", }, { name = "Provisioner", description = "Knows 90% of all recipes and mastered Provisioning", }, { name = "Blacksmith", description = "Knows all 9 traits on heavy armor and weapons and reached lvl 50 in Blacksmithing.", }, { name = "Tailor", description = "Knows all 9 traits on light and medium armor and reached lvl 50 in Clothing.", }, { name = "Woodworker", description = "Knows all 9 traits on shields and wooden weapons and reached lvl 50 in Woodworking.", }, { name = "Enchanter", description = "Knows all runes and reached lvl 50 in Enchanting.", }, { name = "Karl Lagerfeld", description = "Knows all recent crafting styles.", }, } }, })
object_mobile_axkva_min_static = object_mobile_shared_axkva_min_static:new { } ObjectTemplates:addTemplate(object_mobile_axkva_min_static, "object/mobile/axkva_min_static.iff")
-- premake5.lua include "./vendor/premake/premake_customization/solution_items.lua" workspace "Hazel" architecture "x86_64" startproject "Hazel-Editor" configurations { "Debug", "Release", "Dist" } solution_items { ".editorconfig" } flags { "MultiProcessorCompile" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" -- Include directories relative to root folder (solution directory) IncludeDir = {} IncludeDir["GLFW"] = "%{wks.location}/Hazel/vendor/GLFW/include" IncludeDir["Glad"] = "%{wks.location}/Hazel/vendor/Glad/include" IncludeDir["ImGui"] = "%{wks.location}/Hazel/vendor/imgui" IncludeDir["glm"] = "%{wks.location}/Hazel/vendor/glm" IncludeDir["stb_image"] = "%{wks.location}/Hazel/vendor/stb_image" IncludeDir["entt"] = "%{wks.location}/Hazel/vendor/entt/include" IncludeDir["yaml_cpp"] = "%{wks.location}/Hazel/vendor/yaml-cpp/include" IncludeDir["ImGuizmo"] = "%{wks.location}/Hazel/vendor/ImGuizmo" group "Dependencies" include "vendor/premake" include "Hazel/vendor/GLFW" include "Hazel/vendor/Glad" include "Hazel/vendor/imgui" include "Hazel/vendor/yaml-cpp" group "" include "Hazel" include "Sandbox" include "Hazel-Editor"
local serializationKey = "wedit.randomPicker.percentage" randomPickerUtil = {} --- Retrieves the serialized percentage. -- @return Serialized percentage, or nil function randomPickerUtil.getSerializedPercentage() return status.statusProperty(serializationKey) end --- Serializes the percentage. -- @param perc Percentage from 0-100. function randomPickerUtil.serializePercentage(perc) local t = type(perc) if t ~= "number" and t ~= "nil" then error("serializePercentage expected a number or nil.") end status.setStatusProperty(serializationKey, perc) end
--- Module implementing the LuaRocks "lint" command. -- Utility function that checks syntax of the rockspec. module("luarocks.lint", package.seeall) local util = require("luarocks.util") local download = require("luarocks.download") local fetch = require("luarocks.fetch") help_summary = "Check syntax of a rockspec." help_arguments = "<rockspec>" help = [[ This is a utility function that checks the syntax of a rockspec. It returns success or failure if the text of a rockspec is syntactically correct. ]] function run(...) local flags, input = util.parse_flags(...) if not input then return nil, "Argument missing. "..util.see_help("lint") end local filename = input if not input:match(".rockspec$") then local err filename, err = download.download("rockspec", input) if not filename then return nil, err end end local rs, err = fetch.load_local_rockspec(filename) if not rs then return nil, "Failed loading rockspec: "..err end local ok = true -- This should have been done in the type checker, -- but it would break compatibility of other commands. -- Making 'lint' alone be stricter shouldn't be a problem, -- because extra-strict checks is what lint-type commands -- are all about. if not rs.description.license then util.printerr("Rockspec has no license field.") ok = false end return ok, ok or filename.." failed consistency checks." end
--------------------------------------------------------------------------- -- A simple button widget. -- -- --DOC_GEN_IMAGE --DOC_HIDE -- --![Usage example](../images/AUTOGEN_wibox_awidget_defaults_button.svg) -- -- -- awful.widget.button { -- image = beautiful.awesome_icon, -- buttons = { -- awful.button({}, 1, nil, function () -- print(&#34Mouse was clicked&#34) -- end) -- } -- } -- -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @copyright 2008-2009 Julien Danjou -- @widgetmod awful.widget.button -- @supermodule wibox.widget.imagebox --------------------------------------------------------------------------- local setmetatable = setmetatable local abutton = require("awful.button") local imagebox = require("wibox.widget.imagebox") local widget = require("wibox.widget.base") local surface = require("gears.surface") local cairo = require("lgi").cairo local gtable = require("gears.table") local button = { mt = {} } --- Create a button widget. When clicked, the image is deplaced to make it like -- a real button. -- -- @constructorfct awful.widget.button -- @tparam table args Widget arguments. -- @tparam string args.image "image" is the image to display (mandatory). -- @tparam table args.buttons The buttons. -- @return A textbox widget configured as a button. function button.new(args) args = args or {} if not args.image then return widget.empty_widget() end local w = imagebox() local orig_set_image = w.set_image local img_release local img_press function w:set_image(image) img_release = surface.load(image) img_press = img_release:create_similar(cairo.Content.COLOR_ALPHA, img_release.width, img_release.height) local cr = cairo.Context(img_press) cr:set_source_surface(img_release, 2, 2) cr:paint() orig_set_image(self, img_release) end w:set_image(args.image) local btns = gtable.clone(args.buttons or {}, false) table.insert(btns, abutton({}, 1, function () orig_set_image(w, img_press) end, function () orig_set_image(w, img_release) end) ) w.buttons = btns w:connect_signal("mouse::leave", function(self) orig_set_image(self, img_release) end) return w end function button.mt:__call(...) return button.new(...) end return setmetatable(button, button.mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
----------------------------------- -- Area: Promyvion vahzl -- NPC: Memory flux (3) ----------------------------------- local ID = require("scripts/zones/Promyvion-Vahzl/IDs") require("scripts/globals/missions") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if player:getCurrentMission(COP) == tpz.mission.id.cop.DESIRES_OF_EMPTINESS and player:getCharVar("PromathiaStatus") == 5 and not GetMobByID(ID.mob.PONDERER):isSpawned() then SpawnMob(ID.mob.PONDERER):updateClaim(player) elseif player:getCurrentMission(COP) == tpz.mission.id.cop.DESIRES_OF_EMPTINESS and player:getCharVar("PromathiaStatus") == 6 then player:startEvent(53) else player:messageSpecial(ID.text.OVERFLOWING_MEMORIES) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid == 53 then player:setCharVar("PromathiaStatus", 7) end end
require "libs.classes.TransportLinesAccess" BeltAccess = {} BeltAccess.__index = BeltAccess setmetatable(BeltAccess, { __index = TransportLinesAccess, __call = function(class, ...) local self = setmetatable({},class) self:_init(...) return self end }) function BeltAccess:_init(beltEntity, accessFromPosition) TransportLinesAccess._init(self,beltEntity.get_transport_line(1), beltEntity.get_transport_line(2),beltEntity.position,accessFromPosition) self.beltEntity = beltEntity end function BeltAccess:isInput() local direction = self.beltEntity.direction local side = self:getSide() return side == (direction + 4)%8 -- must be 180° end
local module = {} local playerData = require(game:GetService('ServerStorage').Modules.PlayerData) local remote = game:GetService('ReplicatedStorage').Remotes.BiomeChanged local attribute_name = 'Biome' local lastBiomes = {} local function GetContent(name) local content = script:FindFirstChild(name) if content then return require(content) end end local function Sanitize(character, part) local biome = part and part:GetAttribute(attribute_name) if character and biome then return biome end end local function Changed(player, part) local character = player.Character local name = Sanitize(character, part) if name then local lastName = lastBiomes[character] local data = playerData.Get(player) local content = GetContent(name) local last = GetContent(lastName) if last then last.Stop(character, part) end if content then task.spawn(content.Start, character, part) end data.location = name lastBiomes[character] = name end end function module.Start(character) lastBiomes[character] = '' end function module.Stop(character) lastBiomes[character] = nil end remote.OnServerEvent:Connect(Changed) return module
local M = {} local pid = vim.fn.getpid() M.setup = function(config, _, opts) local cmd = { "omnisharp", "--languageserver", "--hostPID", tostring(pid), } config.cmd = opts.cmd and opts.cmd or cmd return config end return M
require 'funcs' local GameMode = require 'tetris.modes.gamemode' local Piece = require 'tetris.components.piece' local History6RollsRandomizer = require 'tetris.randomizers.history_6rolls' local MarathonWCBGame = GameMode:extend() MarathonWCBGame.name = "Marathon WCB" MarathonWCBGame.hash = "MarathonWCB" MarathonWCBGame.tagline = "When all the pieces slip right to their destinations... can you keep up?" function MarathonWCBGame:new() MarathonWCBGame.super:new() self.pieces = 0 self.randomizer = History6RollsRandomizer() self.lock_drop = true self.lock_hard_drop = true self.instant_hard_drop = true self.instant_soft_drop = true self.enable_hold = false self.next_queue_length = 3 self.piece_is_active = false end function MarathonWCBGame:getDropSpeed() return 20 end function MarathonWCBGame:getARR() return 0 end function MarathonWCBGame:getARE() return 0 end function MarathonWCBGame:getLineARE() return 0 end function MarathonWCBGame:getDasLimit() return 0 end function MarathonWCBGame:getLineClearDelay() return 0 end function MarathonWCBGame:getLockDelay() return math.huge end function MarathonWCBGame:getGravity() return self.piece_is_active and 20 or 0 end function MarathonWCBGame:advanceOneFrame() if self.clear then self.roll_frames = self.roll_frames + 1 if self.roll_frames > 150 then self.completed = true end return false elseif self.ready_frames == 0 then self.frames = self.frames + 1 end return true end function MarathonWCBGame:onAttemptPieceMove() if self.piece ~= nil then -- don't let the piece move before it's finished dropping self.piece:dropToBottom(self.grid) end self.piece_is_active = true end function MarathonWCBGame:onAttemptPieceRotate() self.piece_is_active = true end function MarathonWCBGame:onPieceLock() self.piece_is_active = false self.pieces = self.pieces + 1 end function MarathonWCBGame:onLineClear(cleared_row_count) if not self.clear then self.lines = self.lines + cleared_row_count end end function MarathonWCBGame:drawGrid(ruleset) self.grid:draw() if self.piece ~= nil then self:drawGhostPiece(ruleset) end end function MarathonWCBGame:getHighscoreData() return { pieces = self.pieces, frames = self.frames, } end function MarathonWCBGame:drawScoringInfo() MarathonWCBGame.super.drawScoringInfo(self) love.graphics.setColor(1, 1, 1, 1) local text_x = config["side_next"] and 320 or 240 love.graphics.setFont(font_3x5_2) love.graphics.printf("NEXT", 64, 40, 40, "left") love.graphics.printf("lines", text_x, 160, 80, "left") love.graphics.printf("pieces", text_x, 220, 80, "left") love.graphics.setFont(font_3x5_3) love.graphics.printf(self.lines, text_x, 180, 80, "left") love.graphics.printf(self.pieces, text_x, 240, 80, "left") end function MarathonWCBGame:getBackground() return (math.floor(self.pieces / 50) % 20) end return MarathonWCBGame
local function GetPlayingRookieCount() local rookieClients = TGNS.GetMatchingClients(TGNS.GetPlayers(TGNS.GetPlayingClients(TGNS.GetPlayerList())), function(c,p) return p:GetIsRookie() and not TGNS.IsPlayerSM(p) end) local result = #rookieClients return result end local md = TGNSMessageDisplayer.Create() local Plugin = {} function Plugin:JoinTeam(gamerules, player, newTeamNumber, force, shineForce) if not (force or shineForce) then if TGNS.IsGameplayTeamNumber(newTeamNumber) then local playerIsRookie = player:GetIsRookie() if playerIsRookie then local tooManyRookies = TGNS.GetPlayerCount() > 10 and GetPlayingRookieCount() > 4 if tooManyRookies then md:ToPlayerNotifyError(player, "To teach, we limit concurrent rookies. Please spectate for now!") return false end end end end end function Plugin:Initialise() self.Enabled = true return true end function Plugin:Cleanup() --Cleanup your extra stuff like timers, data etc. self.BaseClass.Cleanup( self ) end Shine:RegisterExtension("rookiethrottle", Plugin )
--- -- @module EraserTool -- -- ------------------------------------------------ -- Required Modules -- ------------------------------------------------ local BaseTool = require( 'src.map.editor.BaseTool' ) local TexturePacks = require( 'src.ui.texturepacks.TexturePacks' ) -- ------------------------------------------------ -- Module -- ------------------------------------------------ local EraserTool = BaseTool:subclass( 'EraserTool' ) -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local SPRITE = 'prefab_editor_cursor_erase' -- ------------------------------------------------ -- Public Methods -- ------------------------------------------------ function EraserTool:initialize() BaseTool.initialize( self, 'tool_erase' ) end function EraserTool:draw() if self.iconColorID then TexturePacks.setColor( self.iconColorID ) end local tw, th = TexturePacks.getTileDimensions() for x = 0, self.size-1 do for y = 0, self.size-1 do love.graphics.draw( TexturePacks.getTileset():getSpritesheet(), TexturePacks.getSprite( SPRITE ), (self.x+x) * tw, (self.y+y) * th ) end end TexturePacks.resetColor() end function EraserTool:use( canvas ) if self.layer and self.active then for x = 0, self.size-1 do for y = 0, self.size-1 do if self.layer == 'worldObject' then canvas:removeWorldObject( self.x+x, self.y+y ) elseif self.layer == 'tile' then canvas:removeTile( self.x+x, self.y+y ) end end end end end return EraserTool
--[=[ @private @class LoaderConstants ]=] local Utils = require(script.Parent.Utils) return Utils.readonly({ GROUP_EACH_PACKAGE_INDIVIDUALLY = false; ALLOW_MULTIPLE_GROUPS = true; INCLUDE_IMPLICIT_DEPENDENCIES = true; })
debugstack = debug.traceback strmatch = string.match loadfile("../LibStub.lua")() -- Pretend like loaded libstub is old and doesn't have :IterateLibraries assert(LibStub.minor) LibStub.minor = LibStub.minor - 0.0001 LibStub.IterateLibraries = nil loadfile("../LibStub.lua")() assert(type(LibStub.IterateLibraries)=="function") -- Now pretend that we're the same version -- :IterateLibraries should NOT be re-created LibStub.IterateLibraries = 123 loadfile("../LibStub.lua")() assert(LibStub.IterateLibraries == 123) -- Now pretend that a newer version is loaded -- :IterateLibraries should NOT be re-created LibStub.minor = LibStub.minor + 0.0001 loadfile("../LibStub.lua")() assert(LibStub.IterateLibraries == 123) -- Again with a huge number LibStub.minor = LibStub.minor + 1234567890 loadfile("../LibStub.lua")() assert(LibStub.IterateLibraries == 123) print("OK")
ITEM.name = "Desk" ITEM.description = "containerDeskDesc" ITEM.ContainerModel = "models/props_interiors/Furniture_Desk01a.mdl" ITEM.price = 160
-- XEP-0356 (Privileged Entity) -- Copyright (C) 2015 Jérôme Poisson -- -- This module is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- -- Some parts come from mod_remote_roster (module by Waqas Hussain and Kim Alvefur, see https://code.google.com/p/prosody-modules/) -- TODO: manage external <presence/> (for "roster" presence permission) when the account with the roster is offline local jid = require("util/jid") local set = require("util/set") local st = require("util/stanza") local roster_manager = require("core/rostermanager") local user_manager = require("core/usermanager") local hosts = prosody.hosts local full_sessions = prosody.full_sessions; local priv_session = module:shared("/*/privilege/session") if priv_session.connected_cb == nil then -- set used to have connected event listeners -- which allows a host to react on events from -- other hosts priv_session.connected_cb = set.new() end local connected_cb = priv_session.connected_cb -- the folowing sets are used to forward presence stanza -- the folowing sets are used to forward presence stanza local presence_man_ent = set.new() local presence_roster = set.new() local _ALLOWED_ROSTER = set.new({'none', 'get', 'set', 'both'}) local _ROSTER_GET_PERM = set.new({'get', 'both'}) local _ROSTER_SET_PERM = set.new({'set', 'both'}) local _ALLOWED_MESSAGE = set.new({'none', 'outgoing'}) local _ALLOWED_PRESENCE = set.new({'none', 'managed_entity', 'roster'}) local _PRESENCE_MANAGED = set.new({'managed_entity', 'roster'}) local _TO_CHECK = {roster=_ALLOWED_ROSTER, message=_ALLOWED_MESSAGE, presence=_ALLOWED_PRESENCE} local _PRIV_ENT_NS = 'urn:xmpp:privilege:1' local _FORWARDED_NS = 'urn:xmpp:forward:0' module:log("debug", "Loading privileged entity module "); --> Permissions management <-- local privileges = module:get_option("privileged_entities", {}) local function advertise_perm(session, to_jid, perms) -- send <message/> stanza to advertise permissions -- as expained in § 4.2 local message = st.message({from=module.host, to=to_jid}) :tag("privilege", {xmlns=_PRIV_ENT_NS}) for _, perm in pairs({'roster', 'message', 'presence'}) do if perms[perm] then message:tag("perm", {access=perm, type=perms[perm]}):up() end end session.send(message) end local function set_presence_perm_set(to_jid, perms) -- fill the presence sets according to perms if _PRESENCE_MANAGED:contains(perms.presence) then presence_man_ent:add(to_jid) end if perms.presence == 'roster' then presence_roster:add(to_jid) end end local function advertise_presences(session, to_jid, perms) -- send presence status for already conencted entities -- as explained in § 7.1 -- people in roster are probed only for active sessions -- TODO: manage roster load for inactive sessions if not perms.presence then return; end local to_probe = {} for _, user_session in pairs(full_sessions) do if user_session.presence and _PRESENCE_MANAGED:contains(perms.presence) then local presence = st.clone(user_session.presence) presence.attr.to = to_jid module:log("debug", "sending current presence for "..tostring(user_session.full_jid)) session.send(presence) end if perms.presence == "roster" then -- we reset the cache to avoid to miss a presence that just changed priv_session.last_presence = nil if user_session.roster then local bare_jid = jid.bare(user_session.full_jid) for entity, item in pairs(user_session.roster) do if entity~=false and entity~="pending" and (item.subscription=="both" or item.subscription=="to") then local _, host = jid.split(entity) if not hosts[host] then -- we don't probe jid from hosts we manage -- using a table with entity as key avoid probing several time the same one to_probe[entity] = bare_jid end end end end end end -- now we probe peoples for "roster" presence permission for probe_to, probe_from in pairs(to_probe) do module:log("debug", "probing presence for %s (on behalf of %s)", tostring(probe_to), tostring(probe_from)) local probe = st.presence({from=probe_from, to=probe_to, type="probe"}) prosody.core_route_stanza(nil, probe) end end local function on_auth(event) -- Check if entity is privileged according to configuration, -- and set session.privileges accordingly local session = event.session local bare_jid = jid.join(session.username, session.host) local ent_priv = privileges[bare_jid] if ent_priv ~= nil then module:log("debug", "Entity is privileged") for perm_type, allowed_values in pairs(_TO_CHECK) do local value = ent_priv[perm_type] if value ~= nil then if not allowed_values:contains(value) then module:log('warn', 'Invalid value for '..perm_type..' privilege: ['..value..']') module:log('warn', 'Setting '..perm_type..' privilege to none') ent_priv[perm_type] = nil end if value == 'none' then ent_priv[perm_type] = nil end end end -- extra checks for presence permission if ent_priv.permission == 'roster' and not _ROSTER_GET_PERM:contains(session.privileges.roster) then module:log("warn", "Can't allow roster presence privilege without roster \"get\" privilege") module:log("warn", "Setting presence permission to none") ent_priv.permission = nil end if session.type == "component" then -- we send the message stanza only for component -- it will be sent at first <presence/> for other entities advertise_perm(session, bare_jid, ent_priv) set_presence_perm_set(bare_jid, ent_priv) advertise_presences(session, bare_jid, ent_priv) end end session.privileges = ent_priv end local function on_presence(event) -- Permission are already checked at this point, -- we only advertise them to the entity local session = event.origin if session.privileges then advertise_perm(session, session.full_jid, session.privileges) set_presence_perm_set(session.full_jid, session.privileges) advertise_presences(session, session.full_jid, session.privileges) end end local function on_component_auth(event) -- react to component-authenticated event from this host -- and call the on_auth methods from all other hosts -- needed for the component to get delegations advertising for callback in connected_cb:items() do callback(event) end end connected_cb:add(on_auth) module:hook('authentication-success', on_auth) module:hook('component-authenticated', on_component_auth) module:hook('presence/initial', on_presence) --> roster permission <-- -- get module:hook("iq-get/bare/jabber:iq:roster:query", function(event) local session, stanza = event.origin, event.stanza; if not stanza.attr.to then -- we don't want stanzas addressed to /self return; end if session.privileges and _ROSTER_GET_PERM:contains(session.privileges.roster) then module:log("debug", "Roster get from allowed privileged entity received") -- following code is adapted from mod_remote_roster local node, host = jid.split(stanza.attr.to); local roster = roster_manager.load_roster(node, host); local reply = st.reply(stanza):query("jabber:iq:roster"); for entity_jid, item in pairs(roster) do if entity_jid and entity_jid ~= "pending" then reply:tag("item", { jid = entity_jid, subscription = item.subscription, ask = item.ask, name = item.name, }); for group in pairs(item.groups) do reply:tag("group"):text(group):up(); end reply:up(); -- move out from item end end -- end of code adapted from mod_remote_roster session.send(reply); else module:log("warn", "Entity "..tostring(session.full_jid).." try to get roster without permission") session.send(st.error_reply(stanza, 'auth', 'forbidden')) end return true end); -- set module:hook("iq-set/bare/jabber:iq:roster:query", function(event) local session, stanza = event.origin, event.stanza; if not stanza.attr.to then -- we don't want stanzas addressed to /self return; end if session.privileges and _ROSTER_SET_PERM:contains(session.privileges.roster) then module:log("debug", "Roster set from allowed privileged entity received") -- following code is adapted from mod_remote_roster local from_node, from_host = jid.split(stanza.attr.to); if not(user_manager.user_exists(from_node, from_host)) then return; end local roster = roster_manager.load_roster(from_node, from_host); if not(roster) then return; end local query = stanza.tags[1]; for _, item in ipairs(query.tags) do if item.name == "item" and item.attr.xmlns == "jabber:iq:roster" and item.attr.jid -- Protection against overwriting roster.pending, until we move it and item.attr.jid ~= "pending" then local item_jid = jid.prep(item.attr.jid); local _, host, resource = jid.split(item_jid); if not resource then if item_jid ~= stanza.attr.to then -- not self-item_jid if item.attr.subscription == "remove" then local r_item = roster[item_jid]; if r_item then roster[item_jid] = nil; if roster_manager.save_roster(from_node, from_host, roster) then session.send(st.reply(stanza)); roster_manager.roster_push(from_node, from_host, item_jid); else roster[item_jid] = item; session.send(st.error_reply(stanza, "wait", "internal-server-error", "Unable to save roster")); end else session.send(st.error_reply(stanza, "modify", "item-not-found")); end else local subscription = item.attr.subscription; if subscription ~= "both" and subscription ~= "to" and subscription ~= "from" and subscription ~= "none" then -- TODO error on invalid subscription = roster[item_jid] and roster[item_jid].subscription or "none"; end local r_item = {name = item.attr.name, groups = {}}; if r_item.name == "" then r_item.name = nil; end r_item.subscription = subscription; if subscription ~= "both" and subscription ~= "to" then r_item.ask = roster[item_jid] and roster[item_jid].ask; end for _, child in ipairs(item) do if child.name == "group" then local text = table.concat(child); if text and text ~= "" then r_item.groups[text] = true; end end end local olditem = roster[item_jid]; roster[item_jid] = r_item; if roster_manager.save_roster(from_node, from_host, roster) then -- Ok, send success session.send(st.reply(stanza)); -- and push change to all resources roster_manager.roster_push(from_node, from_host, item_jid); else -- Adding to roster failed roster[item_jid] = olditem; session.send(st.error_reply(stanza, "wait", "internal-server-error", "Unable to save roster")); end end else -- Trying to add self to roster session.send(st.error_reply(stanza, "cancel", "not-allowed")); end else -- Invalid JID added to roster module:log("warn", "resource: %s , host: %s", tostring(resource), tostring(host)) session.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error? end else -- Roster set didn't include a single item, or its name wasn't 'item' session.send(st.error_reply(stanza, "modify", "bad-request")); end end -- for loop end -- end of code adapted from mod_remote_roster else -- The permission is not granted module:log("warn", "Entity "..tostring(session.full_jid).." try to set roster without permission") session.send(st.error_reply(stanza, 'auth', 'forbidden')) end return true end); --> message permission <-- module:hook("message/host", function(event) local session, stanza = event.origin, event.stanza; local privilege_elt = stanza:get_child('privilege', _PRIV_ENT_NS) if privilege_elt==nil then return; end if session.privileges and session.privileges.message=="outgoing" then if #privilege_elt.tags==1 and privilege_elt.tags[1].name == "forwarded" and privilege_elt.tags[1].attr.xmlns==_FORWARDED_NS then local message_elt = privilege_elt.tags[1]:get_child('message', 'jabber:client') if message_elt ~= nil then local _, from_host, from_resource = jid.split(message_elt.attr.from) if from_resource == nil and hosts[from_host] then -- we only accept bare jids from one of the server hosts -- at this point everything should be alright, we can send the message prosody.core_route_stanza(nil, message_elt) else -- trying to send a message from a forbidden entity module:log("warn", "Entity "..tostring(session.full_jid).." try to send a message from "..tostring(message_elt.attr.from)) session.send(st.error_reply(stanza, 'auth', 'forbidden')) end else -- incorrect message child session.send(st.error_reply(stanza, "modify", "bad-request", "invalid forwarded <message/> element")); end else -- incorrect forwarded child session.send(st.error_reply(stanza, "modify", "bad-request", "invalid <forwarded/> element")); end; else -- The permission is not granted module:log("warn", "Entity "..tostring(session.full_jid).." try to send message without permission") session.send(st.error_reply(stanza, 'auth', 'forbidden')) end return true end); --> presence permission <-- local function same_tags(tag1, tag2) -- check if two tags are equivalent if tag1.name ~= tag2.name then return false; end if #tag1 ~= #tag2 then return false; end for name, value in pairs(tag1.attr) do if tag2.attr[name] ~= value then return false; end end for i=1,#tag1 do if type(tag1[i]) == "string" then if tag1[i] ~= tag2[i] then return false; end else if not same_tags(tag1[i], tag2[i]) then return false; end end end return true end local function same_presences(presence1, presence2) -- check that 2 <presence/> stanzas are equivalent (except for "to" attribute) -- /!\ if the id change but everything else is equivalent, this method return false -- this behaviour may change in the future if presence1.attr.from ~= presence2.attr.from or presence1.attr.id ~= presence2.attr.id or presence1.attr.type ~= presence2.attr.type then return false end if presence1.attr.id and presence1.attr.id == presence2.attr.id then return true; end if #presence1 ~= #presence2 then return false; end for i=1,#presence1 do if type(presence1[i]) == "string" then if presence1[i] ~= presence2[i] then return false; end else if not same_tags(presence1[i], presence2[i]) then return false; end end end return true end local function forward_presence(presence, to_jid) local presence_fwd = st.clone(presence) presence_fwd.attr.to = to_jid module:log("debug", "presence forwarded to "..to_jid..": "..tostring(presence_fwd)) module:send(presence_fwd) -- cache used to avoid to send several times the same stanza priv_session.last_presence = presence end module:hook("presence/bare", function(event) if presence_man_ent:empty() and presence_roster:empty() then return; end local stanza = event.stanza if stanza.attr.type == nil or stanza.attr.type == "unavailable" then if not stanza.attr.to then for entity in presence_man_ent:items() do if stanza.attr.from ~= entity then forward_presence(stanza, entity); end end else -- directed presence -- we ignore directed presences from our own host, as we already have them local _, from_host = jid.split(stanza.attr.from) if hosts[from_host] then return; end -- we don't send several time the same presence, as recommended in §7 #2 if priv_session.last_presence and same_presences(priv_session.last_presence, stanza) then return end for entity in presence_roster:items() do if stanza.attr.from ~= entity then forward_presence(stanza, entity); end end end end end, 150)
--[[function VehicleFixes() setModelHandling(568, "maxVelocity", 110) -- Sanchez setModelHandling(522, "maxVelocity", 160) -- NRG-500 setModelHandling(510, "maxVelocity", 60) -- Mountain Bike setModelHandling(509, "maxVelocity", 55) -- Bike setModelHandling(481, "maxVelocity", 55) -- BMX setModelHandling(581, "maxVelocity", 140) -- BF-400 setModelHandling(521, "maxVelocity", 150) -- FCR-900 setModelHandlingd(521, "maxVelocity", 145) -- PCJ-600 setModelHandlingd(463, "maxVelocity", 140) -- Freeway setModelHandlingd(486, "maxVelocity", 130) -- Wayfarer setModelHandlingd(448, "maxVelocity", 80) -- Pizzaboy setModelHandlingd(462, "maxVelocity", 90) -- Pizzaboy setModelHandlingd(471, "maxVelocity", 120) -- Quad setModelHandlingd(523, "maxVelocity", 160) -- HPV1000 end addEventHandler("onResourceStart", getResourceRootElement(getThisResource()), function() VehicleFixes() setTimer (VehicleFixes, 1000, 1) end )]]
-- https://github.com/ttys3/nvim-blamer.lua require'nvim-blamer'.setup { enable = false, -- you must set this to true in order to show the blame info prefix = '', -- you can cusomize it to any thing, unicode emoji, even disable it, just set to empty lua string format = '%committer, %committer-time-human • %summary', auto_hide = false, -- set this to true will enable delay hide even you do not have the cursor moved hide_delay = 3000, -- this is the delay time in milliseconds for delay auto hide show_error = false, -- set to true to show any possible error (just for debug problems) } vim.call('nvimblamer#auto') local nvim_set_keymap = vim.api.nvim_set_keymap local opts = {noremap = true, silent = true} nvim_set_keymap('n', '<leader>gb', ':NvimBlamerToggle<CR>', opts)