content
stringlengths
5
1.05M
-- perf local tconcat = table.concat local PostgreSqlHelpers = {} -- build location execute name function PostgreSqlHelpers.location_for(options) name = { 'gin', options.adapter, options.host, (options.port or ''), options.database, } return tconcat(name, '|'):gsub('[^%w|]', '_') end function PostgreSqlHelpers.execute_location_for(options) name = { PostgreSqlHelpers.location_for(options), 'execute' } return tconcat(name, '|'):gsub('[^%w|]', '_') end return PostgreSqlHelpers
LPCONFIG = { DISMOUNT = true, CAM = false, GINV = true, FINV = true, SINV = nil, DINV = true, SUMM = true, EBG = true, LBG = true, QBG = true, RBG = true, SBG = false, AQUE = true, LOOT = true, EPLATE = false, FPLATE = false, HPLATE = false, RIGHT = true, ZG = 1, DUEL = false, NOSAVE = false, GREEN = 2, SPECIALKEY = true, WORLDDUNGEON = false, WORLDRAID = false, WORLDBG = false, WORLDUNCHECK = nil, SPAM = true, SPAM_UNCOMMON = true, SPAM_RARE = true, SHIFTSPLIT = true, REZ = true, GOSSIP = true, SALVA = false } BINDING_HEADER_LP_HEADER = "_LazyPig"; BINDING_NAME_LOGOUT = "Logout"; BINDING_NAME_UNSTUCK = "Unstuck"; BINDING_NAME_RELOAD = "Reaload UI"; BINDING_NAME_DUEL = "Target WSG EFC/Duel Request-Cancel"; BINDING_NAME_WSGDROP = "Drop WSG Flag/Remove Slow Fall"; BINDING_NAME_MENU = "_LazyPig Menu"; local Original_SelectGossipActiveQuest = SelectGossipActiveQuest; local Original_SelectGossipAvailableQuest = SelectGossipAvailableQuest; local Original_SelectActiveQuest = SelectActiveQuest; local Original_SelectAvailableQuest = SelectAvailableQuest; local OriginalLootFrame_OnEvent = LootFrame_OnEvent; local OriginalLootFrame_Update = LootFrame_Update; local OriginalUseContainerItem = UseContainerItem; local Original_SetItemRef = SetItemRef; local Original_ChatFrame_OnEvent = ChatFrame_OnEvent; local Original_StaticPopup_OnShow = StaticPopup_OnShow; local roster_task_refresh = 0 local last_click = 0 local delayaction = 0 local tradedelay = 0 local bgstatus = 0 local save_check = 0 local save_time = 0 local tmp_splitval = 1 local passpopup = 0 local ctrltime = 0 local alttime = 0 local shift_time = 0 local ctrlalttime = 0 local ctrlshifttime = 0 local altshifttime = 0 local greenrolltime = 0 local timer_split = false local player_summon_confirm = false local player_summon_message = false local player_bg_confirm = false local player_bg_message = false local afk_active = false local dnd_active = false local duel_active = false local merchantstatus = false local tradestatus = false local mailstatus = false local auctionstatus = false local auctionbrowse = false local bankstatus = false local channelstatus = false local battleframe = false local wsgefc = nil local WHITE = "|cffffffff" local RED = "|cffff0000" local GREEN = "|cff00ff00" local BLUE = "|cff00eeee" local ScheduleButton = {} local ScheduleFunction = {} local ScheduleSplit = {} local QuestRecord = {} local ActiveQuest = {} local AvailableQuest = {} local GreySell = {} local ChatMessage = {{}, {}, INDEX = 1} local ScheduleSplit = {} local ScheduleSplitCount = {} ScheduleSplit.active = nil ScheduleSplit.sslot = {} ScheduleSplit.dbag = {} ScheduleSplit.dslot = {} ScheduleSplit.sbag = {} ScheduleSplit.count = {} local LazyPigMenuObjects = {} local LazyPigMenuStrings = { [00]= "Need", [01]= "Greed", [02]= "Pass", [10]= "Need", [11]= "Greed", [12]= "Pass", [20]= "Dungeon", [21]= "Raid", [22]= "Battleground", [23]= "Mute Permanently", [30]= "GuildMates", [31]= "Friends", [32]= "Strangers", [33]= "Idle while in BG or Queue", [40]= "Show Friends", [41]= "Show Enemies", [42]= "Hide if Unchecked", [50]= "Enter BG", [51]= "Leave BG", [52]= "Queue BG", [53]= "Auto Release", [54]= "Leader Queue Announce", [55]= "Block BG Quest Sharing", [60]= "Always", [61]= "Warrior Shield/Druid Bear", [70]= "Players' Spam", [71]= "Uncommon Roll", [72]= "Rare Roll", [73]= "Poor-Common-Money Loot", [90]= "Summon Auto Accept", [91]= "Loot Window Auto Position", [92]= "Improved Right Click", [93]= "Easy Split/Merge (Shift+Right_Click)", [94]= "Extended Camera Distance", [95]= "Special Key Combinations", [96]= "Duel Auto Decline (Shift to ByPass)", [97]= "Instance Resurrection Accept OOC", [98]= "Gossip Auto Processing", [99]= "Character Auto-Save", [100]= "Auto Dismount", [101]= "Chat Spam Filter" } function LazyPig_OnLoad() SelectGossipActiveQuest = LazyPig_SelectGossipActiveQuest; SelectGossipAvailableQuest = LazyPig_SelectGossipAvailableQuest; SelectActiveQuest = LazyPig_SelectActiveQuest; SelectAvailableQuest = LazyPig_SelectAvailableQuest; LootFrame_OnEvent = LazyPig_LootFrame_OnEvent; LootFrame_Update = LazyPig_LootFrame_Update; UseContainerItem = LazyPig_UseContainerItem; SetItemRef = LazyPig_SetItemRef_OnEvent; ChatFrame_OnEvent = LazyPig_ChatFrame_OnEvent; StaticPopup_OnShow = LazyPig_StaticPopup_OnShow; SLASH_LAZYPIG1 = "/lp"; SLASH_LAZYPIG2 = "/lazypig"; SlashCmdList["LAZYPIG"] = LazyPig_Command; this:RegisterEvent("ADDON_LOADED"); this:RegisterEvent("PLAYER_LOGIN") --this:RegisterEvent("PLAYER_ENTERING_WORLD") end function LazyPig_Command() if LazyPigOptionsFrame:IsShown() then LazyPigOptionsFrame:Hide() LazyPigKeybindsFrame:Hide() else LazyPigOptionsFrame:Show() if getglobal("LazyPigOptionsFrameKeibindsButton"):GetText() == "Hide Keybinds" then LazyPigKeybindsFrame:Show() end end end function LazyPig_OnUpdate() local current_time = GetTime(); local shiftstatus = IsShiftKeyDown(); local ctrlstatus = IsControlKeyDown(); local altstatus = IsAltKeyDown(); if shiftstatus then shift_time = current_time elseif altstatus and not ctrlstatus and current_time > alttime then alttime = current_time + 0.75 elseif not altstatus and ctrlstatus and current_time > ctrltime then ctrltime = current_time + 0.75 elseif not altstatus and not ctrlstatus or altstatus and ctrlstatus then ctrltime = 0 alttime = 0 end if ctrlstatus and not shiftstatus and altstatus and current_time > ctrlalttime then ctrlalttime = current_time + 0.75 elseif ctrlstatus and shiftstatus and not altstatus and current_time > ctrlshifttime then ctrlshifttime = current_time + 0.75 elseif not ctrlstatus and shiftstatus and altstatus and current_time > altshifttime then altshifttime = current_time + 0.75 elseif ctrlstatus and shiftstatus and altstatus then ctrlshifttime = 0 ctrlalttime = 0 altshifttime = 0 end if shift_time == current_time then if not (UnitExists("target") and UnitIsUnit("player", "target")) then -- elseif not battleframe then battleframe = current_time elseif (current_time - battleframe) > 3 then BattlefieldFrame:Show() battleframe = current_time end elseif battleframe then battleframe = nil end if LPCONFIG.SPECIALKEY then if ctrlstatus and shiftstatus and altstatus and current_time > delayaction then delayaction = current_time + 1 Logout(); elseif ctrlstatus and not shiftstatus and altstatus and not auctionstatus and not mailstatus and current_time > delayaction then if tradestatus then AcceptTrade(); elseif not tradestatus and UnitExists("target") and UnitIsPlayer("target") and UnitIsFriend("target", "player") and not UnitIsUnit("player", "target") and CheckInteractDistance("target", 2) and (current_time + 0.25) > ctrlalttime and current_time > tradedelay then InitiateTrade("target"); delayaction = current_time + 2 end elseif ctrlstatus and shiftstatus and not altstatus and UnitIsPlayer("target") and UnitIsFriend("target", "player") and current_time > delayaction and (current_time + 0.25) > ctrlshifttime then delayaction = current_time + 1.5 FollowUnit("target"); elseif not ctrlstatus and shiftstatus and altstatus and UnitIsPlayer("target") and current_time > delayaction and (current_time + 0.25) > altshifttime then delayaction = current_time + 1.5 InspectUnit("target"); end if ctrlstatus and not shiftstatus and altstatus or passpopup > current_time then if current_time > delayaction and not LazyPig_BindLootOpen() and not LazyPig_RollLootOpen() and LazyPig_GreenRoll() then delayaction = current_time + 1 elseif current_time > delayaction then for i=1,STATICPOPUP_NUMDIALOGS do local frame = getglobal("StaticPopup"..i) if frame:IsShown() then --DEFAULT_CHAT_FRAME:AddMessage(frame.which) if frame.which == "DEATH" and HasSoulstone() then getglobal("StaticPopup"..i.."Button2"):Click(); if passpopup < current_time then delayaction = current_time + 0.5 end elseif frame.which ~= "CONFIRM_SUMMON" and frame.which ~= "CONFIRM_BATTLEFIELD_ENTRY" and frame.which ~= "CAMP" and frame.which ~= "AREA_SPIRIT_HEAL" then --and release and getglobal("StaticPopup"..i.."Button1"):Click(); if passpopup < current_time then delayaction = current_time + 0.5 end end end end end end if ctrlstatus and not shiftstatus and altstatus then if current_time > delayaction then if auctionstatus and AuctionFrameAuctions and AuctionFrameAuctions:IsVisible() and AuctionsCreateAuctionButton then ScheduleButtonClick(AuctionsCreateAuctionButton, 0); elseif auctionstatus and AuctionFrameBrowse and AuctionFrameBrowse:IsVisible() and BrowseBuyoutButton then ScheduleButtonClick(BrowseBuyoutButton, 0.55); elseif CT_MailFrame and CT_MailFrame:IsVisible() and CT_MailFrame.num > 0 and strlen(CT_MailNameEditBox:GetText()) > 0 and CT_Mail_AcceptSendFrameSendButton then ScheduleButtonClick(CT_Mail_AcceptSendFrameSendButton, 1.25); elseif GMailFrame and GMailFrame:IsVisible() and GMailFrame.num > 0 and strlen(GMailSubjectEditBox:GetText()) > 0 and GMailAcceptSendFrameSendButton then ScheduleButtonClick(GMailAcceptSendFrameSendButton, 1.25); elseif mailstatus and SendMailFrame and SendMailFrame:IsVisible() and SendMailMailButton then ScheduleButtonClick(SendMailMailButton, 0); elseif mailstatus and OpenMailFrame and OpenMailFrame:IsVisible() then if OpenMailFrame.money and OpenMailMoneyButton then ScheduleButtonClick(OpenMailMoneyButton, 0); elseif OpenMailPackageButton then ScheduleButtonClick(OpenMailPackageButton, 0); end end end LazyPig_AutoLeaveBG(); elseif not ctrlstatus and shiftstatus and altstatus and current_time > delayaction then if auctionstatus and AuctionFrameBrowse and AuctionFrameBrowse:IsVisible() and BrowseBidButton then ScheduleButtonClick(BrowseBidButton, 0.55); end end end if merchantstatus and shiftstatus and current_time > last_click and not CursorHasItem() then last_click = current_time + 0.25 LazyPig_GreySellRepair(); end if shiftstatus or altstatus then if QuestFrameDetailPanel:IsVisible() then AcceptQuest(); end elseif QuestRecord["details"] and not shiftstatus then LazyPig_RecordQuest(); end if not afk_active and player_bg_confirm then Check_Bg_Status(); end if bgstatus ~= 0 and (bgstatus + 0.5) > current_time then bgstatus = 0 Check_Bg_Status() LazyPig_AutoLeaveBG() end if(current_time - roster_task_refresh) > 29 then roster_task_refresh = current_time GuildRoster(); ChatSpamClean(); end if save_time ~= 0 and (current_time - save_time) > 3 and not GetBattlefieldWinner() and not UnitAffectingCombat("player") then save_check = current_time save_time = 0 SaveData(); end if player_summon_confirm then LazyPig_AutoSummon(); end LazyPig_CheckSalvation(); ScheduleButtonClick(); ScheduleFunctionLaunch(); ScheduleItemSplit(); LazyPig_WatchSplit(); end function ScheduleButtonClick(button, delay) local current_time = GetTime() if button and not ScheduleButton[button] then delay = delay or 0.75 ScheduleButton[button] = current_time + delay else for blockindex,blockmatch in pairs(ScheduleButton) do if current_time < delayaction then ScheduleButton[blockindex] = nil elseif current_time >= blockmatch then blockindex:Click() passpopup = current_time + 0.75 ScheduleButton[blockindex] = nil end end end end function ScheduleFunctionLaunch(func, delay) local current_time = GetTime() if func and not ScheduleFunction[func] then delay = delay or 0.75 ScheduleFunction[func] = current_time + delay else for blockindex,blockmatch in pairs(ScheduleFunction) do if current_time >= blockmatch then blockindex() ScheduleFunction[blockindex] = nil end end end end function LazyPig_OnEvent(event) if (event == "ADDON_LOADED") and (arg1 == "_LazyPig") then local LP_TITLE = GetAddOnMetadata("_LazyPig", "Title") local LP_VERSION = GetAddOnMetadata("_LazyPig", "Version") local LP_AUTHOR = GetAddOnMetadata("_LazyPig", "Author") DEFAULT_CHAT_FRAME:AddMessage(LP_TITLE .. " v" .. LP_VERSION .. " by " .."|cffFF0066".. LP_AUTHOR .."|cffffffff".. " loaded, type".."|cff00eeee".." /lp".."|cffffffff for options") elseif (event == "PLAYER_LOGIN") then --if (event == "PLAYER_ENTERING_WORLD") then -- this:UnregisterEvent("PLAYER_ENTERING_WORLD") this:RegisterEvent("CHAT_MSG") this:RegisterEvent("CHAT_MSG_SYSTEM") this:RegisterEvent("PARTY_INVITE_REQUEST") this:RegisterEvent("CONFIRM_SUMMON") this:RegisterEvent("RESURRECT_REQUEST") this:RegisterEvent("UPDATE_BATTLEFIELD_STATUS") this:RegisterEvent("CHAT_MSG_BG_SYSTEM_ALLIANCE") this:RegisterEvent("CHAT_MSG_BG_SYSTEM_HORDE") this:RegisterEvent("CHAT_MSG_BG_SYSTEM_NEUTRAL") this:RegisterEvent("BATTLEFIELDS_SHOW") this:RegisterEvent("GOSSIP_SHOW") this:RegisterEvent("QUEST_GREETING") this:RegisterEvent("UI_ERROR_MESSAGE") this:RegisterEvent("CHAT_MSG_LOOT") --this:RegisterEvent("CHAT_MSG_MONEY") this:RegisterEvent("QUEST_PROGRESS") this:RegisterEvent("QUEST_COMPLETE") this:RegisterEvent("START_LOOT_ROLL") this:RegisterEvent("DUEL_REQUESTED") this:RegisterEvent("MERCHANT_SHOW") this:RegisterEvent("MERCHANT_CLOSED") this:RegisterEvent("TRADE_SHOW") this:RegisterEvent("TRADE_CLOSED") this:RegisterEvent("MAIL_SHOW") this:RegisterEvent("MAIL_CLOSED") this:RegisterEvent("AUCTION_HOUSE_SHOW") this:RegisterEvent("AUCTION_HOUSE_CLOSED") this:RegisterEvent("BANKFRAME_OPENED") this:RegisterEvent("BANKFRAME_CLOSED") this:RegisterEvent("ZONE_CHANGED_NEW_AREA") this:RegisterEvent("PLAYER_UNGHOST") this:RegisterEvent("PLAYER_DEAD") this:RegisterEvent("PLAYER_AURAS_CHANGED") this:RegisterEvent("UPDATE_BONUS_ACTIONBAR") this:RegisterEvent("UNIT_INVENTORY_CHANGED") this:RegisterEvent("UI_INFO_MESSAGE") LazyPigOptionsFrame = LazyPig_CreateOptionsFrame() LazyPigKeybindsFrame = LazyPig_CreateKeybindsFrame() LazyPig_CheckSalvation(); Check_Bg_Status(); LazyPig_AutoLeaveBG(); LazyPig_AutoSummon(); ScheduleFunctionLaunch(LazyPig_ZoneCheck, 6); ScheduleFunctionLaunch(LazyPig_ZoneCheck2, 7); ScheduleFunctionLaunch(LazyPig_RefreshNameplates, 0.25); MailtoCheck(); if LPCONFIG.CAM then SetCVar("cameraDistanceMax",50) end if LPCONFIG.LOOT then UIPanelWindows["LootFrame"] = nil end QuestRecord["index"] = 0 elseif (LPCONFIG.SALVA and (event == "PLAYER_AURAS_CHANGED" or event == "UPDATE_BONUS_ACTIONBAR" and LazyPig_PlayerClass("Druid", "player") or event == "UNIT_INVENTORY_CHANGED")) then LazyPig_CheckSalvation() elseif(event == "DUEL_REQUESTED") then duel_active = true if LPCONFIG.DUEL and not IsShiftKeyDown() then --dnd_active and duel_active = nil CancelDuel() UIErrorsFrame:AddMessage(arg1.." - Duel Cancelled") end elseif(event == "PLAYER_DEAD") then if LPCONFIG.RBG and LazyPig_BG() then RepopMe(); end elseif(event == "ZONE_CHANGED_NEW_AREA" or event == "PLAYER_UNGHOST") then if event == "ZONE_CHANGED_NEW_AREA" then tradestatus = nil mailstatus = nil auctionstatus = nil bankstatus = nil wsgefc = nil end ScheduleFunctionLaunch(LazyPig_RefreshNameplates, 0.25) ScheduleFunctionLaunch(LazyPig_ZoneCheck, 5) ScheduleFunctionLaunch(LazyPig_ZoneCheck, 6) --DEFAULT_CHAT_FRAME:AddMessage(event); elseif(event == "BANKFRAME_OPENED") then bankstatus = true tmp_splitval = 1 elseif(event == "BANKFRAME_CLOSED") then bankstatus = false LazyPig_EndSplit() elseif(event == "AUCTION_HOUSE_SHOW") then auctionstatus = true auctionbrowse = nil tmp_splitval = 1 elseif(event == "AUCTION_HOUSE_CLOSED") then auctionstatus = false LazyPig_EndSplit() elseif(event == "MAIL_SHOW") then mailstatus = true tmp_splitval = 1 elseif(event == "MAIL_CLOSED") then mailstatus = false LazyPig_EndSplit() elseif(event == "MERCHANT_SHOW") then merchantstatus = true GreySell = {} elseif(event == "MERCHANT_CLOSED") then merchantstatus = false elseif(event == "TRADE_SHOW") then tradestatus = true tmp_splitval = 1 elseif(event == "TRADE_CLOSED") then tradedelay = GetTime() + 1 tradestatus = false LazyPig_EndSplit() elseif(event == "START_LOOT_ROLL") then LazyPig_ZGRoll(arg1) elseif(event == "CHAT_MSG_LOOT") then if (string.find(arg1 ,"You won") or string.find(arg1 ,"You receive")) and (string.find(arg1 ,"cffa335e") or string.find(arg1, "cff0070d") or string.find(arg1, "cffff840")) and not string.find(arg1 ,"Bijou") and not string.find(arg1 ,"Idol") and not string.find(arg1 ,"Shard") then save_time = GetTime() end elseif(event == "UI_ERROR_MESSAGE") then if(string.find(arg1, "mounted") or string.find(arg1, "while silenced")) and LPCONFIG.DISMOUNT then UIErrorsFrame:Clear() LazyPig_Dismount() end elseif (event == "UI_INFO_MESSAGE") then if string.find(arg1 ,"Duel cancelled") then duel_active = nil end elseif (event == "CHAT_MSG_SYSTEM") then if arg1 == CLEARED_DND or arg1 == CLEARED_AFK then dnd_active = false afk_active = false Check_Bg_Status() elseif(string.find(arg1, string.sub(MARKED_DND, 1, string.len(MARKED_DND) -3))) then afk_active = false dnd_active = true --if LPCONFIG.DUEL then CancelDuel() UIErrorsFrame:AddMessage("Duel Decline Atctive - DND") end elseif(string.find(arg1, string.sub(MARKED_AFK, 1, string.len(MARKED_AFK) -2))) then afk_active = true if LPCONFIG.EBG and not LazyPig_Raid() and not LazyPig_Dungeon() then UIErrorsFrame:AddMessage("Auto Join BG Inactive - AFK") end elseif string.find(arg1, "There is no such command") and (GetTime() - save_check) < 1 then LPCONFIG.NOSAVE = GetRealmName() DEFAULT_CHAT_FRAME:AddMessage("LazyPig:"..RED.."Auto Save Disabled - Command not Supported"); elseif LPCONFIG.AQUE and string.find(arg1 ,"Queued") and UnitIsPartyLeader("player") then if UnitInRaid("player") then SendChatMessage(arg1, "RAID"); elseif GetNumPartyMembers() > 1 then SendChatMessage(arg1, "PARTY"); end elseif string.find(arg1 ,"completed.") then LazyPig_FixQuest(arg1) QuestRecord["progress"] = nil elseif string.find(arg1 ,"Duel starting:") or string.find(arg1 ,"requested a duel") then duel_active = true elseif string.find(arg1 ,"in a duel") then duel_active = nil end elseif(event == "QUEST_GREETING") then ActiveQuest = {} AvailableQuest = {} for i=1, GetNumActiveQuests() do ActiveQuest[i] = GetActiveTitle(i).." "..GetActiveLevel(i) end for i=1, GetNumAvailableQuests() do AvailableQuest[i] = GetAvailableTitle(i).." "..GetAvailableLevel(i) end LazyPig_ReplyQuest(event); elseif(event == "GOSSIP_SHOW") then local GossipOptions = {}; local dsc = nil local gossipnr = nil local gossipbreak = nil local processgossip = IsShiftKeyDown() or LPCONFIG.GOSSIP dsc,GossipOptions[1],_,GossipOptions[2],_,GossipOptions[3],_,GossipOptions[4],_,GossipOptions[5] = GetGossipOptions() ActiveQuest = LazyPig_ProcessQuests(GetGossipActiveQuests()) AvailableQuest = LazyPig_ProcessQuests(GetGossipAvailableQuests()) if QuestRecord["qnpc"] ~= UnitName("target") then QuestRecord["index"] = 0 QuestRecord["qnpc"] = UnitName("target") end if #AvailableQuest ~= 0 or #ActiveQuest ~= 0 then gossipbreak = true end for i=1, getn(GossipOptions) do if GossipOptions[i] == "binder" then local bind = GetBindLocation(); if not (bind == GetSubZoneText() or bind == GetZoneText() or bind == GetRealZoneText() or bind == GetMinimapZoneText()) then gossipbreak = true end elseif gossipnr then gossipbreak = true elseif (GossipOptions[i] == "trainer" or GossipOptions[i] == "vendor" and processgossip or GossipOptions[i] == "battlemaster" and (LPCONFIG.QBG or processgossip) or GossipOptions[i] == "gossip" and (IsAltKeyDown() or IsShiftKeyDown() or string.find(dsc, "Teleport me to the Molten Core") and processgossip)) then gossipnr = i elseif GossipOptions[i] == "taxi" and processgossip then gossipnr = i LazyPig_Dismount(); end end if not gossipbreak and gossipnr then SelectGossipOption(gossipnr); else LazyPig_ReplyQuest(event); end elseif(event == "QUEST_PROGRESS" or event == "QUEST_COMPLETE") then LazyPig_ReplyQuest(event); elseif (event == "CHAT_MSG_BG_SYSTEM_ALLIANCE" or event == "CHAT_MSG_BG_SYSTEM_HORDE") then --DEFAULT_CHAT_FRAME:AddMessage(event.." - "..arg1); LazyPig_Track_EFC(arg1) elseif(event == "UPDATE_BATTLEFIELD_STATUS" and not afk_active or event == "CHAT_MSG_BG_SYSTEM_NEUTRAL" and arg1 and string.find(arg1, "wins!")) then bgstatus = GetTime() elseif(event == "BATTLEFIELDS_SHOW") then LazyPig_QueueBG(); elseif (event == "CONFIRM_SUMMON") then LazyPig_AutoSummon(); elseif(event == "PARTY_INVITE_REQUEST") then local check1 = not LPCONFIG.DINV or LPCONFIG.DINV and not LazyPig_BG() and not LazyPig_Queue() local check2 = LPCONFIG.GINV and IsGuildMate(arg1) or LPCONFIG.FINV and IsFriend(arg1) or not IsGuildMate(arg1) and not IsFriend(arg1) and LPCONFIG.SINV if check1 and check2 then AcceptGroupInvite(); end elseif(event == "RESURRECT_REQUEST" and LPCONFIG.REZ) then UIErrorsFrame:AddMessage(arg1.." - Resurrection") TargetByName(arg1, true) if GetCorpseRecoveryDelay() == 0 and (LazyPig_Raid() or LazyPig_Dungeon() or LazyPig_BG()) and UnitIsPlayer("target") and UnitIsVisible("target") and not UnitAffectingCombat("target") then AcceptResurrect() StaticPopup_Hide("RESURRECT_NO_TIMER"); StaticPopup_Hide("RESURRECT_NO_SICKNESS"); StaticPopup_Hide("RESURRECT"); end TargetLastTarget(); end --DEFAULT_CHAT_FRAME:AddMessage(event); end function LazyPig_StaticPopup_OnShow() if this.which == "QUEST_ACCEPT" and LazyPig_BG() and LPCONFIG.SBG then UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage("Quest Blocked Successfully"); this:Hide(); else Original_StaticPopup_OnShow(); end end function MailtoCheck(msg) if MailTo_Option then -- to avoid conflicts with mailto addon local disable = LPCONFIG.RIGHT or LPCONFIG.SHIFT MailTo_Option.noshift = disable MailTo_Option.noauction = disable MailTo_Option.notrade = disable MailTo_Option.noclick = disable if msg then DEFAULT_CHAT_FRAME:AddMessage("_LazyPig: Warning Improved Right Click and Easy Split/Merge features may override MailTo addon functionality !") end end end function LazyPig_Text(txt) if txt then LazyPigText:SetTextColor(0, 1, 0) LazyPigText:SetText(txt) LazyPigText:Show() else LazyPigText:SetText() LazyPigText:Hide() end end --code taken from quickloot local function LazyPig_ItemUnderCursor() if LPCONFIG.LOOT then local index; local x, y = GetCursorPosition(); local scale = LootFrame:GetEffectiveScale(); x = x / scale; y = y / scale; LootFrame:ClearAllPoints(); for index = 1, LOOTFRAME_NUMBUTTONS, 1 do local button = getglobal("LootButton"..index); if( button:IsVisible() ) then x = x - 42; y = y + 56 + (40 * index); LootFrame:SetPoint("TOPLEFT", "UIParent", "BOTTOMLEFT", x, y); return; end end if LootFrameDownButton:IsVisible() then x = x - 158; y = y + 223; else if GetNumLootItems() == 0 then HideUIPanel(LootFrame); return end x = x - 173; y = y + 25; end LootFrame:SetPoint("TOPLEFT", "UIParent", "BOTTOMLEFT", x, y); end end function LazyPig_LootFrame_OnEvent(event) OriginalLootFrame_OnEvent(event); if(event == "LOOT_SLOT_CLEARED") then LazyPig_ItemUnderCursor(); end end function LazyPig_LootFrame_Update() OriginalLootFrame_Update(); LazyPig_ItemUnderCursor(); end function IsFriend(name) for i = 1, GetNumFriends() do if GetFriendInfo(i) == name then return true end end return nil end function IsGuildMate(name) if IsInGuild() then local ngm=GetNumGuildMembers() for i=1, ngm do n, rank, rankIndex, level, class, zone, note, officernote, online, status, classFileName = GetGuildRosterInfo(i); if strlower(n) == strlower(name) then return true end end end return nil end function AcceptGroupInvite() AcceptGroup(); StaticPopup_Hide("PARTY_INVITE"); PlaySoundFile("Sound\\Doodad\\BellTollNightElf.wav"); UIErrorsFrame:AddMessage("Group Auto Accept"); end function LazyPig_AutoSummon() local keyenter = IsAltKeyDown() and IsControlKeyDown() and not tradestatus and not mailstatus and not auctionstatus and GetTime() > delayaction and GetTime() > (tradedelay + 0.5) if LPCONFIG.SUMM then local expireTime = GetSummonConfirmTimeLeft() if not player_summon_message and expireTime ~= 0 then player_summon_message = true player_summon_confirm = true DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Auto Summon in "..math.floor(expireTime).."s", 1.0, 1.0, 0.0); elseif expireTime <= 3 or keyenter then player_summon_confirm = false player_summon_message = false for i=1,STATICPOPUP_NUMDIALOGS do local frame = getglobal("StaticPopup"..i) if frame.which == "CONFIRM_SUMMON" and frame:IsShown() then ConfirmSummon(); delayaction = GetTime() + 0.75 StaticPopup_Hide("CONFIRM_SUMMON"); end end elseif expireTime == 0 then player_summon_confirm = false player_summon_message = false end end end function Check_Bg_Status() local bgStatus = {}; local player_bg_active = false local player_bg_request = false for i=1, MAX_BATTLEFIELD_QUEUES do local status, mapName, instanceID = GetBattlefieldStatus(i); bgStatus[i] = {}; bgStatus[i]["status"] = status; bgStatus[i]["map"] = mapName; bgStatus[i]["id"] = instanceID; if(status == "confirm" ) then player_bg_request = true elseif((status == "active") and not (mapName == "Eastern Kingdoms") and not (mapName == "Kalimdor") and not (mapName == "Outland")) then player_bg_active = true end end player_bg_confirm = player_bg_request if(player_bg_message and not player_bg_active and not player_bg_request) then player_bg_message = false end if(not player_bg_active and player_bg_request) then local index = 1 while bgStatus[index] do if(bgStatus[index]["status"] == "confirm" ) then LazyPig_AutoJoinBG(index, bgStatus[index]["map"]); end index = index + 1 end end end function LazyPig_QueueBG() if LPCONFIG.QBG then for i=1, MAX_BATTLEFIELD_QUEUES do local status = GetBattlefieldStatus(i); if IsShiftKeyDown() and (status == "queued" or status == "confirm") then AcceptBattlefieldPort(i,nil); end end if (GetNumPartyMembers() > 0 or GetNumRaidMembers() > 0) and IsPartyLeader() then JoinBattlefield(0,1); else JoinBattlefield(0); end ClearTarget(); BattlefieldFrameCancelButton:Click() end end function LazyPig_AutoJoinBG(index, map_name) local keyenter = IsAltKeyDown() and IsControlKeyDown() and not tradestatus and not mailstatus and not auctionstatus and GetTime() > delayaction and GetTime() > (tradedelay + 0.5) if LPCONFIG.EBG or keyenter then local expireTime = GetBattlefieldPortExpiration(index)/1000 expireTime = math.floor(expireTime); if not player_bg_message and expireTime > 3 and GetTime() > delayaction then player_bg_message = true DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Auto Join ".. map_name.." in "..expireTime.."s", 1.0, 1.0, 0.0) elseif expireTime <= 3 or keyenter then AcceptBattlefieldPort(index, true); StaticPopup_Hide("CONFIRM_BATTLEFIELD_ENTRY") delayaction = GetTime() + 0.75 if player_bg_message then player_bg_message = false end end end end function LazyPig_AutoLeaveBG() local keyenter = IsAltKeyDown() and IsControlKeyDown() if LPCONFIG.LBG or keyenter then local bg_winner = GetBattlefieldWinner() local winner_name = "Alliance" if bg_winner ~= nil then save_time = GetTime() + 15 if bg_winner == 0 then winner_name = "Horde" end UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage(winner_name.." Wins"); LeaveBattlefield(); end end end function SaveData() if LPCONFIG.NOSAVE ~= GetRealmName() then SendChatMessage(".save", "SAY"); UIErrorsFrame:Clear() UIErrorsFrame:AddMessage("Character Saved"); end end function LazyPig_BagReturn(find) local link = nil local bagslots = nil for bag=0,NUM_BAG_FRAMES do bagslots = GetContainerNumSlots(bag) if bagslots and bagslots > 0 then for slot=1,bagslots do link = GetContainerItemLink(bag, slot) if not find and not link or find and link and string.find(link, find) then return bag, slot end end end end return nil end function LazyPig_ZGRoll(id) RollReturn = function() local txt = "" if LPCONFIG.ZG == 1 then txt = "NEED" elseif LPCONFIG.ZG == 2 then txt = "GREED" elseif LPCONFIG.ZG == 0 then txt = "PASS" end return txt end if LPCONFIG.ZG then local _, name, _, quality = GetLootRollItemInfo(id); if string.find(name ,"Hakkari Bijou") or string.find(name ,"Coin") or string.find(name ,"Mark of the Illidari") or string.find(name ,"Amani Hex Stick") or string.find(name ,"Fel Armament") or string.find(name ,"Arcane Tome") then RollOnLoot(id, LPCONFIG.ZG); local _, _, _, hex = GetItemQualityColor(quality) DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Auto "..hex..RollReturn().." "..GetLootRollItemLink(id)) return end if string.find(name ,"Heart of Darkness") then RollOnLoot(id,0); return end end end function LazyPig_GreenRoll() RollReturn = function() local txt = "" if LPCONFIG.GREEN == 1 then txt = "NEED" elseif LPCONFIG.GREEN == 2 then txt = "GREED" elseif LPCONFIG.GREEN == 0 then txt = "PASS" end return txt end local pass = nil if LPCONFIG.GREEN then for i=1, NUM_GROUP_LOOT_FRAMES do local frame = getglobal("GroupLootFrame"..i); if frame:IsVisible() then local id = frame.rollID local _, name, _, quality = GetLootRollItemInfo(id); if quality == 2 then RollOnLoot(id, LPCONFIG.GREEN); local _, _, _, hex = GetItemQualityColor(quality) greenrolltime = GetTime() + 1 DEFAULT_CHAT_FRAME:AddMessage("LazyPig: "..hex..RollReturn().."|cffffffff Roll "..GetLootRollItemLink(id)) pass = true end end end end return pass end function LazyPig_GreySellRepair() local bag, slot = LazyPig_BagReturn("ff9d9d9d") if bag and slot then local _, _, locked = GetContainerItemInfo(bag, slot) if bag and slot and not locked then UseContainerItem(bag,slot) if not(GreySell.bag == bag and GreySell.slot == slot) then DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Selling "..GetContainerItemLink(bag, slot)) GreySell.bag = bag GreySell.slot = slot end end elseif CanMerchantRepair() then local rcost = GetRepairAllCost() if rcost and rcost ~= 0 then if rcost > GetMoney() then DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Not Enough Money to Repair") return end GreySell.repair = rcost RepairAllItems(); elseif GreySell.repair and rcost == 0 then local gold = floor(abs(GreySell.repair / 10000)) local silver = floor(abs(mod(GreySell.repair / 100, 100))) local copper = floor(abs(mod(GreySell.repair, 100))) local COLOR_COPPER = "|cffeda55f" local COLOR_SILVER = "|cffc7c7cf" local COLOR_GOLD = "|cffffd700" DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Repairing All Items "..COLOR_GOLD..gold.."g "..COLOR_SILVER..silver.."s "..COLOR_COPPER..copper.."c") GreySell.repair = nil end end end function LazyPig_ProcessQuests(...) local quest = {} for i = 1, #arg, 2 do local count, title, level = i, arg[i], arg[i+1] if count > 1 then count = (count+1)/2 end quest[count] = title.." "..level end return quest end function LazyPig_PrepareQuestAutoPickup() if IsAltKeyDown() then GossipFrameCloseButton:Click(); ClearTarget(); end end function LazyPig_SelectGossipActiveQuest(index, norecord) if not norecord then LazyPig_RecordQuest(ActiveQuest[index]) end Original_SelectGossipActiveQuest(index); end function LazyPig_SelectGossipAvailableQuest(index, norecord) if not norecord then LazyPig_RecordQuest(AvailableQuest[index]) end Original_SelectGossipAvailableQuest(index); end function LazyPig_SelectActiveQuest(index, norecord) if not norecord then LazyPig_RecordQuest(ActiveQuest[index]) end Original_SelectActiveQuest(index); end function LazyPig_SelectAvailableQuest(index, norecord) if not norecord then LazyPig_RecordQuest(AvailableQuest[index]) end Original_SelectAvailableQuest(index); end function LazyPig_FixQuest(quest, annouce) if not QuestRecord["details"] then annouce = true end if QuestRecord["details"] and annouce then UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage("Recording: "..QuestRecord["details"]) end end function LazyPig_RecordQuest(qdetails) if IsShiftKeyDown() and qdetails then if QuestRecord["details"] ~= qdetails then QuestRecord["details"] = qdetails end LazyPig_FixQuest(QuestRecord["details"], true) elseif not IsShiftKeyDown() and QuestRecord["details"] then QuestRecord["details"] = nil end QuestRecord["progress"] = true end function LazyPig_ReplyQuest(event) if IsShiftKeyDown() or IsAltKeyDown() then if QuestRecord["details"] then UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage("Replaying: "..QuestRecord["details"]) end if event == "GOSSIP_SHOW" then if QuestRecord["details"] then for blockindex,blockmatch in pairs(ActiveQuest) do if blockmatch == QuestRecord["details"] then Original_SelectGossipActiveQuest(blockindex) return end end for blockindex,blockmatch in pairs(AvailableQuest) do if blockmatch == QuestRecord["details"] then Original_SelectGossipAvailableQuest(blockindex) return end end elseif #ActiveQuest == 0 and #AvailableQuest == 1 or IsAltKeyDown() and #AvailableQuest > 0 then LazyPig_SelectGossipAvailableQuest(1, true) elseif #ActiveQuest == 1 and #AvailableQuest == 0 or IsAltKeyDown() and #ActiveQuest > 0 then local nr = #ActiveQuest if QuestRecord["progress"] and (nr - QuestRecord["index"]) > 0 then --DEFAULT_CHAT_FRAME:AddMessage("++quest dec nr - "..nr.." index - "..QuestRecord["index"]) QuestRecord["index"] = QuestRecord["index"] + 1 nr = nr - QuestRecord["index"] end LazyPig_SelectGossipActiveQuest(nr, true) end elseif event == "QUEST_GREETING" then if QuestRecord["details"] then for blockindex,blockmatch in pairs(ActiveQuest) do if blockmatch == QuestRecord["details"] then Original_SelectActiveQuest(blockindex) return end end for blockindex,blockmatch in pairs(AvailableQuest) do if blockmatch == QuestRecord["details"] then Original_SelectAvailableQuest(blockindex) return end end elseif #ActiveQuest == 0 and #AvailableQuest == 1 or IsAltKeyDown() and #AvailableQuest > 0 then LazyPig_SelectAvailableQuest(1, true) elseif #ActiveQuest == 1 and #AvailableQuest == 0 or IsAltKeyDown() and #ActiveQuest > 0 then local nr = #ActiveQuest if QuestRecord["progress"] and (nr - QuestRecord["index"]) > 0 then --DEFAULT_CHAT_FRAME:AddMessage("--quest dec nr - "..nr.." index - "..QuestRecord["index"]) QuestRecord["index"] = QuestRecord["index"] + 1 nr = nr - QuestRecord["index"] end LazyPig_SelectActiveQuest(nr, true) end elseif event == "QUEST_PROGRESS" then CompleteQuest() elseif event == "QUEST_COMPLETE" and GetNumQuestChoices() == 0 then GetQuestReward(0) end end end function LazyPig_Dismount() Dismount(); end function LazyPig_DropWSGFlag_NoggBuff() local counter = 0 local tooltipfind1 = "Warsong Flag" local tooltipfind2 = "You feel light" local tooltipfind3 = "Slow Fall" while GetPlayerBuff(counter) >= 0 do local index, untilCancelled = GetPlayerBuff(counter) LazyPig_Buff_Tooltip:SetPlayerBuff(index) local desc = LazyPig_Buff_TooltipTextLeft1:GetText() if string.find(desc, tooltipfind1) or string.find(desc, tooltipfind3) then CancelPlayerBuff(counter) end desc = LazyPig_Buff_TooltipTextLeft2:GetText() if string.find(desc, tooltipfind2) then CancelPlayerBuff(counter) end counter = counter + 1 end end function LazyPig_ItemIsTradeable(bag, item) for i = 1, 29, 1 do getglobal("LazyPig_Buff_TooltipTextLeft" .. i):SetText(""); end LazyPig_Buff_Tooltip:SetBagItem(bag, item); for i = 1, LazyPig_Buff_Tooltip:NumLines(), 1 do local text = getglobal("LazyPig_Buff_TooltipTextLeft" .. i):GetText(); if ( text == ITEM_SOULBOUND ) then return nil elseif ( text == ITEM_BIND_QUEST ) then return nil elseif ( text == ITEM_CONJURED ) then return nil end end return true end function LazyPig_Raid() local t = GetRealZoneText() if t =="Molten Core" or t =="Blackwing Lair" or t =="Zul'Gurub" or t =="Ahn'Qiraj" or t =="Onyxia's Lair" or t =="Ruins of Ahn'Qiraj" or t =="Temple of Ahn'Qiraj" or t =="Naxxramas" or t =="Blackrock Spire" or t =="Black Temple" or t =="Karazhan" or t =="Zul'Aman" or t =="Hyjal Summit" or t =="Sunwell Plateau" or t =="Serpentshrine Cavern" or t =="The Eye" or t =="Magtheridon's Lair" or t =="Gruul's Lair" then return true end return false end function LazyPig_Dungeon() local t = GetRealZoneText() if t =="Dire Maul" or t =="Stratholme" or t =="Scholomance" or t =="Blackrock Depths" or t =="Sunken Temple" or t =="The Stockade" or t =="Zul'Farrak" or t =="Scarlet Monastery" or t =="Gnomeregan" or t =="The Deadmines" or t=="Blackfathom Deeps" or t=="Wailing Caverns" or t=="Razorfen Downs" or t=="Razorfen Kraul" or t=="The Underbog" or t =="The Slave Pens" or t =="The Steamvault" or t =="Magisters' Terrace" or t =="The Mechanar" or t =="The Botanica" or t =="The Arcatraz" or t =="Old Hillsbrad Foothills" or t =="The Black Morass" or t =="Hellfire Ramparts" or t =="The Blood Furnace" or t =="The Shattered Halls" or t =="Auchenai Crypts" or t =="Mana-Tombs" or t =="Sethekk Halls" or t =="Shadow Labyrinth" then return true end return false end function LazyPig_BG() local t = GetRealZoneText() if t == "Arathi Basin" or t == "Warsong Gulch" or t == "Alterac Valley" or t == "Eye of The Storm" then return true end return false end function LazyPig_Queue() for i=1, MAX_BATTLEFIELD_QUEUES do local status, mapName, instanceID = GetBattlefieldStatus(i); if(status == "confirm" or status == "active") then return true end end return nil end function LazyPig_EndSplit() timer_split = nil tmp_splitval = 1 LazyPig_Text() end function LazyPig_DecodeItemLink(link) if link then local found, _, id, name = string.find(link, "item:(%d+):.*%[(.*)%]") if found then id = tonumber(id) return name, id end end return nil end function LazyPig_WatchSplit(enable) local returnval = timer_split if LPCONFIG.SHIFTSPLIT then local time = GetTime() local txt_show = enable local ctrl = IsControlKeyDown() local alt = IsAltKeyDown() local duration = 9 if enable then timer_split = time + duration elseif timer_split then local boost = -0.006*tmp_splitval + 1 if auctionstatus then if AuctionFrameBrowse:IsVisible() then if not auctionbrowse then auctionbrowse = true LazyPig_EndSplit() return end else auctionbrowse = nil end end if time > timer_split or auctionstatus and AuctionFrameAuctions and not (AuctionFrameAuctions:IsVisible() or AuctionFrameBrowse:IsVisible()) or mailstatus and SendMailFrame and not SendMailFrame:IsVisible() and (not CT_MailFrame or CT_MailFrame and not CT_MailFrame:IsVisible()) and (not GMailFrame or GMailFrame and not GMailFrame:IsVisible()) then LazyPig_EndSplit() elseif (ctrl or alt) and time > last_click then local forcepass = (timer_split - duration + 0.6) > time if ctrl and alt then timer_split = time + duration - 1 return elseif alt and ((time + 0.1) > alttime or forcepass) and tmp_splitval < 100 then alttime = time + 0.125 tmp_splitval = tmp_splitval + 1 timer_split = time + duration last_click = 0.109*boost + time txt_show = true elseif ctrl and ((time + 0.1) > ctrltime or forcepass) and tmp_splitval > 1 then ctrltime = time + 0.125 tmp_splitval = tmp_splitval - 1 timer_split = time + duration last_click = 0.109*boost + time txt_show = true end end elseif auctionstatus and AuctionFrameAuctions and AuctionFrameAuctions:IsVisible() or mailstatus and SendMailFrame and SendMailFrame:IsVisible() or tradestatus or bankstatus or CT_MailFrame and CT_MailFrame:IsVisible() or GMailFrame and GMailFrame:IsVisible() then timer_split = time + duration - 1 txt_show = true end if txt_show then LazyPig_Text("- Ctrl "..tmp_splitval.." Alt +", duration) end end return returnval end function LazyPig_UseContainerItem(ParentID,ItemID) if LPCONFIG.SHIFTSPLIT and not CursorHasItem() and not merchantstatus and IsShiftKeyDown() and not IsAltKeyDown() then if(GetTime() - last_click) < 0.3 then return end local _, itemCount, locked = GetContainerItemInfo(ParentID, ItemID) if locked or not itemCount then return end if not LazyPig_WatchSplit(true) then return end last_click = GetTime() local ItemArray = {} local name, id = LazyPig_DecodeItemLink(GetContainerItemLink(ParentID,ItemID)) local _, _, _, _, _, _, maxstack = GetItemInfo(id) local out_slpit = tmp_splitval if out_slpit > maxstack then out_slpit = maxstack end local dcount = out_slpit local dbag = nil local dslot = nil local cursoritem = nil if itemCount < out_slpit then dbag, dslot = ParentID, ItemID dcount = out_slpit - itemCount cursoritem = true end if name then for b=0, NUM_BAG_FRAMES do local bagslots = GetContainerNumSlots(b) if bagslots and bagslots > 0 then for s=1, bagslots do local link = GetContainerItemLink(b, s) local n, d = LazyPig_DecodeItemLink(link) if not cursoritem or cursoritem and not (b == ParentID and s == ItemID) then if not link and not dbag and not dslot then dbag, dslot = b, s --DEFAULT_CHAT_FRAME:AddMessage(b.." "..s.." - scan mode1") elseif n then if n == name then --if (string.find(n, name) or n == name) then local _, c, l = GetContainerItemInfo(b, s) if not l then if not (itemCount < out_slpit) and not dbag and not dslot and c < out_slpit then dbag, dslot = b, s dcount = out_slpit - c --DEFAULT_CHAT_FRAME:AddMessage("b.." "..s.." count - "..c.." - "..scan mode2) elseif c ~= out_slpit or cursoritem then ItemArray[b.."_"..s] = c end end end end end end end end if not dbag or not dslot or CursorHasItem() then return end local escape = 0 while dcount > 0 do local sbag = nil local sslot = nil local score = nil local number = nil local index = nil for blockindex,blockmatch in pairs(ItemArray) do local x = nil local y = nil x = string.gsub(blockindex,"_(.+)","") x = tonumber(x) y = string.gsub(blockindex,"(.+)_","") y = tonumber(y) if not number or number > blockmatch or number == blockmatch and (x*10 + y) > score then sbag = x sslot = y score = 10*sbag + sslot number = blockmatch index = blockindex end end if sbag and sslot then local splitval = nil if (number - dcount) >= out_slpit then splitval = dcount elseif number > out_slpit then splitval = number - out_slpit elseif number < dcount then splitval = number else splitval = dcount end dcount = dcount - splitval ScheduleItemSplit(sbag, sslot, dbag, dslot, splitval) ItemArray[index] = nil --DEFAULT_CHAT_FRAME:AddMessage("Dest "..dbag.." - "..dslot.." From "..sbag.." - "..sslot.." - Count "..splitval) end if escape > 99 then --DEFAULT_CHAT_FRAME:AddMessage("LazPig_Split: Loop stop") return else escape = escape + 1 end end end return elseif LPCONFIG.RIGHT and tradestatus and not IsShiftKeyDown() and not IsAltKeyDown() and LazyPig_ItemIsTradeable(ParentID,ItemID) then PickupContainerItem(ParentID,ItemID) local slot = TradeFrame_GetAvailableSlot() if slot then ClickTradeButton(slot) end if CursorHasItem() then ClearCursor() end return elseif LPCONFIG.RIGHT and GMailFrame and GMailFrame:IsVisible() and not CursorHasItem() then local i local bag, item = ParentID,ItemID for i = 1, GMAIL_NUMITEMBUTTONS, 1 do if ( not getglobal("GMailButton" .. i).item ) then if ( GMail:ItemIsMailable(bag, item) ) then GMail:Print("GMail: Cannot attach item.", 1, 0.5, 0) return end PickupContainerItem(bag, item) --GMail.hooks["PickupContainerItem"].orig(bag, item) GMail:MailButton_OnClick(getglobal("GMailButton" .. i)) GMail:UpdateItemButtons() return end end elseif LPCONFIG.RIGHT and CT_MailFrame and CT_MailFrame:IsVisible() and not IsShiftKeyDown() and not IsAltKeyDown() then local bag, item = ParentID,ItemID if ( ( CT_Mail_GetItemFrame(bag, item) or ( CT_Mail_addItem and CT_Mail_addItem[1] == bag and CT_Mail_addItem[2] == item ) ) and not special ) then return; end if ( not CursorHasItem() ) then CT_MailFrame.bag = bag; CT_MailFrame.item = item; end if ( CT_MailFrame:IsVisible() and not CursorHasItem() ) then local i; for i = 1, CT_MAIL_NUMITEMBUTTONS, 1 do if ( not getglobal("CT_MailButton" .. i).item ) then local canMail = CT_Mail_ItemIsMailable(bag, item); if ( canMail ) then DEFAULT_CHAT_FRAME:AddMessage("<CTMod> Cannot attach item, item is " .. canMail, 1, 0.5, 0); return; end CT_oldPickupContainerItem(bag, item); CT_MailButton_OnClick(getglobal("CT_MailButton" .. i)); CT_Mail_UpdateItemButtons(); return; end end end elseif LPCONFIG.RIGHT and mailstatus and not IsShiftKeyDown() and not IsAltKeyDown() then if not LazyPig_ItemIsTradeable(ParentID,ItemID) then DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Cannot attach item", 1, 0.5, 0); return end if InboxFrame and InboxFrame:IsVisible() then MailFrameTab_OnClick(2); return end if SendMailFrame and SendMailFrame:IsVisible() then PickupContainerItem(ParentID,ItemID) ClickSendMailItemButton() if CursorHasItem() then ClearCursor() end return end elseif LPCONFIG.RIGHT and auctionstatus and not IsShiftKeyDown() and not IsAltKeyDown() then if not LazyPig_ItemIsTradeable(ParentID,ItemID) then DEFAULT_CHAT_FRAME:AddMessage("LazyPig: Cannot sell item", 1, 0.5, 0); return end if not AuctionFrameAuctions:IsVisible() then AuctionFrameTab3:Click() return end PickupContainerItem(ParentID,ItemID) ClickAuctionSellItemButton() if CursorHasItem() then ClearCursor() end return end OriginalUseContainerItem(ParentID,ItemID) end function ScheduleItemSplit(sbag, sslot, dbag, dslot, count) if sbag and sslot and dbag and dslot and count then local number = nil for blockindex,blockmatch in pairs(ScheduleSplitCount) do if not number or number < blockindex then number = blockindex end end if not number then number = 1 else number = number + 1 end --DEFAULT_CHAT_FRAME:AddMessage("Task Count - "..number) ScheduleSplitCount[number] = true ScheduleSplit.sbag[number] = sbag ScheduleSplit.sslot[number] = sslot ScheduleSplit.dbag[number] = dbag ScheduleSplit.dslot[number] = dslot ScheduleSplit.count[number] = count ScheduleSplit.active = true elseif ScheduleSplit.active then local number = nil for blockindex,blockmatch in pairs(ScheduleSplitCount) do if not number or number > blockindex then number = blockindex end end if number then last_click = GetTime() local _, _, lock = GetContainerItemInfo(ScheduleSplit.dbag[number], ScheduleSplit.dslot[number]) if not lock then --DEFAULT_CHAT_FRAME:AddMessage("Dest "..ScheduleSplit.dbag[number].." - "..ScheduleSplit.dslot[number].." From "..ScheduleSplit.sbag[number].." - "..ScheduleSplit.sslot[number].." - Count "..ScheduleSplit.count[number]) SplitContainerItem(ScheduleSplit.sbag[number], ScheduleSplit.sslot[number], ScheduleSplit.count[number]) PickupContainerItem(ScheduleSplit.dbag[number], ScheduleSplit.dslot[number]) ScheduleSplitCount[number] = nil end else ScheduleSplit.active = nil end end end function LazyPig_CreateLink(name, count, rgb) rgb = rgb or WHITE if(name ~= nil) then local color = rgb..name.."|r" local hlink = "[|Hlazypig:"..count.."|h"..color.."|h]"; return hlink end end function LazyPig_SetItemRef_OnEvent(link, text, button) if link and string.find(link, "lazypig:") then --local count = string.gsub(link,"lazypig:","") LazyPig_Command() else Original_SetItemRef(link, text, button) end end function LazyPig_RefreshNameplates() if LPCONFIG.EPLATE then ShowNameplates(); elseif LPCONFIG.HPLATE then HideNameplates(); end if LPCONFIG.FPLATE then ShowFriendNameplates(); elseif LPCONFIG.HPLATE then HideFriendNameplates(); end end function LazyPig_GetOption(num) local labelString = getglobal(this:GetName().."Text"); local label = LazyPigMenuStrings[num] or ""; LazyPigMenuObjects[num] = this if num == 00 and LPCONFIG.GREEN == 1 or num == 01 and LPCONFIG.GREEN == 2 or num == 02 and LPCONFIG.GREEN == 0 or num == 10 and LPCONFIG.ZG == 1 or num == 11 and LPCONFIG.ZG == 2 or num == 12 and LPCONFIG.ZG == 0 or num == 20 and LPCONFIG.WORLDDUNGEON or num == 21 and LPCONFIG.WORLDRAID or num == 22 and LPCONFIG.WORLDBG or num == 23 and LPCONFIG.WORLDUNCHECK or num == 30 and LPCONFIG.GINV or num == 31 and LPCONFIG.FINV or num == 32 and LPCONFIG.SINV or num == 33 and LPCONFIG.DINV or num == 40 and LPCONFIG.FPLATE or num == 41 and LPCONFIG.EPLATE or num == 42 and LPCONFIG.HPLATE or num == 50 and LPCONFIG.EBG or num == 51 and LPCONFIG.LBG or num == 52 and LPCONFIG.QBG or num == 53 and LPCONFIG.RBG or num == 54 and LPCONFIG.AQUE or num == 55 and LPCONFIG.SBG or num == 60 and LPCONFIG.SALVA == 1 or num == 61 and LPCONFIG.SALVA == 2 or num == 90 and LPCONFIG.SUMM or num == 70 and LPCONFIG.SPAM or num == 71 and LPCONFIG.SPAM_UNCOMMON or num == 72 and LPCONFIG.SPAM_RARE or num == 73 and LPCONFIG.SPAM_LOOT or num == 91 and LPCONFIG.LOOT or num == 92 and LPCONFIG.RIGHT or num == 93 and LPCONFIG.SHIFTSPLIT or num == 94 and LPCONFIG.CAM or num == 95 and LPCONFIG.SPECIALKEY or num == 96 and LPCONFIG.DUEL or num == 97 and LPCONFIG.REZ or num == 98 and LPCONFIG.GOSSIP or num == 99 and LPCONFIG.NOSAVE ~= GetRealmName() or num == 100 and LPCONFIG.DISMOUNT or num == 101 and LPCONFIG.SPAM or nil then this:SetChecked(true); else this:SetChecked(nil); end labelString:SetText(label); end function LazyPig_SetOption(num) local checked = this:GetChecked() if num == 00 then LPCONFIG.GREEN = 1 if not checked then LPCONFIG.GREEN = nil end LazyPigMenuObjects[01]:SetChecked(nil) LazyPigMenuObjects[02]:SetChecked(nil) elseif num == 01 then LPCONFIG.GREEN = 2 if not checked then LPCONFIG.GREEN = nil end LazyPigMenuObjects[00]:SetChecked(nil) LazyPigMenuObjects[02]:SetChecked(nil) elseif num == 02 then LPCONFIG.GREEN = 0 if not checked then LPCONFIG.GREEN = nil end LazyPigMenuObjects[00]:SetChecked(nil) LazyPigMenuObjects[01]:SetChecked(nil) elseif num == 10 then LPCONFIG.ZG = 1 if not checked then LPCONFIG.ZG = nil end LazyPigMenuObjects[11]:SetChecked(nil) LazyPigMenuObjects[12]:SetChecked(nil) elseif num == 11 then LPCONFIG.ZG= 2 if not checked then LPCONFIG.ZG = nil end LazyPigMenuObjects[10]:SetChecked(nil) LazyPigMenuObjects[12]:SetChecked(nil) elseif num == 12 then LPCONFIG.ZG = 0 if not checked then LPCONFIG.ZG = nil end LazyPigMenuObjects[10]:SetChecked(nil) LazyPigMenuObjects[11]:SetChecked(nil) elseif num == 20 then LPCONFIG.WORLDDUNGEON = true --fixed if not checked then LPCONFIG.WORLDDUNGEON = nil end if LPCONFIG.WORLDDUNGEON or LPCONFIG.WORLDRAID or LPCONFIG.WORLDBG then LPCONFIG.WORLDUNCHECK = nil LazyPigMenuObjects[23]:SetChecked(nil) end LazyPig_ZoneCheck() elseif num == 21 then LPCONFIG.WORLDRAID = true if not checked then LPCONFIG.WORLDRAID = nil end if LPCONFIG.WORLDDUNGEON or LPCONFIG.WORLDRAID or LPCONFIG.WORLDBG then LPCONFIG.WORLDUNCHECK = nil LazyPigMenuObjects[23]:SetChecked(nil) end LazyPig_ZoneCheck() elseif num == 22 then LPCONFIG.WORLDBG = true if not checked then LPCONFIG.WORLDBG = nil end if LPCONFIG.WORLDDUNGEON or LPCONFIG.WORLDRAID or LPCONFIG.WORLDBG then LPCONFIG.WORLDUNCHECK = nil LazyPigMenuObjects[23]:SetChecked(nil) end LazyPig_ZoneCheck() elseif num == 23 then LPCONFIG.WORLDUNCHECK = true if not checked then LPCONFIG.WORLDUNCHECK = nil else LPCONFIG.WORLDDUNGEON = nil LPCONFIG.WORLDRAID = nil LPCONFIG.WORLDBG = nil LazyPigMenuObjects[20]:SetChecked(nil) LazyPigMenuObjects[21]:SetChecked(nil) LazyPigMenuObjects[22]:SetChecked(nil) end LazyPig_ZoneCheck() elseif num == 30 then --fixed LPCONFIG.GINV = true if not checked then LPCONFIG.GINV = nil end elseif num == 31 then LPCONFIG.FINV = true if not checked then LPCONFIG.FINV = nil end elseif num == 32 then LPCONFIG.SINV = true if not checked then LPCONFIG.SINV = nil end elseif num == 33 then LPCONFIG.DINV = true if not checked then LPCONFIG.DINV = nil end elseif num == 40 then --fixed LPCONFIG.FPLATE = true if not checked then LPCONFIG.FPLATE = nil end if LPCONFIG.EPLATE and LPCONFIG.FPLATE then LPCONFIG.HPLATE = nil LazyPigMenuObjects[42]:SetChecked(nil) end LazyPig_RefreshNameplates() elseif num == 41 then LPCONFIG.EPLATE = true if not checked then LPCONFIG.EPLATE = nil end if LPCONFIG.EPLATE and LPCONFIG.FPLATE then LPCONFIG.HPLATE = nil LazyPigMenuObjects[42]:SetChecked(nil) end LazyPig_RefreshNameplates() elseif num == 42 then LPCONFIG.HPLATE = true if not checked then LPCONFIG.HPLATE = nil end if LPCONFIG.EPLATE and LPCONFIG.FPLATE then LPCONFIG.HPLATE = nil LazyPigMenuObjects[42]:SetChecked(nil) end LazyPig_RefreshNameplates() elseif num == 50 then --fixed LPCONFIG.EBG = true if not checked then LPCONFIG.EBG = nil end elseif num == 51 then LPCONFIG.LBG = true if not checked then LPCONFIG.LBG = nil end elseif num == 52 then LPCONFIG.QBG = true if not checked then LPCONFIG.QBG = nil end elseif num == 53 then LPCONFIG.RBG = true if not checked then LPCONFIG.RBG = nil end elseif num == 54 then LPCONFIG.AQUE = true if not checked then LPCONFIG.AQUE = nil end elseif num == 55 then LPCONFIG.SBG = true if not checked then LPCONFIG.SBG = nil end elseif num == 60 then LPCONFIG.SALVA = 1 if not checked then LPCONFIG.SALVA = nil end LazyPigMenuObjects[61]:SetChecked(nil) LazyPig_CheckSalvation() elseif num == 61 then LPCONFIG.SALVA = 2 if not checked then LPCONFIG.SALVA = nil end LazyPigMenuObjects[60]:SetChecked(nil) LazyPig_CheckSalvation() elseif num == 70 then --fixed LPCONFIG.SPAM = true if not checked then LPCONFIG.SPAM = nil end elseif num == 71 then LPCONFIG.SPAM_UNCOMMON = true if not checked then LPCONFIG.SPAM_UNCOMMON = nil end elseif num == 72 then LPCONFIG.SPAM_RARE = true if not checked then LPCONFIG.SPAM_RARE = nil end elseif num == 73 then LPCONFIG.SPAM_LOOT = true if not checked then LPCONFIG.SPAM_LOOT = nil end elseif num == 90 then LPCONFIG.SUMM = true if not checked then LPCONFIG.SUMM = nil end elseif num == 91 then LPCONFIG.LOOT = true if not checked then LPCONFIG.LOOT = nil end elseif num == 92 then LPCONFIG.RIGHT = true if not checked then LPCONFIG.RIGHT = nil end MailtoCheck(LPCONFIG.RIGHT) elseif num == 93 then--fixed LPCONFIG.SHIFTSPLIT = true if not checked then LPCONFIG.SHIFTSPLIT = nil end MailtoCheck(LPCONFIG.SHIFTSPLIT) elseif num == 94 then--fixed LPCONFIG.CAM = true if not checked then LPCONFIG.CAM = nil end if LPCONFIG.CAM then SetCVar("cameraDistanceMax",50) else SetCVar("cameraDistanceMaxFactor",1) SetCVar("cameraDistanceMax",15) end elseif num == 95 then LPCONFIG.SPECIALKEY = true if not checked then LPCONFIG.SPECIALKEY = nil end elseif num == 96 then LPCONFIG.DUEL = true if not checked then LPCONFIG.DUEL = nil end if LPCONFIG.DUEL then CancelDuel() end elseif num == 97 then LPCONFIG.REZ = true if not checked then LPCONFIG.REZ = nil end elseif num == 98 then LPCONFIG.GOSSIP = true if not checked then LPCONFIG.GOSSIP = nil end elseif num == 99 then LPCONFIG.NOSAVE = true if not checked then LPCONFIG.NOSAVE = GetRealmName() end elseif num == 100 then LPCONFIG.DISMOUNT = true if not checked then LPCONFIG.DISMOUNT = nil end elseif num == 101 then LPCONFIG.SPAM = true if not checked then LPCONFIG.SPAM = nil end else --DEFAULT_CHAT_FRAME:AddMessage("DEBUG: No num assigned - "..num) end --DEFAULT_CHAT_FRAME:AddMessage("DEBUG: Num chosen - "..num) end function LazyPig_RollLootOpen() for i=1,STATICPOPUP_NUMDIALOGS do local frame = getglobal("StaticPopup"..i) if frame:IsShown() and frame.which == "CONFIRM_LOOT_ROLL" then --DEFAULT_CHAT_FRAME:AddMessage("LazyPig_RollLootOpen - TRUE") return true end end return nil end function LazyPig_BindLootOpen() for i=1,STATICPOPUP_NUMDIALOGS do local frame = getglobal("StaticPopup"..i) if frame:IsShown() and frame.which == "LOOT_BIND" then --DEFAULT_CHAT_FRAME:AddMessage("LazyPig_BindLootOpen - TRUE") return true end end return nil end function LazyPig_ZoneCheck2() LazyPig_ZoneCheck() end function LazyPig_ZoneCheck() local process = function(ChatFrame, name) for index, value in ChatFrame.channelList do if (strupper(name) == strupper(value)) then return true end end return nil end local leavechat = LPCONFIG.WORLDRAID and LazyPig_Raid() or LPCONFIG.WORLDDUNGEON and LazyPig_Dungeon() or LPCONFIG.WORLDBG and LazyPig_BG() or LPCONFIG.WORLDUNCHECK for i = 1, NUM_CHAT_WINDOWS do local ChatFrame = getglobal("ChatFrame"..i) if ChatFrame:IsVisible() and not UnitIsDeadOrGhost("player") then local id, name = GetChannelName("world") if id > 0 then if leavechat then if process(ChatFrame, name) then ChatFrame_RemoveChannel(ChatFrame, name) channelstatus = true UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage("Leaving World") end return end end if (LPCONFIG.WORLDRAID or LPCONFIG.WORLDDUNGEON or LPCONFIG.WORLDBG) and not leavechat then local framename = ChatFrame:GetName() if id == 0 then UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage("Joining World"); JoinChannelByName("world", nil, ChatFrame:GetID()); else if (not process(ChatFrame, name) or channelstatus) and framename == "ChatFrame1" then ChatFrame_AddChannel(ChatFrame, name); UIErrorsFrame:Clear(); UIErrorsFrame:AddMessage("Joining World"); channelstatus = false end end end end end end function LazyPig_PlayerClass(class, unit) if class then local unit = unit or "player" local _, c = UnitClass(unit) if c then if string.lower(c) == string.lower(class) then return true end end end return false end function LazyPig_IsBearForm() local i; local max = GetNumShapeshiftForms(); for i = 1 , max do local _, name, isActive = GetShapeshiftFormInfo(i); if(isActive and LazyPig_PlayerClass("Druid", "player") and (name == "Bear Form" or name == "Dire Bear Form")) then return true end end return false end function LazyPig_IsShieldEquipped() local slot = GetInventorySlotInfo("SecondaryHandSlot") local link = GetInventoryItemLink("player", slot) if link then local found, _, id, name = string.find(link, "item:(%d+):.*%[(.*)%]") if found then local _,_,_,_,_,itemType = GetItemInfo(tonumber(id)) if(itemType == "Shields") then return true end end end return false end function LazyPig_CancelSalvationBuff() CancelPlayerBuff("Greater Blessing of Salvation"); CancelPlayerBuff("Blessing of Salvation"); return nil end function LazyPig_CheckSalvation() if(LPCONFIG.SALVA == 1 or LPCONFIG.SALVA == 2 and (LazyPig_IsShieldEquipped() and (LazyPig_PlayerClass("Warrior", "player") or LazyPig_PlayerClass("Paladin", "player")) or LazyPig_IsBearForm())) then LazyPig_CancelSalvationBuff() end end function LazyPig_ShowBindings(bind, fs, desc) local bind1, bind2 = GetBindingKey(bind) local fsl = getglobal(fs) local printout = nil if bind1 and bind2 then printout = "[" .. bind1 .. "/" .. bind2 .. "]" elseif bind1 then printout = "[" .. bind1 .. "]" elseif bind2 then printout = "[" .. bind2 .. "]" elseif desc then printout = "[" .. desc .. "]" else printout = "none" fsl:SetTextColor(1,1,1,1) end fsl:SetText(printout) end function LazyPig_ChatFrame_OnEvent(event) if event == "CHAT_MSG_LOOT" or event == "CHAT_MSG_MONEY" then local bijou = string.find(arg1 ,"Bijou") local coin = string.find(arg1 ,"Coin") local mark = string.find(arg1 ,"Mark of the Illidari") local fel = string.find(arg1 ,"Fel Armament") local arc = string.find(arg1 ,"Arcane Tome") local stick = string.find(arg1 ,"Amani Hex Stick") local heart = string.find(arg1 ,"Heart of Darkness") local green_roll = greenrolltime > GetTime() local check_uncommon = LPCONFIG.SPAM_UNCOMMON and string.find(arg1 ,"1eff00") local check_rare = LPCONFIG.SPAM_RARE and string.find(arg1 ,"0070dd") local check_loot = LPCONFIG.SPAM_LOOT and (string.find(arg1 ,"9d9d9d") or string.find(arg1 ,"ffffff") or string.find(arg1 ,"Your share of the loot")) local check_money = LPCONFIG.SPAM_LOOT and string.find(arg1 ,"Your share of the loot") local check1 = string.find(arg1 ,"You") local check2 = string.find(arg1 ,"won") or string.find(arg1 ,"receive") local check3 = LPCONFIG.ZG and (bijou or coin or mark or fel or arc or stick or heart) local check4 = check1 and not check3 and not green_roll or check2 if not check4 and (check_uncommon or check_rare) or check_loot and not check1 or check_money then return end end if LPCONFIG.SPAM and arg2 and arg2 ~= GetUnitName("player") and (event == "CHAT_MSG_SAY" or event == "CHAT_MSG_CHANNEL" or event == "CHAT_MSG_YELL" or event == "CHAT_MSG_EMOTE" and not (IsGuildMate(arg2) or IsFriend(arg2))) then local time = GetTime() local index = ChatMessage["INDEX"] for blockindex,blockmatch in pairs(ChatMessage[index]) do local findmatch1 = (blockmatch + 70) > time --70s delay local findmatch2 = blockindex == arg1 if findmatch1 and findmatch2 then return end end ChatMessage[index][arg1] = time end Original_ChatFrame_OnEvent(event); end function ChatSpamClean() local time = GetTime() local index = ChatMessage["INDEX"] local newindex = nil if index == 1 then newindex = 2 else newindex = 1 end for blockindex,blockmatch in pairs(ChatMessage[index]) do if (blockmatch + 70) > time then ChatMessage[newindex][blockindex] = ChatMessage[index][blockindex] end end ChatMessage[index] = {} ChatMessage["INDEX"] = newindex --DEFAULT_CHAT_FRAME:AddMessage("ChatSpamClean") end function LazyPig_Track_EFC(msg) if msg then msg = strlower(msg) local find0 = "captured " local find1 = "The "..UnitFactionGroup("player").." Flag" local find2 = " was picked up " local find3 = " was dropped " if string.find(msg, strlower(find1..find2)) then _, _, wsgefc = string.find(msg, strlower(find1..find2.."by (.+)%!")) --DEFAULT_CHAT_FRAME:AddMessage("ADD EFC - "..wsgefc) elseif string.find(msg, strlower(find1..find3)) or string.find(msg, strlower(find0..find1)) then wsgefc = nil --DEFAULT_CHAT_FRAME:AddMessage("DEL EFC") end end end function LazyPig_Target_EFC() ClearTarget() if wsgefc then TargetByName(wsgefc, true) UIErrorsFrame:Clear() if not UnitExists("target") then UIErrorsFrame:AddMessage("OUT OF RANGE - EFC - "..strupper(wsgefc)) elseif strlower(GetUnitName("target")) == wsgefc then local class, classFileName = UnitClass("target") local color = RAID_CLASS_COLORS[classFileName] UIErrorsFrame:AddMessage(strupper(class.." - EFC - "..wsgefc), color.r, color.g, color.b) end end end function LazyPig_Duel_EFC() if GetRealZoneText() == "Warsong Gulch" then LazyPig_Target_EFC() else local duel = nil for i=1,STATICPOPUP_NUMDIALOGS do local frame = getglobal("StaticPopup"..i) if frame:IsShown() then if frame.which == "DUEL_REQUESTED" then duel = true end end end if duel_active or duel then CancelDuel() elseif UnitExists("target") and UnitIsFriend("target", "player") then StartDuel(GetUnitName("target")) end end end function aaa() PlayerFrame:Hide() end
--------------------------------------------------------------------------------------------------- ---multi_page_menu_selector.lua ---author: Karl ---date: 2021.5.11 ---desc: Defines a selector for text menu that has multiple pages --------------------------------------------------------------------------------------------------- local ShakeEffListingSelector = require("BHElib.ui.selectors.shake_eff_listing_selector") local SimpleMenuSelector = require("BHElib.ui.selectors.simple_menu_selector") ---@class MultiPageMenuSelector:SimpleMenuSelector local M = LuaClass("selectors.MultiPageMenuSelector", SimpleMenuSelector) --------------------------------------------------------------------------------------------------- ---@param selection_input InputManager the object for this selector to receive input from ---@param focused_index number initial focused index ---@param menu_body_pos math.vec2 initial position of the menu body ---@param shake_max_time number duration of the shaking effect ---@param shake_amplitude number amplitude of the shaking effect; shaking only occurs in x direction ---@param shake_period number period of harmonic (sine) motion of shaking effect in frames ---@param blink_speed number speed of selectable blinking ---@param blink_color_a math.vec4 blinking color; of form {r, g, b, a} ---@param blink_color_b math.vec4 blinking color; of form {r, g, b, a} ---@param normal_color math.vec4 color of the text when they are not blinking; of form {r, g, b, a} ---@param title_pos_offset math.vec2 title position relative to the body of the menu ---@param title_text_obj ui.TextClass text object describing how the title text should look; require everything ---@param body_text_obj ui.TextClass text object describing how the body text should look; require everything except text and color ---@param pos_increment math.vec2 increment in position between each two menu selectables ---@param all_selectable table an array of all selectables in this menu ---@param transition_fly_directions table an array of numbers specifying the transition flying direction in degrees ---@param transition_fly_distances table an array of numbers specifying the transition flying distance function M.__create( selection_input, focused_index, menu_body_pos, shake_max_time, shake_amplitude, shake_period, blink_speed, blink_color_a, blink_color_b, normal_color, title_pos_offset, title_text_obj, body_text_obj, pos_increment, all_selectable, num_selectable_in_page, num_pages, transition_fly_directions, transition_fly_distances) local self = SimpleMenuSelector.__create( selection_input, focused_index, menu_body_pos, shake_max_time, shake_amplitude, shake_period, blink_speed, blink_color_a, blink_color_b, normal_color, title_pos_offset, title_text_obj, body_text_obj, pos_increment, {}, transition_fly_directions, transition_fly_distances ) self.all_selectable = all_selectable self.num_selectable_in_page = num_selectable_in_page self.num_pages = num_pages self.page_index = 1 self.menu_body_pos = menu_body_pos self.title_pos_offset = title_pos_offset self.title_text_obj = title_text_obj self.body_text_obj = body_text_obj return self end ---analogy to moveFocusTo(); flip to a new page, and load options into selectable_array ---page index starts at 1; ---focus index may be out of range when this function is called, the function needs to warp it in place and play selection effect ---@param index number page number to flip to; may be out of range function M:flipPageTo(index) -- cleanup the current page self:resetShakeTimer(math.huge) -- calculate the next page index = (index - 1) % self.num_pages + 1 self.page_index = index self:loadSelectableArray(index) self:moveFocusTo(self.focused_index) end ---@param index number page number function M:loadSelectableArray(index) assert(index >= 1 and index <= self.num_pages, "Error: Page index out of range!") local num_item = self.num_selectable_in_page local selectable_array = self.selectable_array local base_index = num_item * (index - 1) for i = 1, num_item do local selectable = self.all_selectable[base_index + i] selectable_array[i] = selectable end end function M:setSelectableAtIndex(index, new_selectable) self.all_selectable[index] = new_selectable self:loadSelectableArray(self.page_index) end function M:renderSelectable(index) if self.selectable_array[index] == nil then self:renderDummySelectable(index) else ShakeEffListingSelector.renderSelectable(self, index) end end function M:renderDummySelectable(index) local body_text_obj = self.body_text_obj local item_pos = self.menu_body_pos + self:getListingPosOffsetAfterShakeEff(index) local color_vec -- the selected selectable will blink if index == self.focused_index then local lerp_coeff = 0.5 + 0.5 * sin(self.timer * self.blink_speed) color_vec = self.blink_color_a * lerp_coeff + self.blink_color_b * (1 - lerp_coeff) else color_vec = self.normal_color end body_text_obj:setFontColor(Color(color_vec.w, color_vec.x, color_vec.y, color_vec.z)) body_text_obj:setText(self.selectable_array[index].text) body_text_obj:render(item_pos.x, item_pos.y) end ---test for and process user input on the menu function M:processInput() ---@type InputManager local input = self.selection_input local page_index_diff = 0 local focused_index_diff = 0 if input:isAnyKeyJustChanged("left", false, true) then page_index_diff = -1 elseif input:isAnyKeyJustChanged("right", false, true) then page_index_diff = 1 end if page_index_diff == 0 then -- only check for up down movement if no page flip has happened -- moving through options if input:isAnyKeyJustChanged("up", false, true) then focused_index_diff = -1 elseif input:isAnyKeyJustChanged("down", false, true) then focused_index_diff = 1 end local focused_index = self.focused_index + focused_index_diff if focused_index <= 0 then page_index_diff = -1 elseif focused_index > self.num_selectable_in_page then page_index_diff = 1 end end if page_index_diff ~= 0 then self.focused_index = self.focused_index + focused_index_diff self:flipPageTo(self.page_index + page_index_diff) elseif focused_index_diff ~= 0 then self:moveFocusTo(self.focused_index + focused_index_diff) end -- selecting an option if input:isAnyKeyJustChanged("select", false, true) then self:select(self.focused_index) end end function M:select(i) local item = self.selectable_array[i] if item.choices ~= nil then ShakeEffListingSelector.select(self, i) end end function M:globalMoveFocus(index) local page_index = math.ceil(index / self.num_selectable_in_page) self.focused_index = index -- will be warped to the correct position in this following function self:flipPageTo(math.clamp(page_index, 1, self.num_pages)) end --------------------------------------------------------------------------------------------------- ---shorter init parameter list local MenuConst = require("BHElib.ui.menu.menu_global") local InteractiveSelector = require("BHElib.ui.selectors.interactive_selector") local Input = require("BHElib.input.input_and_recording") local TextClass = require("BHElib.ui.text_class") local Vec2 = math.vec2 ---@param init_global_focused_index number ---@param scale number scaling of the displayed text size and line height ---@param fly_distance number distance of travelling when transition in/out ---@param relative_pos math.vec2 relative position of the menu page ---@param all_selectable table an array of SimpleMenuSelector.Selectable objects ---@param num_selectable_in_page number number of options max in one page ---@param num_pages number number of pages total ---@param menu_page_title string text title of the page function M.shortInit(init_global_focused_index, scale, fly_distance, relative_pos, all_selectable, menu_page_title, num_selectable_in_page, num_pages, enter_dir, exit_dir) -- create simple menu selector local text_line_height = MenuConst.line_height * scale local text_align = {"center"} local title_color = MenuConst.title_color local title_text_object = TextClass( menu_page_title, Color(title_color.w, title_color.x, title_color.y, title_color.z), MenuConst.font_name, MenuConst.font_size * scale, unpack(text_align)) local body_text_object = TextClass( nil, nil, MenuConst.font_name, MenuConst.font_size * scale, unpack(text_align)) local transition_fly_directions = { [MenuConst.IN_FORWARD] = enter_dir or -180, [MenuConst.IN_BACKWARD] = exit_dir or 0, [MenuConst.OUT_FORWARD] = exit_dir or 0, [MenuConst.OUT_BACKWARD] = enter_dir or -180, } local transition_fly_distances = { [MenuConst.IN_FORWARD] = fly_distance, [MenuConst.IN_BACKWARD] = fly_distance, [MenuConst.OUT_FORWARD] = fly_distance, [MenuConst.OUT_BACKWARD] = fly_distance, } local selector = M( Input, 1, relative_pos, MenuConst.shake_time, MenuConst.shake_range, MenuConst.shake_period, MenuConst.blink_speed, MenuConst.focused_color_a, MenuConst.focused_color_b, MenuConst.unfocused_color, Vec2(0, 2 * text_line_height), title_text_object, body_text_object, Vec2(0, -text_line_height), all_selectable, num_selectable_in_page, num_pages, transition_fly_directions, transition_fly_distances) selector:globalMoveFocus(init_global_focused_index) return selector end return M
-- vim:foldmethod=marker local r = require 'repl' -- we don't call it 'repl' so we don't shadow -- repl in the plugin environment pcall(require, 'luarocks.loader') require 'Test.More' local utils = require 'test-utils' plan(5) local clone = r:clone() do -- basic tests {{{ local with_plugin = clone:clone() function with_plugin:foo() end local line_no local _, err = pcall(function() with_plugin:loadplugin(function() line_no = utils.next_line_number() function repl:foo() end end) end) like(err, string.format("%d: The 'foo' method already exists", line_no)) with_plugin:loadplugin(function() function repl:bar() return 17 end end) is(with_plugin:bar(), 17) with_plugin:loadplugin(function() repl.baz = 18 end) is(with_plugin.baz, 18) end -- }}} do -- conflict tests {{{ local clone = r:clone() local line_no clone:loadplugin(function() function repl:foo() end end) local _, err = pcall(function() clone:loadplugin(function() line_no = utils.next_line_number() function repl:foo() end end) end) like(err, tostring(line_no) .. ": The 'foo' method already exists") end -- }}} do -- proxy tests {{{ local clone = r:clone() clone:loadplugin(function() features = 'foo' end) clone:loadplugin(function() ok(repl:hasfeature 'foo') end) end -- }}}
--[=[ @class CameraGamepadInputUtility ]=] local CameraGamepadInputUtility = {} -- K is a tunable parameter that changes the shape of the S-curve -- the larger K is the more straight/linear the curve gets local k = 0.35 local lowerK = 0.8 local function SCurveTransform(t) t = math.clamp(t, -1, 1) if t >= 0 then return (k * t) / (k - t + 1) end return -((lowerK * -t) / (lowerK + t + 1)) end local DEADZONE = 0.1 local function toSCurveSpace(t) return (1 + DEADZONE) * (2 * math.abs(t) - 1) - DEADZONE end local function fromSCurveSpace(t) return t / 2 + 0.5 end function CameraGamepadInputUtility.OutOfDeadZone(inputObject) local stickOffset = inputObject.Position return stickOffset.Magnitude >= DEADZONE end local function onAxis(axisValue) local sign = 1 if axisValue < 0 then sign = -1 end return math.clamp(fromSCurveSpace(SCurveTransform(toSCurveSpace(math.abs(axisValue)))) * sign, -1, 1) end function CameraGamepadInputUtility.GamepadLinearToCurve(thumbstickPosition) return Vector2.new(onAxis(thumbstickPosition.X), onAxis(thumbstickPosition.Y)) end table.freeze(CameraGamepadInputUtility) return CameraGamepadInputUtility
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_underlord_atrophy_aura_lua_debuff = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_underlord_atrophy_aura_lua_debuff:IsHidden() return false end function modifier_underlord_atrophy_aura_lua_debuff:IsDebuff() return true end function modifier_underlord_atrophy_aura_lua_debuff:IsStunDebuff() return false end function modifier_underlord_atrophy_aura_lua_debuff:IsPurgable() return true end function modifier_underlord_atrophy_aura_lua_debuff:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end -------------------------------------------------------------------------------- -- Initializations function modifier_underlord_atrophy_aura_lua_debuff:OnCreated( kv ) -- references self.reduction = self:GetAbility():GetSpecialValueFor( "damage_reduction_pct" ) if not IsServer() then return end end function modifier_underlord_atrophy_aura_lua_debuff:OnRefresh( kv ) -- references self.reduction = self:GetAbility():GetSpecialValueFor( "damage_reduction_pct" ) end function modifier_underlord_atrophy_aura_lua_debuff:OnRemoved() end function modifier_underlord_atrophy_aura_lua_debuff:OnDestroy() end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_underlord_atrophy_aura_lua_debuff:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_BASEDAMAGEOUTGOING_PERCENTAGE, } return funcs end function modifier_underlord_atrophy_aura_lua_debuff:GetModifierBaseDamageOutgoing_Percentage( params ) return -self.reduction end
--[[注意:只支持默认数字连续键值!!!]] BehTree.StackList = {} local this = BehTree.StackList this.count = 0 function this:New() self.stack_list = {} setmetatable(self, this) this.__index = this return self end function this:Push(element) self.count = self.count+1 self.stack_list[self.count] = element end function this:Pop() if self.count < 1 then print('stack_list self.count is 0!!') return end local pope = table.remove(self.stack_list, self.count) self.count = self.count-1 return pope end function this:Count() return self.count end function this:GetTop() local top = self.stack_list[self.count] return top end function this:Contain(e) for i=1, self.count do if e == self.stack_list[i] then return true end end return false end function this:Clear() self.stack_list = nil self.stack_list = {} self.count = 0 end function this:ToString() if self.count <= 0 then print('this self.Count is : 0') end for k, v in pairs(self.stack_list) do print('Stack 信息: key :'..k..' vale: '..tostring(v)) end end
-- gcf calculates the greatest common factor of x and y -- implementation uses the Euclidean Algorithm -- https://en.wikipedia.org/wiki/Euclidean_algorithm function gcf(x, y) -- Greatest common factor of x and x is x. if x == y then return x end -- Swap order such that y > x. if x > y then y, x = x, y end -- gcf(x, y) = gcf(y-x, x) | y > x return gcf(y-x, x) end print("Greatest common factor of 55 and 30: " .. gcf(55, 30))
return { recursiveToString = require(script.recursiveToString), }
function div(a, b) return math.floor(a/b) end t = {} function pali(a) local y, c = 1, a while c > 0 do t[y], y, c = c % 10, y + 1, div(c, 10) end y = y - 1 for x = 1, y/2 do if t[x] ~= t[y] then return false end y = y - 1 end return true end for line in io.lines(arg[1]) do local l, r = line:match("(%d+) (%d+)") local n = 0 for i = l, r do local prev = -1 for j = i, r do local p = 0 if prev > -1 then p = prev if pali(j) then p = p + 1 end else p = 0 for k = i, j do if pali(k) then p = p + 1 end end end if p%2 == 0 then n = n + 1 end prev = p end end print(n) end
-- Cacher -- By default, use uri as the hash key local function default_hash_key () return ngx.var.uri end local function default_set () error('set must be specified') end local function default_get () error('get must be specified') end local function default_load () error('load must be specified') end -- by default, always cache local function when (res) return true end local M = { _hash_key = default_hash_key, _set = default_set, _get = default_get, _load = default_load, _when = when } function M.new (self) return setmetatable({}, {__index = M}) end function M.hash_key (self, fn) self._hash_key = fn return self end function M.setter (self, fn) self._set = fn return self end function M.getter (self, fn) self._get = fn return self end function M.when(self, fn) self._when = fn return self end function M.loader (self, fn) self._load = fn return self end function M.expires (self, fn) self._get_expires = fn return self end function M.reload (self, key, options) local res = self._load(key, options) -- 1. if response is not valid -- 2. or it is already queued, then _load() will return nil if res and self._when(res) then self._set(key, res, options.expires) end return res end function M.get (self, on_response, force_reload) local key = self._hash_key() local res, err, stale, expires_at = self._get(key) local reloaded = false local hit = true -- 1. cache not found -- 2. redis connection error -- 3. force to reload if not res or err or force_reload then reloaded = true hit = false stale = false res = self:reload(key, { expires = self._get_expires(), -- `sub_request` indicates that it is a request that should come up with -- the main request sychronously sub_request = true }) end -- lua has block scope local expires = nil local uri = nil local query = nil local headers = nil local body = nil local method = nil -- Prefetch parameters before connection closed. if stale then expires = self._get_expires() uri = ngx.var.uri headers = ngx.req.get_headers() or {} query = ngx.req.get_uri_args() or {} body = ngx.req.get_body_data() or '' method = ngx.var.request_method or 'GET' end on_response(res, hit, stale, expires_at) -- If stale, then we need reload cache -- TODO: concurrency if stale then self:reload(key, { -- Only allow single http connection to penetrate Gaia single_through = true, expires = expires, uri = uri, headers = headers, query = query, body = body, method = method }) end end return M
--- -- @class PANEL -- @section DComboBoxTTT2 local PANEL = {} Derma_Hook(PANEL, "Paint", "Paint", "ComboBoxTTT2") Derma_Install_Convar_Functions(PANEL) --- -- @accessor boolean -- @realm client AccessorFunc(PANEL, "m_bDoSort", "SortItems", FORCE_BOOL) --- -- @ignore function PANEL:Init() self.DropButton = vgui.Create("DPanel", self) self.DropButton:SetMouseInputEnabled(false) self.DropButton.ComboBox = self self.DropButton.Paint = function(panel, w, h) derma.SkinHook("Paint", "ComboDownArrow", panel, w, h) end self:SetTall(22) self:Clear() self:SetContentAlignment(4) self:SetTextInset(8, 0) self:SetIsMenu(true) self:SetSortItems(true) self:SetFont("DermaTTT2Text") self.choices = {} self.titleIndices = {} self.valueIndices = {} end --- -- @ignore function PANEL:PerformLayout() self.DropButton:SetSize(15, 15) self.DropButton:AlignRight(4) self.DropButton:CenterVertical() end --- -- @realm client function PANEL:Clear() self:SetText("") self.choices = {} self.titleIndices = {} self.valueIndices = {} self.selected = nil self:CloseMenu() end --- -- Gets the displayed Text if one is set, otherwise the value like in the original DComboBox -- @note this doesnt necessarily get the value used to set conVars, use `PANEL:GetOptionValue(index)` instead -- @param number index the option id -- @return string -- @realm client function PANEL:GetOptionText(index) local choice = self.choices[index] if not choice then return end return choice.title or choice.value end --- -- @param number index the option id -- @return string/number a value that is indexable -- @realm client function PANEL:GetOptionValue(index) return self.choices[index].value end --- -- @param number index the option id -- @return any -- @realm client function PANEL:GetOptionData(index) return self.choices[index].data end --- -- @param string/number value should be indexable -- @return number -- @realm client function PANEL:GetOptionID(value) return self.valueIndices[value] or 1 end --- -- @param string title -- @return number -- @realm client function PANEL:GetOptionTitleID(title) return self.titleIndices[title] or 1 end --- -- @param any data -- @return any -- @realm client function PANEL:GetOptionTextByData(data) local choices = self.choices local choicesSize = #choices for index = 1, choicesSize do local choiceData = choices[index].data if choiceData ~= data and choiceData ~= tonumber(data) then continue end return self:GetOptionText(index) end return end --- -- @param string title -- @param string/number value should be indexable -- @param bool select -- @param string icon -- @param any data additional data that you might want to use -- @return number index -- @realm client function PANEL:AddChoice(title, value, select, icon, data) if istable(value) then ErrorNoHalt("[TTT2] dcombobox_ttt2 AddChoice format changed to PANEL:AddChoice(title, value, select, icon, data)\n For any table data use the last parameter.\n") return end local index = #self.choices + 1 self.choices[index] = { title = title, value = value, icon = icon, data = data } -- Index tables for fast access self.titleIndices[title] = index self.valueIndices[value] = index if select then self:ChooseOptionID(index, true) end return index end --- -- @param number index the option id -- @param[default=false] bool ignoreConVar To avoid endless loops, separated setting of convars and UI values -- @realm client function PANEL:ChooseOptionID(index, ignoreConVar) local choices = self.choices if index > #choices then ErrorNoHalt("[TTT2] PANEL:ChooseOptionID failed, exceeding index size of choices.") return end local choice = choices[index] local value = choice.value self.selected = index self:SetText(choice.title) self:OnSelect(index, value, choice.data) self:CloseMenu() if ignoreConVar then return end self:SetConVarValues(tostring(value)) end --- -- @note this chooses the the set value like in the original DComboBox -- @param string/number value should be indexable e.g. the value used to set conVars -- @param[default=false] bool ignoreConVar To avoid endless loops, separated setting of convars and UI values -- @realm client function PANEL:ChooseOptionValue(value, ignoreConVar) self:ChooseOptionID(self:GetOptionID(value), ignoreConVar) end --- -- @note this chooses the displayed text rather than the set value like in the original DComboBox -- So use `PANEL:ChooseOptionValue` for the old behaviour -- @param string name the displayed text -- @param[default=false] bool ignoreConVar To avoid endless loops, separated setting of convars and UI values -- @realm client function PANEL:ChooseOptionName(name, ignoreConVar) self:ChooseOptionID(self:GetOptionTitleID(name), ignoreConVar) end --- -- Choose option by index, title is not settable -- @param[opt] string title is unused as it cant be set anymore -- @param number index the option id -- @param[default=false] bool ignoreConVar To avoid endless loops, separated setting of convars and UI values -- @realm client -- @deprecated Giving titles is not possible anymore. Use `PANEL:ChooseOptionID` instead function PANEL:ChooseOption(title, index, ignoreConVar) self:ChooseOptionID(index, ignoreConVar) end --- -- @return number -- @realm client function PANEL:GetSelectedID() return self.selected end --- -- @note this returns the set value not the displayed text, like in the combobox -- @warning the second return-argument is the additional data that is given not what was before the set value, which is now given in the first return argument -- @return string the set value -- @return any the additional data if given -- @realm client function PANEL:GetSelected() if not self.selected then return end return self:GetOptionValue(self.selected), self:GetOptionData(self.selected) end --- -- @param number index -- @param string/number value is indexable -- @param any data -- @realm client function PANEL:OnSelect(index, value, data) end --- -- @return boolean -- @realm client function PANEL:DoClick() if self:IsMenuOpen() then self:CloseMenu() end self:OpenMenu() end --- -- @return boolean -- @realm client function PANEL:IsMenuOpen() return IsValid(self.menu) and self.menu:IsVisible() end --- -- @param Panel pControlOpener -- @realm client function PANEL:OpenMenu(pControlOpener) if pControlOpener and pControlOpener == self.TextEntry then return end -- Do a table Copy if you want to sort items local sortItems = self:GetSortItems() local choices = sortItems and table.Copy(self.choices) or self.choices local choicesSize = #choices -- Don't do anything if there aren't any options.. if choicesSize == 0 then return end -- If the menu still exists and hasn't been deleted -- then just close it and open a new one. self:CloseMenu() self.menu = DermaMenu(false, self) if sortItems then -- Convert Gmod Strings for i = 1, choicesSize do local choice = choices[i] local title = choice.title if string.len(title) > 1 and title:StartWith("#") then title = language.GetPhrase(title:sub(2)) end choice.title = title end -- Sort by title table.SortByMember(choices, "title", true) end for index = 1, choicesSize do local choice = choices[index] local option = self.menu:AddOption(choice.title, function() self:SetValue(choice.value, false) end) if choice.icon then option:SetIcon(choice.icon) end end local x, y = self:LocalToScreen(0, self:GetTall()) self.menu:SetMinimumWidth(self:GetWide()) self.menu:Open(x, y, false, self) end --- -- @realm client function PANEL:CloseMenu() if IsValid(self.menu) then self.menu:Remove() self.menu = nil end end --- -- @warning this doesnt set the displayed text like before, but the value and selects an option -- @param string/number value should be indexable -- @param bool ignoreConVar To avoid endless loops, separated setting of convars and UI values -- @realm client function PANEL:SetValue(value, ignoreConVar) self:ChooseOptionValue(value, ignoreConVar) end local convarTracker = 0 --- -- @param Panel menu to set the value of -- @param string conVar name of the convar local function AddConVarChangeCallback(menu, conVar) convarTracker = convarTracker % 1023 + 1 local myIdentifierString = "TTT2F1MenuConVarChangeCallback" .. tostring(convarTracker) local function OnConVarChangeCallback(conVarName, oldValue, newValue) if not IsValid(menu) then cvars.RemoveChangeCallback(conVarName, myIdentifierString) return end menu:SetValue(newValue, true) end cvars.AddChangeCallback(conVar, OnConVarChangeCallback, myIdentifierString) end --- -- @param string conVarName -- @realm client function PANEL:SetConVar(conVarName) if not ConVarExists(conVarName or "") then return end local conVar = GetConVar(conVarName) self.conVar = conVar self:SetValue(conVar:GetString(), true) self:SetDefaultValue(conVar:GetDefault()) AddConVarChangeCallback(self, conVarName) end --- -- @param string conVarName -- @realm client function PANEL:SetServerConVar(conVarName) if not conVarName or conVarName == "" then return end self.serverConVar = conVarName cvars.ServerConVarGetValue(conVarName, function (wasSuccess, value, default) if wasSuccess then self:SetValue(value, true) self:SetDefaultValue(default) end end) AddConVarChangeCallback(self, conVarName) end --- -- @param string value -- @realm client function PANEL:SetConVarValues(value) if self.conVar then self.conVar:SetString(value) end if self.serverConVar then cvars.ChangeServerConVar(self.serverConVar, value) end end --- -- @param string value -- @realm client function PANEL:SetDefaultValue(value) local noDefault = true if isstring(value) then self.default = value noDefault = false else self.default = nil end local reset = self:GetResetButton() if ispanel(reset) then reset.noDefault = noDefault end end --- -- @return number defaultValue -- @realm client function PANEL:GetDefaultValue() return self.default end --- -- @realm client function PANEL:ResetToDefaultValue() local default = self:GetDefaultValue() if not default then return end self:SetValue(default, false) end --- -- @param Panel reset -- @realm client function PANEL:SetResetButton(reset) if not ispanel(reset) then return end self.resetButton = reset reset.DoClick = function(slf) self:ResetToDefaultValue() end reset.noDefault = self.default == nil end --- -- @return Panel reset -- @realm client function PANEL:GetResetButton() return self.resetButton end derma.DefineControl("DComboBoxTTT2", "", PANEL, "DButtonTTT2")
-------------------------------------------------------------------------------- -- NordVPN Status Widget -- Icon shows connected/disconnected, notification shows more details -- More details could be found here: -- https://bitbucket.org/easlice/awesome-as-widgets -- @author Andrew Slice -- @license MIT -------------------------------------------------------------------------------- local wibox = require("wibox") local watch = require("awful.widget.watch") local spawn = require("awful.spawn") local naughty = require("naughty") local beautiful = require("beautiful") local gears = require("gears") local PATH_TO_ICONS = "/usr/share/icons/Arc/status/symbolic/" local CONNECTED_ICON = PATH_TO_ICONS .. "network-vpn-symbolic.svg" local DISCONNECTED_ICON = PATH_TO_ICONS .. "network-vpn-acquiring-symbolic.svg" local NORD_STATUS_CMD = 'nordvpn status' local NORD_CONNECT_CMD = 'nordvpn c' local NORD_DISCONNECT_CMD = 'nordvpn d' local this = { connected = false } -------------------------------------------------------------------------------- -- returns the connected state -------------------------------------------------------------------------------- local function parse_connected(stdout) local status = string.match(stdout, "Status: (%a+)") if status ~= nil and status:lower() == "connected" then return true end return false end -------------------------------------------------------------------------------- -- Set the icons and last_stdout based on the parse results -------------------------------------------------------------------------------- local function update_status(vpn_conn_obj, stdout, _, _, _) local is_connected = parse_connected(stdout) vpn_conn_obj.connected = is_connected -- There's come crud in the output by default, so let's remove that stdout = "\n" .. stdout:gsub("^%W*[\r\n]*","") vpn_conn_obj.last_stdout = stdout; vpn_conn_obj.widget.icon.image = gears.color.recolor_image( vpn_conn_obj.connected and vpn_conn_obj.connected_icon or vpn_conn_obj.disconnected_icon, beautiful.fg_normal ) if vpn_conn_obj.display_notification and vpn_conn_obj.notification then vpn_conn_obj.notification.image = gears.color.recolor_image( vpn_conn_obj.connected and vpn_conn_obj.connected_icon or vpn_conn_obj.disconnected_icon, beautiful.fg_normal ) naughty.replace_text(vpn_conn_obj.notification, "VPN Connection Status", stdout) end end local function worker(args) ---------------------------------------------------------------------------- -- Initial Config local args = args or {} this.display_notification = args.display_notification or true this.notification_position = args.notification_position or "top_right" this.connected_icon = args.connected_icon or CONNECTED_ICON this.disconnected_icon = args.disconnected_icon or DISCONNECTED_ICON ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -- Widget Creation this.widget = wibox.widget { { id = "icon", image = gears.color.recolor_image(this.disconnected_icon, beautiful.fg_normal), widget = wibox.widget.imagebox, }, layout = wibox.container.margin(_, _, _, 3), } ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -- Internal Functions -- Run a given command and then run an update command. function this:_cmd(cmd) spawn.easy_async( cmd, function(stdout, stderr, exitreason, exitcode) this:_update() end ) end -- Get the latest status and update the info in the widget function this:_update() spawn.easy_async( NORD_STATUS_CMD, function(stdout, _, _, _) update_status(this, stdout) end ) end -- Show the notification -- keep, if true, makes the notification not fade out function this:_show(keep) if this.display_notification then naughty.destroy(this.notification) this.notification = naughty.notify{ text = this.last_stdout, icon = gears.color.recolor_image( this.connected and this.connected_icon or this.disconnected_icon, beautiful.fg_normal ), title = "VPN Connection Status", position = this.notification_position, timeout = keep and 0 or 2, hover_timeout = 0.5, } end end -- toggle the connection on and off function this:_toggle() if this.connected then this:_cmd(NORD_DISCONNECT_CMD) else this:_cmd(NORD_CONNECT_CMD) end end ---------------------------------------------------------------------------- ---------------------------------------------------------------------------- -- Mouse Events this.widget:connect_signal("button::press", function(_,_,_,button) if (button == 1) then this._toggle() end end) if this.display_notification then this.widget:connect_signal("mouse::enter", function() this:_update();this:_show(true) end) this.widget:connect_signal("mouse::leave", function() naughty.destroy(this.notification) end) end ---------------------------------------------------------------------------- this:_update() watch( GET_NORD_STATUS_CMD, 5, function() this:_update() end, this.widget ) return this.widget end return setmetatable(this, { __call = function(_, ...) return worker(...) end })
local class = require('middleclass') local Controller = require('mvc.Controller') local HasSignals = require('HasSignals') local tools = require('app.helpers.tools') local GVMemberListController = class("GVMemberListController", Controller):include(HasSignals) local SoundMng = require "app.helpers.SoundMng" function GVMemberListController:initialize(data) Controller.initialize(self) HasSignals.initialize(self) self.group = data[1] self.isAdmin = data[2] self.isAdminFu = data[3] end function GVMemberListController:viewDidLoad() self.view:layout({self.group, self.isAdmin, self.isAdminFu}) local group = self.group self.listener = { self.group:on('memberList', function(msg) self.view:freshGameState(true) self.view:freshMemberList() end), self.view:on('userInfo', function(playerId) self.group:queryUserInfo(playerId) end), group:on('resultSetMemberScore', function(msg) if msg.code == -1 then tools.showRemind("操作失败") elseif msg.code == 0 then tools.showRemind(msg.errorCode) elseif msg.code == 1 then tools.showRemind("操作成功") self:clickCloseScoreLayer() end end), } local groupInfo = self.group:getCurGroup() local groupId = groupInfo.id self.group:memberList(groupId) end function GVMemberListController:clickBan() local groupInfo = self.group:getCurGroup() if not groupInfo then return end local groupId = groupInfo.id if next(self.view.banData) then local arr = {} for k,v in pairs(self.view.banData) do table.insert(arr, k) end self.group:banUser(groupId, arr, 'ban') end end function GVMemberListController:clickUnban() local groupInfo = self.group:getCurGroup() if not groupInfo then return end local groupId = groupInfo.id if next(self.view.banData) then local arr = {} for k,v in pairs(self.view.banData) do table.insert(arr, k) end self.group:banUser(groupId, arr, 'unban') end end function GVMemberListController:clickSureDel() local groupInfo = self.group:getCurGroup() if not groupInfo then return end local groupId = groupInfo.id if next(self.view.delData) then local arr = {} for k,v in pairs(self.view.delData) do table.insert(arr, k) end self.group:delUser(groupId, arr) end end function GVMemberListController:clickCloseScoreLayer() self.view:freshScoreLayer(false) end function GVMemberListController:clickSetAdmin() local groupInfo = self.group:getCurGroup() if not groupInfo then return end local groupId = groupInfo.id local arr = {} if next(self.view.adminFu) then for k,v in pairs(self.view.adminFu) do table.insert(arr, k) end end self.group:setAdmin(groupId, arr) end function GVMemberListController:clickToBan() self.view:setOperationMode('ban') self.view:freshclicktoLayer(false,false,true,false) end function GVMemberListController:clickToDelete() self.view:setOperationMode('del') self.view:freshclicktoLayer(false,true,false,false) end function GVMemberListController:clickToAdmin() self.view:setOperationMode('none') self.view:freshclicktoLayer(true,false,false,false) end function GVMemberListController:clickToSetScore() self.view:setOperationMode('setscore') self.view:freshclicktoLayer(false,false,false,true) end function GVMemberListController:clickReduceScore() self.view:freshSureLayer(true, 'reduce') end function GVMemberListController:clickAddScore() self.view:freshSureLayer(true, 'add') end function GVMemberListController:clickCloseSureLayer() self.view:freshSureLayer(false) end function GVMemberListController:clickSureScore() local options = self.view:getScoreOptions() if not options.data or not options.mode or not options.newScore then tools.showRemind('操作失败') return end local groupInfo = self.group:getCurGroup() if not groupInfo then return end if options.state then tools.showRemind('该玩家正在游戏中') return end dump(options) local groupId = groupInfo.id self.group:setMemberScore(groupId, options) self:clickCloseSureLayer() end function GVMemberListController:clickNumber(sender) SoundMng.playEft('btn_click.mp3') local data = sender:getComponent("ComExtensionData"):getCustomProperty() self.view:setNewScore('input', data) end function GVMemberListController:clickDelete() SoundMng.playEft('btn_click.mp3') self.view:setNewScore('del') end function GVMemberListController:clickReenter() SoundMng.playEft('btn_click.mp3') self.view:setNewScore('reenter') end function GVMemberListController:finalize() for i = 1,#self.listener do self.listener[i]:dispose() end end function GVMemberListController:clickBack() self.emitter:emit('back') end return GVMemberListController
local Handler = require("cmdhndlr.core.handler").Handler local M = {} local BuildRunner = {} M.BuildRunner = BuildRunner function BuildRunner.new(bufnr, ...) local handler, err = Handler.new("build_runner", bufnr, ...) if err ~= nil then return nil, err end vim.validate({ build = { handler.build, "function" } }) local tbl = { _bufnr = bufnr, _handler = handler } return setmetatable(tbl, BuildRunner) end function BuildRunner.__index(self, k) return rawget(BuildRunner, k) or self._handler[k] end function BuildRunner.execute(self) local path = vim.api.nvim_buf_get_name(self._bufnr) local info_factory = self:info_factory() local output, err = self:build(path) return self:result(info_factory, output, err) end return M
--- Check whether a string is a suffix of self. -- @param s The suffix string to check for. -- @return True if self ends with s, otherwise false. -- @usage string.suffix("abcdef", "def") -- returns true -- @usage string.suffix("abcdef", "e") -- returns false function string:suffix(s) local pos = #self - #s + 1 local index = string.find(self, s, pos, true) return index ~= nil and index == pos end
local _, Private = ... if Private.initialized then local name = "nerien_ovale_deathknight_blood" local desc = string.format("[9.1] %s: Death Knight - Blood", Private.name) local code = [[ # Adapted from "[9.1.0] Advanced Blood Death Knight Guide for M+" # by Kyrasis-Stormreaver. # https://docs.google.com/document/d/1FJlB1T8ijaQLjY_cihyoyhLoi6lYRnT-N-ipVFCLidE Include(nerien_ovale_library) ### Definitions ### # Talents Define(antimagic_barrier_talent 22014) Define(blood_tap_talent 22135) Define(heartbreaker_talent 19165) Define(relish_in_blood_talent 22134) Define(tightening_grasp_talent 19226) Define(voracious_talent 19230) # Class Abilities Define(antimagic_shell 48707) SpellInfo(antimagic_shell cd=60 offgcd=1) SpellRequire(antimagic_shell cd add=-20 enabled=(HasTalent(antimagic_barrier_talent))) Define(antimagic_zone 51052) SpellInfo(antimagic_zone cd=120) Define(asphyxiate 221562) SpellInfo(asphyxiate cd=45) Define(blooddrinker 206931) SpellInfo(blooddrinker runes=1 runicpower=-10 cd=30 channel=3 tick=1) SpellRequire(blooddrinker unusable set=1 enabled=(not HasTalent(blooddrinker_talent))) Define(blooddrinker_talent 19166) Define(blood_boil 50842) SpellInfo(blood_boil cd=7.5) Define(blood_plague_debuff 55078) SpellInfo(blood_plague_debuff duration=24) SpellAddTargetDebuff(blood_boil blood_plague_debuff add=1) Define(blood_tap 221699) SpellInfo(blood_tap cd=0.5 charge_cd=60 runes=-1) SpellRequire(blood_tap unusable set=1 enabled=(not HasTalent(blood_tap_talent))) Define(bone_shield 195181) SpellInfo(bone_shield duration=30 max_stacks=10) SpellAddBuff(dancing_rune_weapon bone_shield add=5 enabled=(EquippedRuneforge(crimson_rune_weapon_runeforge))) SpellAddBuff(marrowrend bone_shield add=3) SpellAddBuff(tombstone bone_shield add=-5) Define(bonestorm 194844) SpellInfo(bonestorm runicpower=10 cd=60) SpellRequire(bonestorm unusable set=1 enabled=(not HasTalent(bonestorm_talent))) Define(bonestorm_talent 21209) Define(consumption 274156) SpellInfo(consumption cd=30) SpellRequire(consumption unusable set=1 enabled=(not HasTalent(consumption_talent))) Define(consumption_talent 19220) Define(crimson_scourge_buff 81141) SpellInfo(crimson_scourge_buff duration=15) SpellAddBuff(death_and_decay crimson_scourge_buff set=0) SpellRequire(death_and_decay runes set=0 enabled=(BuffPresent(crimson_scourge_buff))) SpellRequire(death_and_decay runicpower set=0 enabled=(BuffPresent(crimson_scourge_buff) and not HasTalent(relish_in_blood_talent))) SpellRequire(death_and_decay runicpower add=-10 enabled=(BuffPresent(crimson_scourge_buff) and HasTalent(relish_in_blood_talent))) SpellAddBuff(deaths_due crimson_scourge_buff set=0) SpellRequire(deaths_due runes set=0 enabled=(BuffPresent(crimson_scourge_buff))) SpellRequire(deaths_due runicpower set=0 enabled=(BuffPresent(crimson_scourge_buff) and not HasTalent(relish_in_blood_talent))) SpellRequire(deaths_due runicpower add=-10 enabled=(BuffPresent(crimson_scourge_buff) and HasTalent(relish_in_blood_talent))) Define(dancing_rune_weapon 49028) SpellInfo(dancing_rune_weapon cd=120) Define(dancing_rune_weapon_buff 81256) SpellInfo(dancing_rune_weapon_buff duration=8) SpellAddBuff(dancing_rune_weapon dancing_rune_weapon_buff add=1) Define(death_and_decay 43265) SpellInfo(death_and_decay runes=1 runicpower=-10 cd=30) Define(death_coil 47541) Define(death_and_decay_buff 188290) SpellInfo(death_and_decay_buff duration=10 tick=1) SpellAddBuff(death_and_decay death_and_decay_buff add=1) Define(deaths_due_buff 324165) SpellInfo(deaths_due_buff duration=12 tick=1) Define(deaths_due_debuff 324164) SpellInfo(deaths_due_debuff duration=12) SpellAddTargetDebuff(deaths_due deaths_due_debuff add=1) Define(death_grip 49576) SpellInfo(death_grip cd=25) Define(death_strike 49998) SpellInfo(death_strike runicpower=45) SpellRequire(death_strike runicpower add=-5 enabled=(SpellKnown(ossuary) and BuffStacks(bone_shield) >= 5)) Define(gorefiends_grasp 108199) SpellInfo(gorefiends_grasp cd=120) SpellRequire(gorefiends_grasp cd add=-30 enabled=(HasTalent(tightening_grasp_talent))) Define(heart_strike 206930) SpellInfo(heart_strike runes=1 runicpower=-10) SpellRequire(heart_strike runicpower add=-5 enabled=(Level() >= 23)) SpellRequire(heart_strike runicpower add=-2 enabled=(HasTalent(heartbreaker_talent))) Define(hemostasis_buff 273947) SpellInfo(hemostasis_buff duration=15 max_stacks=5) SpellAddBuff(death_strike hemostasis_buff set=0) Define(icebound_fortitude 48792) SpellInfo(icebound_fortitude cd=180 offgcd=1) Define(mark_of_blood 206940) SpellInfo(mark_of_blood cd=6 duration=15) SpellAddTargetDebuff(mark_of_blood mark_of_blood add=1) Define(marrowrend 195182) SpellInfo(marrowrend runes=2 runicpower=-20) Define(mind_freeze 47528) SpellInfo(mind_freeze cd=15 gcd=0 offgcd=1 interrupt=1) Define(ossuary 219786) Define(raise_dead 46585) SpellInfo(raise_dead cd=120 duration=60 totem=1 gcd=0 offgcd=1) SpellRequire(raise_dead unusable set=1 enabled=(pet.Present())) Define(rune_tap 194679) SpellInfo(rune_tap cd=25 offgcd=1 runes=1 runicpower=-10 duration=4) Define(sacrificial_pact 327574) SpellInfo(sacrificial_pact runicpower=20 cd=120) SpellRequire(sacrificial_pact unusable set=1 enabled=(TotemExpires(raise_dead))) Define(tombstone 219809) SpellInfo(tombstone cd=60) SpellRequire(tombstone unusable set=1 enabled=(not HasTalent(tombstone_talent))) Define(tombstone_talent 23454) Define(vampiric_blood 55233) SpellInfo(vampiric_blood cd=90 gcd=0 offgcd=1) # Covenant Abilities Define(abomination_limb 315443) SpellInfo(abomination_limb cd=120 duration=12 tick=1) SpellAddBuff(abomination_limb abomination_limb add=1) SpellAddBuff(abomination_limb bone_shield add=3) SpellRequire(abomination_limb unusable set=1 enabled=(not IsCovenant(necrolord))) Define(deaths_due 324128) SpellInfo(deaths_due cd=30 runes=1 runicpower=-10) SpellRequire(deaths_due unusable set=1 enabled=(not IsCovenant(night_fae))) SpellRequire(death_and_decay replaced_by set=deaths_due enabled=(IsCovenant(night_fae) and SpellKnown(deaths_due))) Define(shackle_the_unworthy 312202) SpellInfo(shackle_the_unworthy cd=60) SpellRequire(shackle_the_unworthy unusable set=1 enabled=(not IsCovenant(kyrian))) Define(swarming_mist 311648) SpellInfo(swarming_mist cd=60 runes=1 runicpower=-10 duration=8 tick=1) SpellRequire(swarming_mist unusable set=1 enabled=(not IsCovenant(venthyr))) SpellAddBuff(swarming_mist swarming_mist add=1) # Runeforge Legendary Effects Define(bryndaors_might_runeforge 6940) Define(crimson_rune_weapon_runeforge 6941) ### Functions ### AddFunction BloodInRange { target.InRange(death_strike) } AddFunction BloodHasPooledForBonestorm { # Bonestorm only with 3+ targets and Runic Power is above 90 for full healing ticks. HasTalent(bonestorm_talent) and not SpellCooldown(bonestorm) > 0 and Enemies(tagged=1) >= 3 and RunicPower() > 90 } AddFunction BloodIsPoolingForBonestorm { # Begin pooling for Bonestorm when it is down to 3 seconds left on the cooldown. HasTalent(bonestorm_talent) and SpellCooldown(bonestorm) < 3 and Enemies(tagged=1) >= 3 and not RunicPower() > 90 } AddFunction BloodDeathStrikeMinHealing { MaxHealth() * (7 + 3 * HasTalent(voracious_talent)) / 100 } AddFunction BloodDeathStrikeBaseHealing { if (IncomingDamage(5) / 4 > BloodDeathStrikeMinHealing()) (IncomingDamage(5) / 4) BloodDeathStrikeMinHealing() } AddFunction BloodDeathStrikeHealing { # Death Strike healing is increased by both Voracious and Hemostatis talents. BloodDeathStrikeBaseHealing() * ((100 + 20 * HasTalent(voracious_talent)) / 100) * ((100 + 8 * BuffStacks(hemostasis_buff)) / 100) } AddFunction BloodHeartStrikeMaxTargets { # Heart Strike hits 2 targets, but up to 5 targets if player is standing in Death and Decay. 2 + 3 * BuffPresent(death_and_decay_buff) } AddFunction BloodHeartStrikeTargets { # Return the number of targets that Heart Strike can hit. if (Enemies(tagged=1) <= BloodHeartStrikeMaxTargets()) Enemies(tagged=1) BloodHeartStrikeMaxTargets() } AddFunction BloodHeartStrikeRunicPower { # Return the amount of runic power generated by Heart Strike. if (Level() < 23) (10 + HasTalent(heartbreaker_talent) * 2 * BloodHeartStrikeTargets()) 15 + HasTalent(heartbreaker_talent) * 2 * BloodHeartStrikeTargets() } AddFunction BloodOssuaryThreshold { # Return the number of Bone Shield charges at which we should Marrowrend to maintain Ossuary. # Marrowrend if below 8 stacks of Bone Shield (7 stacks with Crimson Rune Weapon). # Bone Shield loses 1 stack every 2.5 seconds with incoming physical damage. # Keep Bone Shield stacks low when Dancing Rune Weapon (with Crimson Rune Weapon) or Abomination Limb is coming off cooldown. if (BuffPresent(dancing_rune_weapon_buff) or BuffRemaining(abomination_limb) > 6) (5) if (EquippedRuneforge(crimson_rune_weapon_runeforge) and SpellCooldown(dancing_rune_weapon) / 2.5 < 3) (4 + SpellCooldown(dancing_rune_weapon) / 2.5) if (IsCovenant(necrolord) and SpellCooldown(abomination_limb) / 2.5 < 3) (4 + SpellCooldown(abomination_limb) / 2.5) if EquippedRuneforge(crimson_rune_weapon_runeforge) (7) 8 } AddFunction BloodPrecombatShortCdActions { PrecombatShortCdActions() # Only Rune Tap if Bone Shield is down or about to expire. if (not BuffPresent(rune_tap) and BuffRemaining(bone_shield) < BaseDuration(rune_tap)) Spell(rune_tap) } AddFunction BloodShortCdActions { if Rune() < 3 { # Blood Tap if you have 2 charges, or are less than 5 seconds away from 2 charges of Blood Tap, and you have less than 3 Runes. if (Charges(blood_tap count=0) > 1.9) Spell(blood_tap) # Bank 2nd charge of Blood Tap unless healing is needed. if (HealthPercent() <= 60) { # Blood Tap if you have less than 3 Runes and less than 63 RP (57 RP with Bryndaor’s Might equipped). if (not EquippedRuneforge(bryndaors_might_runeforge) and RunicPower() < 63) Spell(blood_tap) if ( EquippedRuneforge(bryndaors_might_runeforge) and RunicPower() < 57) Spell(blood_tap) } } # (Venthyr) Swarming Mist with less than 67 RP (61 RP with Bryndaor’s Might equipped). if (not EquippedRuneforge(bryndaors_might_runeforge) and RunicPower() < 67) Spell(swarming_mist) if (EquippedRuneforge(bryndaors_might_runeforge) and RunicPower() < 61) Spell(swarming_mist) # (Kyrian) Shackle the Unworthy (with Combat Meditation enabled). Spell(shackle_the_unworthy) unless ((BuffRemaining(bone_shield) < GCD() + 2) and Spell(marrowrend)) or ((DebuffCountOnAny(blood_plague_debuff) < Enemies(tagged=1) or target.DebuffRefreshable(blood_plague_debuff)) and ((not BuffPresent(swarming_mist) and not BuffPresent(abomination_limb)) and Spell(blood_boil))) or ((3 < BuffRemaining(deaths_due_buff) and BuffRemaining(deaths_due_buff) < 5) and Spell(deaths_due)) or ((3 < target.DebuffRemaining(deaths_due_debuff) and target.DebuffRemaining(deaths_due_debuff) < 5) and Spell(deaths_due)) or (BuffPresent(death_and_decay_buff) and (((BuffRemaining(deaths_due_buff) < 3 or target.DebuffRemaining(deaths_due_debuff) < 3) and Spell(heart_strike)) or (BuffRemaining(death_and_decay_buff) < 3 and (((BuffRemaining(deaths_due_buff) - BuffRemaining(death_and_decay_buff) < 9) and Spell(heart_strike)) or ((target.DebuffRemaining(deaths_due_debuff) - BuffRemaining(death_and_decay_buff) < 9) and Spell(heart_strike)))))) or (BloodHasPooledForBonestorm() and Spell(bonestorm)) or ((not BloodIsPoolingForBonestorm() and RunicPowerDeficit() < 20) and Spell(death_strike)) or ((BuffStacks(bone_shield) < BloodOssuaryThreshold()) and Spell(marrowrend)) { # (Night Fae) Death and Decay Spell(deaths_due) unless ((TimeToRunes(3) < GCD()) and Spell(heart_strike)) { # Death and Decay when Crimson Scourge procs with 3+ targets. if (not BuffPresent(dancing_rune_weapon_buff) and BuffPresent(crimson_scourge_buff) and Enemies(tagged=1) >= 3) Spell(death_and_decay) unless ((Charges(blood_boil count=0) >= 1.8 and BuffStacks(hemostasis_buff) < 5) and Spell(blood_boil)) or ((EquippedRuneforge(crimson_rune_weapon_runeforge) and BuffPresent(dancing_rune_weapon_buff)) and Spell(heart_strike)) or ((Rune() >= 3) and Spell(heart_strike)) or ((BuffStacks(bone_shield) >= 8 and BuffRemaining(bone_shield) >= 7.5) and ((not IsCovenant(night_fae) and Rune() >= 2) or ((BuffPresent(dancing_rune_weapon_buff) and RunicPowerDeficit() > 50) and Spell(heart_strike)) or ((not BuffPresent(dancing_rune_weapon_buff) and BuffPresent(death_and_decay_buff) and Enemies(tagged=1) >= 3 and RunicPowerDeficit() > 40) and Spell(heart_strike)))) or ((BuffStacks(hemostasis_buff) < 5) and Spell(blood_boil)) { # Death and Decay when Crimson Scourge procs. if (not BuffPresent(dancing_rune_weapon_buff) and BuffPresent(crimson_scourge_buff)) { Spell(deaths_due) Spell(death_and_decay) } } } } # [*] (Necrolord) Fleshcraft. Spell(fleshcraft) } AddFunction BloodPrecombatMainActions { # [*] Blooddrinker when closing with the boss on the opener. if not BuffPresent(dancing_rune_weapon_buff) Spell(blooddrinker) if (BuffRemaining(bone_shield) < GCD() + 2) { if not EquippedRuneforge(crimson_rune_weapon_runeforge) Spell(marrowrend) # [*] Skip Marrowrend with Crimson Rune Weapon if Dancing Rune Weapon is available out of combat. if (EquippedRuneforge(crimson_rune_weapon_runeforge) and SpellCooldown(dancing_rune_weapon) > 0) Spell(marrowrend) } } AddFunction BloodMainActions { if (HealthPercent() <= 60) { if (Enemies(tagged=1) >= 3) { # [*] Bonestorm if you are below 60% health. if BloodHasPooledForBonestorm() Spell(bonestorm) # [*] Consumption with 3+ targets. Spell(consumption) } # Death Strike if you are below 60% Health. if (not BloodIsPoolingForBonestorm() and BloodDeathStrikeHealing() <= HealthMissing()) Spell(death_strike) } # Marrowrend if Bone Shield is not active or about to expire. if (BuffRemaining(bone_shield) < GCD() + 2) Spell(marrowrend) # Blood Boil if a target does not have Blood Plague and (Venthyr) Swarming Mist or (Necrolord) Abomination Limb is not active. if DebuffCountOnAny(blood_plague_debuff) < Enemies(tagged=1) or target.DebuffRefreshable(blood_plague_debuff) { if (not BuffPresent(swarming_mist) and not BuffPresent(abomination_limb)) Spell(blood_boil) } # (Night Fae) Death and Decay when the duration of the Death’s Due buff/debuff is about to expire, but with enough remaining time to Heart Strike. if (3 < BuffRemaining(deaths_due_buff) and BuffRemaining(deaths_due_buff) < 5) Spell(deaths_due) if (3 < target.DebuffRemaining(deaths_due_debuff) and target.DebuffRemaining(deaths_due_debuff) < 5) Spell(deaths_due) # (Night Fae) Heart Strike: # while in Death and Decay when the duration of the Death’s Due buff/debuff is about to expire or # (the duration of our Death and Decay ground effect is about to expire and # the Death’s Due buff/debuff won’t outlast the Death and Decay by at least ~9 seconds). if BuffPresent(death_and_decay_buff) { if (BuffRemaining(deaths_due_buff) < 3 or target.DebuffRemaining(deaths_due_debuff) < 3) Spell(heart_strike) if BuffRemaining(death_and_decay_buff) < 3 { if (BuffRemaining(deaths_due_buff) - BuffRemaining(death_and_decay_buff) < 9) Spell(heart_strike) if (target.DebuffRemaining(deaths_due_debuff) - BuffRemaining(death_and_decay_buff) < 9) Spell(heart_strike) } } # [*] Use Bonestorm if we have pooled enough Runic Power. if BloodHasPooledForBonestorm() Spell(bonestorm) # Death Strike when Runic Power is above 105 (121 with Rune of Hysteria). if (not BloodIsPoolingForBonestorm() and RunicPowerDeficit() < 20) Spell(death_strike) # Marrowrend if below 8 stacks of Bone Shield (7 stacks with Crimson Rune Weapon). if (BuffStacks(bone_shield) < BloodOssuaryThreshold()) Spell(marrowrend) # Heart Strike with, or when 1.5 second away from, having more than 3 Runes. if (TimeToRunes(3) < GCD()) Spell(heart_strike) # Blood Boil with 2 charges and less than 5 stacks of Hemostasis. if (Charges(blood_boil count=0) >= 1.8 and BuffStacks(hemostasis_buff) < 5) Spell(blood_boil) # [*] Heart Strike with Crimson Rune Weapon and Dancing Rune Weapon is active. # [*] This depletes runes ahead of gaining 40% increased rune regeneration for 10s after Dancing Rune Weapon expires. if (EquippedRuneforge(crimson_rune_weapon_runeforge) and BuffPresent(dancing_rune_weapon_buff)) Spell(heart_strike) # Heart Strike with 3 Runes. if (Rune() >= 3) Spell(heart_strike) # Heart Strike with: # ((not Night Fae and with 2 runes) or # ([Dancing Rune Weapon] and less than 76 RP (86 RP with [Rune of Hysteria])) or # ([Death and Decay] with 3+ targets without [Dancing Rune Weapon] and less than 81 RP (92 RP with [Rune of Hysteria]))) # and 8+ stacks of Bone Shield and 7.5+ seconds left of Bone Shield duration. if (BuffStacks(bone_shield) >= 8 and BuffRemaining(bone_shield) >= 7.5) { if (not IsCovenant(night_fae) and Rune() >= 2) Spell(heart_strike) if (BuffPresent(dancing_rune_weapon_buff) and RunicPowerDeficit() > 50) Spell(heart_strike) if (not BuffPresent(dancing_rune_weapon_buff) and BuffPresent(death_and_decay_buff) and Enemies(tagged=1) >= 3 and RunicPowerDeficit() > 40) Spell(heart_strike) } # Blood Boil with 1 charge and less than 5 stacks of Hemostasis. if (BuffStacks(hemostasis_buff) < 5) Spell(blood_boil) # [*] Fillers that don't consume Runes or Runic Power. if (target.DebuffExpires(mark_of_blood) and target.IsTargetingPlayer()) Spell(mark_of_blood) if not BuffPresent(dancing_rune_weapon_buff) Spell(blooddrinker) Spell(consumption) } AddFunction BloodPrecombatCdActions { PrecombatCdActions() Spell(abomination_limb) Spell(dancing_rune_weapon) Spell(raise_dead) } AddFunction BloodOffensiveCdActions { if not BuffPresent(dancing_rune_weapon_buff) { Spell(abomination_limb) Spell(dancing_rune_weapon) Spell(raise_dead) # Sacrifice ghoul with at least 5 enemies or 15 seconds left. if (Enemies(tagged=1) >= 5 or TotemRemaining(raise_dead) < 15) Spell(sacrificial_pact) } } AddFunction BloodDefensiveCdActions { if (IncomingMagicDamage(1.5) > 0) Spell(antimagic_shell) if (BuffStacks(bone_shield) >= 6) Spell(tombstone) Spell(dancing_rune_weapon) # (Necrolord) Abomination Limb if below 6 stacks of Bone Shield or for threat generation. if (not BuffPresent(dancing_rune_weapon_buff) and BuffStacks(bone_shield) < 6) Spell(abomination_limb) Spell(vampiric_blood) Spell(icebound_fortitude) if (IncomingMagicDamage(1.5) > 0) Spell(antimagic_zone) # Only suggest Rune Tap if Heart Strike won't grant enough Runic Power # for a Death Strike heal. if (not BuffPresent(rune_tap) and RunicPower() < RunicPowerCost(death_strike) - BloodHeartStrikeRunicPower()) Spell(rune_tap) } AddFunction BloodCdActions { BloodDefensiveCdActions() } AddFunction BloodInterruptActions { if not focus.IsFriend() and focus.Casting() { if (focus.InRange(mind_freeze) and focus.IsInterruptible()) Spell(mind_freeze text=focus) if not focus.Classification(worldboss) { if focus.InRange(asphyxiate) Spell(asphyxiate text=focus) if focus.InRange(death_grip) Spell(death_grip text=focus) if (focus.Distance() < 15) Spell(gorefiends_grasp text=focus) } } if not target.IsFriend() and target.Casting() { if (target.InRange(mind_freeze) and target.IsInterruptible()) Spell(mind_freeze) if not target.Classification(worldboss) { if target.InRange(asphyxiate) Spell(asphyxiate) if target.InRange(death_grip) Spell(death_grip) if (target.Distance() < 15) Spell(gorefiends_grasp) } } InterruptActions() } AddFunction BloodDispelActions { OffensiveDispelActions() DefensiveDispelActions() } AddFunction BloodHealActions { ItemHealActions() } ### User Interface ### AddIcon help=interrupt size=small { BloodInterruptActions() BloodDispelActions() BloodHealActions() } AddIcon help=shortcd { if not InCombat() BloodPrecombatShortCdActions() BloodShortCdActions() } AddIcon enemies=1 help=main { if not InCombat() BloodPrecombatMainActions() BloodMainActions() } AddIcon help=aoe { if not InCombat() BloodPrecombatMainActions() BloodMainActions() } AddIcon help=cd { if not InCombat() BloodPrecombatCdActions() BloodCdActions() } AddIcon help=trinkets size=small { BloodOffensiveCdActions() if not BloodInRange() Texture(misc_arrowlup help=L(not_in_melee_range)) Item(Trinket0Slot usable=1 text=13) Item(Trinket1Slot usable=1 text=14) } ]] Private.scripts:registerScript("DEATHKNIGHT", "blood", name, desc, code, "script") end
-- 协议号规范 -- 0x0100 ~ 0x0fff 服务器给客户端发 -- 0x1000 ~ 0x4fff 与游戏服之间的rpc -- 0x9000 ~ 0xcfff 玩家离线操作 local opcode = {} local code2name = {} local code2module = {} local code2simplename = {} local code2session = {} local code2urlrequest = {} local function REG(code, message_name, urlrequest, session) assert(not code2name[code], string.format("code 0x%x exist", code)) local namespace = opcode for v in string.gmatch(message_name, "([^.]+)[.]") do namespace[v] = rawget(namespace, v) or setmetatable({}, { __index = function(_, k) error(k) end}) namespace = namespace[v] end namespace[string.match(message_name, "[%w_]+$")] = code code2name[code] = message_name code2urlrequest[code] = urlrequest code2session[code] = session code2module[code] = string.lower(string.match(message_name, "^[^.]+")) code2simplename[code] = string.match(message_name, "[^.]+$") end opcode.REG = REG function opcode.toname(code) return code2name[code] end function opcode.tomodule(code) return code2module[code] end function opcode.tosimplename(code) return code2simplename[code] end function opcode.has_session(code) return code2session[code] end function opcode.urlrequest(code) return code2urlrequest[code] end function opcode.get_code2name() return code2name end return opcode
package.path = package.path .. ";../src/?.lua" local serialize = require "savelua" it("handles a basic table", function() local basicTable = { 1, 2, 3, one = 1, two = 2, three = 3 } local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.same(basicTable, data) end) it("handles a basic table with metatable", function() local basicTable = { 1, 2, 3, one = 1, two = 2, three = 3 } local mt = { __call = function() return "hello from __call" end } setmetatable(basicTable, mt) local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.same(basicTable, data) assert.are.equals("hello from __call", data()) end) it("handles table self reference: t[t] = t, t[k] = t", function() local basicTable = {} basicTable.loop = basicTable basicTable[basicTable] = basicTable local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.equals(data, data.loop) assert.are.equals(data, data[data]) end) it("handles table self reference: t[t] = v", function() local basicTable = {} basicTable[basicTable] = "loop" local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.equals("loop", data[data]) end) it("handles deep self reference", function() local basicTable = { loop = {} } basicTable.loop.deep = basicTable local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.equals(data, data.loop.deep) end) it("handles complex deep self reference 1", function() local basicTable = { loop = {} } basicTable.loop.deep = basicTable basicTable.loop.deep.gotcha = basicTable.loop local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.equals(data, data.loop.deep, basicTable.loop.deep.gotcha) end) it("handles complex deep self reference 2", function() local basicTable = { loop = {}, intermediate = { "intermediate" } } basicTable.loop.deep = basicTable basicTable.loop.gotcha = basicTable.intermediate local serialized = serialize(basicTable) local deserialized = (loadstring or load)(serialized) assert.is_not_nil(deserialized) local ok, data = pcall(deserialized) assert.is_true(ok) assert.are.equals(data, data.loop.deep) assert.are.equals(data.intermediate, data.loop.gotcha) end)
-- Reboot mod for Minetest -- Waits for the last player to leave then shuts the server down -- -- Copyright © 2018 by luk3yx -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE. local reboot = false local checkReboot checkReboot = function() if reboot and next(minetest.get_connected_players()) == nil then -- Time to reboot if minetest.global_exists('irc') then irc.say("The server is empty! Rebooting...") end minetest.request_shutdown("Rebooting...", true, 1) end end minetest.register_on_leaveplayer(checkReboot) minetest.register_chatcommand("reboot", { privs = {server = true}, params = "", description = "Reboots the server next time it is empty.", func = function() if reboot then return false, "There is already a reboot pending!" end reboot = true checkReboot() return true, "Reboot scheduled!" end }) minetest.register_chatcommand("cancelreboot", { privs = {server = true}, params = "", description = "Cancels a pending reboot.", func = function() if not reboot then return false, "There is no reboot to cancel!" end reboot = false return true, "Reboot aborted!" end })
-- [impl->dsn~get-a-role-mask~1] --[[ CREATE OR REPLACE LUA SCALAR SCRIPT BIT_POSITIONS(num DOUBLE) EMITS(pos DOUBLE) AS --]] function run(ctx) num = ctx.num index = 1 while num > 0 do rest = math.fmod(num, 2) if rest == 1 then ctx.emit(index) end num = (num - rest) / 2 index = index + 1 end end --[[ / --]]
module 'bugly' path = "../../frameworks/libxgame/src/bugly" headers = [[ #include "lua-bindings/lua_conv.h" #include "lua-bindings/lua_conv_manual.h" #include "cclua/xlua.h" #include "bugly/CrashReport.h" ]] make_luacls = function (cppname) cppname = string.gsub(cppname, "^cclua::", "cclua.") cppname = string.gsub(cppname, "::", ".") return cppname end include "conf/exclude-type.lua" ifdef 'CCLUA_BUILD_BUGLY' typeconf "cclua::CrashReport::LogLevel" typeconf "cclua::CrashReport" .require 'cclua::runtime::registerFeature("bugly", true);' endif ''
local config = { max_depth = { include = 100, expansion = 100, eval = 100 }, reserved = { appendvararg = "_Appendvararg", defined = "_Defined", dw = "_Dw", identity = "_Identity", labelcontext = "_Labelcontext", litmap = "_Litmap", macrounique = "_Macrounique", model = "_Model", next = "_Next", org = "_Org", peerlabel = "_Peerlabel", superlabel = "_Superlabel", this = "_This", vararg = "_Vararg", varargsize = "_Varargsize", }, litmap = {} } for ix = 0, 127 do config.litmap[ix] = ix end return config
-- cclog cclog = function(...) print(string.format(...)) end -- for CCLuaEngine traceback function __G__TRACKBACK__(msg) cclog("----------------------------------------") cclog("LUA ERROR: " .. tostring(msg) .. "\n") cclog(debug.traceback()) cclog("----------------------------------------") end local function main() -- avoid memory leak collectgarbage("setpause", 100) collectgarbage("setstepmul", 5000) require "hello2" cclog("result is " .. myadd(1, 1)) --------------- local visibleSize = CCDirector:sharedDirector():getVisibleSize() local origin = CCDirector:sharedDirector():getVisibleOrigin() -- add the moving dog local function creatDog() local frameWidth = 105 local frameHeight = 95 -- create dog animate local textureDog = CCTextureCache:sharedTextureCache():addImage("dog.png") local rect = CCRectMake(0, 0, frameWidth, frameHeight) local frame0 = CCSpriteFrame:createWithTexture(textureDog, rect) rect = CCRectMake(frameWidth, 0, frameWidth, frameHeight) local frame1 = CCSpriteFrame:createWithTexture(textureDog, rect) local spriteDog = CCSprite:createWithSpriteFrame(frame0) spriteDog.isPaused = false spriteDog:setPosition(origin.x, origin.y + visibleSize.height / 4 * 3) local animFrames = CCArray:create() animFrames:addObject(frame0) animFrames:addObject(frame1) local animation = CCAnimation:createWithSpriteFrames(animFrames, 0.5) local animate = CCAnimate:create(animation); spriteDog:runAction(CCRepeatForever:create(animate)) -- moving dog at every frame local function tick() if spriteDog.isPaused then return end local x, y = spriteDog:getPosition() if x > origin.x + visibleSize.width then x = origin.x else x = x + 1 end spriteDog:setPositionX(x) end CCDirector:sharedDirector():getScheduler():scheduleScriptFunc(tick, 0, false) return spriteDog end -- create farm local function createLayerFarm() local layerFarm = CCLayer:create() -- add in farm background local bg = CCSprite:create("farm.jpg") bg:setPosition(origin.x + visibleSize.width / 2 + 80, origin.y + visibleSize.height / 2) layerFarm:addChild(bg) -- add land sprite for i = 0, 3 do for j = 0, 1 do local spriteLand = CCSprite:create("land.png") spriteLand:setPosition(200 + j * 180 - i % 2 * 90, 10 + i * 95 / 2) layerFarm:addChild(spriteLand) end end -- add crop local frameCrop = CCSpriteFrame:create("crop.png", CCRectMake(0, 0, 105, 95)) for i = 0, 3 do for j = 0, 1 do local spriteCrop = CCSprite:createWithSpriteFrame(frameCrop); spriteCrop:setPosition(10 + 200 + j * 180 - i % 2 * 90, 30 + 10 + i * 95 / 2) layerFarm:addChild(spriteCrop) end end -- add moving dog local spriteDog = creatDog() layerFarm:addChild(spriteDog) -- handing touch events local touchBeginPoint = nil local function onTouchBegan(x, y) cclog("onTouchBegan: %0.2f, %0.2f", x, y) touchBeginPoint = {x = x, y = y} spriteDog.isPaused = true -- CCTOUCHBEGAN event must return true return true end local function onTouchMoved(x, y) cclog("onTouchMoved: %0.2f, %0.2f", x, y) if touchBeginPoint then local cx, cy = layerFarm:getPosition() layerFarm:setPosition(cx + x - touchBeginPoint.x, cy + y - touchBeginPoint.y) touchBeginPoint = {x = x, y = y} end end local function onTouchEnded(x, y) cclog("onTouchEnded: %0.2f, %0.2f", x, y) touchBeginPoint = nil spriteDog.isPaused = false end local function onTouch(eventType, x, y) if eventType == "began" then return onTouchBegan(x, y) elseif eventType == "moved" then return onTouchMoved(x, y) else return onTouchEnded(x, y) end end layerFarm:registerScriptTouchHandler(onTouch) layerFarm:setTouchEnabled(true) return layerFarm end -- create menu local function createLayerMenu() local layerMenu = CCLayer:create() local menuPopup, menuTools, effectID local function menuCallbackClosePopup() -- stop test sound effect SimpleAudioEngine:sharedEngine():stopEffect(effectID) menuPopup:setVisible(false) end local function menuCallbackOpenPopup() -- loop test sound effect local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav") effectID = SimpleAudioEngine:sharedEngine():playEffect(effectPath) menuPopup:setVisible(true) end -- add a popup menu local menuPopupItem = CCMenuItemImage:create("menu2.png", "menu2.png") menuPopupItem:setPosition(0, 0) menuPopupItem:registerScriptTapHandler(menuCallbackClosePopup) menuPopup = CCMenu:createWithItem(menuPopupItem) menuPopup:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 2) menuPopup:setVisible(false) layerMenu:addChild(menuPopup) -- add the left-bottom "tools" menu to invoke menuPopup local menuToolsItem = CCMenuItemImage:create("menu1.png", "menu1.png") menuToolsItem:setPosition(0, 0) menuToolsItem:registerScriptTapHandler(menuCallbackOpenPopup) menuTools = CCMenu:createWithItem(menuToolsItem) local itemWidth = menuToolsItem:getContentSize().width local itemHeight = menuToolsItem:getContentSize().height menuTools:setPosition(origin.x + itemWidth/2, origin.y + itemHeight/2) layerMenu:addChild(menuTools) return layerMenu end -- play background music, preload effect -- uncomment below for the BlackBerry version -- local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.ogg") local bgMusicPath = CCFileUtils:sharedFileUtils():fullPathForFilename("background.mp3") SimpleAudioEngine:sharedEngine():playBackgroundMusic(bgMusicPath, true) local effectPath = CCFileUtils:sharedFileUtils():fullPathForFilename("effect1.wav") SimpleAudioEngine:sharedEngine():preloadEffect(effectPath) -- run local sceneGame = NdCxControl.NdScene:node() sceneGame:addChild(createLayerFarm()) sceneGame:addChild(createLayerMenu()) CCDirector:sharedDirector():runWithScene(sceneGame) end xpcall(main, __G__TRACKBACK__)
local Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118 } ESX = nil local HasAlreadyEnteredMarker = false local LastZone = nil local CurrentAction = nil local CurrentActionMsg = '' local CurrentActionData = {} local ZoneId = '' local MenuActions = {} local MenuOpen = false local RentedBike = false local MenuOpen = false local Parachute = false Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj)ESX = obj end) Citizen.Wait(0) end Citizen.Wait(5000) ESX.TriggerServerCallback('drp_recreation:bikerental', function(status) RentedBike = status TriggerEvent('esx:removeWeapon', 'GADGET_PARACHUTE') end, "check") end) AddEventHandler('drp_recreation:hasEnteredMarker', function(zone) CurrentAction = MenuActions.MenuTrigger CurrentActionMsg = MenuActions.MenuMessage CurrentActionData = {zone = zone} end) AddEventHandler('drp_recreation:hasExitedMarker', function(zone) CurrentAction = nil ESX.UI.Menu.CloseAll() end) AddEventHandler('onResourceStop', function(resource) if resource == GetCurrentResourceName() then if MenuOpen then ESX.UI.Menu.CloseAll() end end end) Citizen.CreateThread(function() for k, v in pairs(Config.Zones) do if v.EnableBlips then for i = 1, #v.Pos, 1 do local blip = AddBlipForCoord(v.Pos[i].x, v.Pos[i].y, v.Pos[i].z) SetBlipSprite(blip, v.BlipSprite) SetBlipDisplay(blip, 4) SetBlipScale(blip, v.BlipScale) SetBlipColour(blip, v.BlipColor) SetBlipAsShortRange(blip, true) BeginTextCommandSetBlipName("STRING") AddTextComponentString(v.Name) EndTextCommandSetBlipName(blip) end end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local ped = PlayerPedId() local coords = GetEntityCoords(ped) local canSleep = true for k, v in pairs(Config.Zones) do for i = 1, #v.Pos, 1 do if (v.Enable and GetDistanceBetweenCoords(coords, v.Pos[i].x, v.Pos[i].y, v.Pos[i].z, true) < v.DrawDistance) then if k == "BikeRental" and RentedBike then DrawMarker(v.MarkerType, v.Pos[i].x, v.Pos[i].y, v.Pos[i].z, 0.0, 0.0, 0.0, 0, 0.0, 0.0, v.ZoneSize.x, v.ZoneSize.y, v.ZoneSize.z, v.RentetMarkerColor.r, v.RentetMarkerColor.g, v.RentetMarkerColor.b, 100, false, true, 2, false, false, false, false) else DrawMarker(v.MarkerType, v.Pos[i].x, v.Pos[i].y, v.Pos[i].z, 0.0, 0.0, 0.0, 0, 0.0, 0.0, v.ZoneSize.x, v.ZoneSize.y, v.ZoneSize.z, v.MarkerColor.r, v.MarkerColor.g, v.MarkerColor.b, 100, false, true, 2, false, false, false, false) end canSleep = false end end end if canSleep then Citizen.Wait(500) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) local ped = PlayerPedId() local coords = GetEntityCoords(ped) local isInMarker = false local currentZone = nil for k, v in pairs(Config.Zones) do for i = 1, #v.Pos, 1 do if (v.Enable and GetDistanceBetweenCoords(coords, v.Pos[i].x, v.Pos[i].y, v.Pos[i].z, true) < 1.5) then isInMarker = true ShopItems = v.Items MenuActions = v.MenuActions currentZone = k LastZone = k ZoneId = i end end end if isInMarker and not HasAlreadyEnteredMarker then HasAlreadyEnteredMarker = true TriggerEvent('drp_recreation:hasEnteredMarker', currentZone) end if not isInMarker and HasAlreadyEnteredMarker then HasAlreadyEnteredMarker = false TriggerEvent('drp_recreation:hasExitedMarker', LastZone) end if not HasAlreadyEnteredMarker then Citizen.Wait(500) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(0) if CurrentAction ~= nil then local ped = PlayerPedId() if CurrentActionData.zone == "BikeRental" and IsPedOnAnyBike(ped) and RentedBike then ESX.ShowHelpNotification(_U('return_bike')) else ESX.ShowHelpNotification(CurrentActionMsg) end if IsControlJustReleased(0, Keys['E']) then if CurrentActionData.zone == "Basejumping" then OpenMenu(CurrentActionData.zone) elseif CurrentActionData.zone == "BikeRental" then if IsPedOnAnyBike(ped) and RentedBike then ESX.TriggerServerCallback('drp_recreation:bikerental', function(status) transition(0) ESX.Game.DeleteVehicle(GetVehiclePedIsIn(ped, false)) RentedBike = status end, false) else OpenMenu(CurrentActionData.zone) end end CurrentAction = nil end else Citizen.Wait(500) end end end) function OpenMenu(zone) if zone == "Basejumping" then ESX.ShowNotification(_U('caution')) end local elements = {} MenuOpen = true for i = 1, #Config.Zones[zone].Items, 1 do local item = Config.Zones[zone].Items[i] if Config.Zones[zone].Free then table.insert(elements, { label = item.label, item = item.item, action = Config.Zones[zone].MenuActions.MenuTrigger, itemId = i, itemType = Config.Zones[zone].ItemType, }) else if zone == "BikeRental" and RentedBike then table.insert(elements, { label = ('%s - <span style="color: #90ee90;">%s</span>'):format(item.label, _U('item_price', Config.CurrencyPrefix, ESX.Math.GroupDigits(item.price * Config.Zones[zone].Multiplier), Config.CurrencySuffix)), item = item.item, action = Config.Zones[zone].MenuActions.MenuTrigger, itemId = i, itemType = Config.Zones[zone].ItemType, }) else table.insert(elements, { label = ('%s - <span style="color: #90ee90;">%s</span>'):format(item.label, _U('item_price', Config.CurrencyPrefix, ESX.Math.GroupDigits(item.price), Config.CurrencySuffix)), item = item.item, action = Config.Zones[zone].MenuActions.MenuTrigger, itemId = i, itemType = Config.Zones[zone].ItemType, }) end end end ESX.UI.Menu.CloseAll() ESX.UI.Menu.Open('default', GetCurrentResourceName(), 'multimenu', { title = Config.Zones[zone].MenuTitle, align = 'top-left', elements = elements }, function(data, menu) if data.current.action == 'bikerental_menu' then ESX.TriggerServerCallback('drp_recreation:payment', function(payed) if payed then menu.close() MenuOpen = false local ped = PlayerPedId() local coords = GetEntityCoords(ped) local heading = GetEntityHeading(ped) transition(0) ESX.Game.SpawnVehicle(data.current.item, coords, heading, function(vehicle) TaskWarpPedIntoVehicle(ped, vehicle, -1) end) ESX.ShowNotification(_U('enjoy')) ESX.TriggerServerCallback('drp_recreation:bikerental', function(status) RentedBike = status end, true) else ESX.ShowNotification(_U('not_enough_money')) menu.close() end end, zone, data.current.itemId, data.current.itemType) elseif data.current.action == 'basejumping_menu' then ESX.TriggerServerCallback('drp_recreation:payment', function(payed) if payed then menu.close() MenuOpen = false local ped = PlayerPedId() DoScreenFadeOut(1000) while not IsScreenFadedOut() do Citizen.Wait(10) end ESX.Game.Teleport(ped, vector3(Config.Zones[zone].TelePos[ZoneId].x, Config.Zones[zone].TelePos[ZoneId].y, Config.Zones[zone].TelePos[ZoneId].z), function() Parachute = true SetEntityHeading(ped, Config.Zones[zone].TelePos[ZoneId].h) ParachuteRelease() end) ESX.ShowNotification(_U('enjoy')) else ESX.ShowNotification(_U('not_enough_money')) menu.close() end end, zone, data.current.itemId, data.current.itemType) else menu.close() end end, function(data, menu) MenuOpen = false menu.close() CurrentAction = MenuActions.MenuTrigger CurrentActionMsg = MenuActions.MenuMessage CurrentActionData = {zone = zone} end, function(data, menu) end) end function ParachuteRelease() Citizen.CreateThread(function() while Parachute do Citizen.Wait(0) local ped = PlayerPedId() if IsPedInParachuteFreeFall(ped) then ForcePedToOpenParachute(ped) Parachute = false Citizen.Wait(900) DoScreenFadeIn(3000) end end end) end function transition(timer) DoScreenFadeOut(1000) while not IsScreenFadedOut() do Citizen.Wait(10) end Citizen.Wait(timer) DoScreenFadeIn(3000) end
-- Exposed variables local FRIENDLY_EXPLOSION = script:GetCustomProperty("FriendlyExplosionDamage") local EXPLOSION_DAMAGE_RANGE = script:GetCustomProperty("ExplosionDamageRange") local EXPLOSION_RADIUS = script:GetCustomProperty("ExplosionRadius") local EXPLOSION_KNOCKBACK_SPEED = script:GetCustomProperty("ExplosionKnockbackSpeed") local propDestructableManagerScript = script:GetCustomProperty("DestructableManagerScript") destructableMgr = require(propDestructableManagerScript) owner = nil sourceAbility = nil -- nil Blast(Vector3) -- Creates a explosion at the projectile impact position -- Damages players within the blast function Blast(center) local players = Game.FindPlayersInSphere(center, EXPLOSION_RADIUS) for _, player in pairs(players) do local canDamage = true if owner ~= nil then -- Checks to see if friendly fire off and is friendly if not Teams.AreTeamsEnemies(player.team, owner.team) and not FRIENDLY_EXPLOSION then canDamage = false end end -- If canDamage is true and there is no objects obstructing the explosion then damage the player if canDamage then local displacement = player:GetWorldPosition() - center local obscured = true -- raycast to player's center -- so long as it hits nothing, or hits the player, damage can proceed local centerCast = World.Raycast(center, player:GetWorldPosition() + Vector3.New(0, 0, 100)) if (not centerCast or centerCast.other.name == player.name) then obscured = false end if (not obscured) then -- The farther the player from the blast the less damage that player takes local minDamage = EXPLOSION_DAMAGE_RANGE.x local maxDamage = EXPLOSION_DAMAGE_RANGE.y displacement.z = 0 local t = (displacement).size / EXPLOSION_RADIUS local damageAmount = CoreMath.Lerp(maxDamage, minDamage, t) -- Create damage information local damage = Damage.New(damageAmount) damage.sourcePlayer = owner damage.sourceAbility = sourceAbility -- Apply damage to player player:ApplyDamage(damage) -- Create a direction at which the player is pushed away from the blast player:AddImpulse((displacement):GetNormalized() * player.mass * EXPLOSION_KNOCKBACK_SPEED) end end end local vases = World.FindObjectsByName("Destructible Vase") for _,v in pairs(vases) do if ((center - v:GetWorldPosition()).size <= EXPLOSION_RADIUS) then -- break the vase Task.Spawn(function() destructableMgr.DamageObject(10, v) end) end end end
return { win = { conquer_lesimas = "信じられない!あなたはネフィアの迷宮「レシマス」を制覇した!", watch_event_again = "達成のシーンをもう一度再現する?", window = { arrived_at_tyris = function(_1, _2, _3) return ("%s年%s月%s日に、あなたはノースティリスに到着した。") :format(_1, _2, _3) end, caption = "制覇までの軌跡", comment = function(_1) return ("あなたは「%s」とコメントした。") :format(_1) end, have_killed = function(_1, _2) return ("最深で%s階相当まで到達し、%s匹の敵を殺して、") :format(_1, _2) end, lesimas = function(_1, _2, _3) return ("%s年%s月%s日にレシマスを制覇して、") :format(_1, _2, _3) end, score = function(_1) return ("現在%s点のスコアを叩き出している。") :format(_1) end, title = "*勝利*", your_journey_continues = "…あなたの旅はまだ終わらない。" }, you_acquired_codex = function(_1, _2) return ("%s%sに祝福あれ!あなたは遂にレシマスの秘宝を手にいれた!") :format(_1, _2) end, words = { _0 = "遂に…!", _1 = "当然の結果だ", _2 = "おぉぉぉぉ!", _3 = "ふっ", _4 = "今日は眠れないな", _5 = "またそんな冗談を" }, event = { text = { _0 = "「お前がここに辿り着くことは」台座から、何かの声が聞こえる。", _1 = "「決まっていたことなのだ…遅かれ早かれな」", _2 = "部屋の空気が突然緊張し、あなたの前に端麗な青年が現れた。", _3 = "「我々からすれば、複雑性の一面に過ぎないが、人間は運命とでも呼ぶのだろう?」", _4 = "あなたは懸命に脚の震えを抑えようとしたが、難しかった。", _5 = "華奢に見える幼顔の男の影は、人のものではない。", _6 = "あどけない瞳の奥に、あなたは底知れない力と闇を感じた。", _7 = "「ネフィアの永遠の盟約に基づき」青年は台座の横の死体を指し、皮肉な微笑を送った。", _8 = "「この哀れな老人が守っていたものは、今からお前のものだ」", _9 = "あなたは、台座の上に置かれている絢爛な装飾の本を、いぶかしげに眺めた。", _10 = "青年は悪戯っぽくニヤリと笑い、壁に寄りかかった。", _11 = "…どれくらい時間がたっただろう。氷の瞳の男は、いつの間にか姿を消していた。あなたは不安を振り払い、ゆっくりと本に手を伸ばした…", } } }, }
ENT.Type = "brush"; ENT.Base = "base_brush"; function ENT:GoToNextLevel() game.ConsoleCommand( "changelevel " .. self.NextMap .. "\n" ); end function ENT:AcceptInput( name ) if( name == "ChangeLevel" ) then self:GoToNextLevel(); end end function ENT:Touch( e ) if( !self.NoTouch ) then self:GoToNextLevel(); end end function ENT:KeyValue( key, value ) if( key == "landmark" ) then self.Landmark = value; end if( key == "map" ) then self.NextMap = value; end if( key == "spawnflags" ) then self.NoTouch = ( bit.band( tonumber( value ), 1 ) == 1 ); end end
require'nvim-treesitter.configs'.setup { ensure_installed = "maintained", -- one of "all", "maintained" (parsers with maintainers), or a list of languages -- ensure_installed = { "norg", "norg_meta", "norg_table", "haskell", "cpp", "c", "javascript", "markdown" }, sync_install = false, -- install languages synchronously (only applied to `ensure_installed`) -- ignore_install = { "javascript" }, -- List of parsers to ignore installing highlight = { enable = true, -- false will disable the whole extension -- disable = { "c", "rust" }, -- list of language that will be disabled -- Setting this to true will run `:h syntax` and tree-sitter at the same time. -- Set this to `true` if you depend on 'syntax' being enabled (like for indentation). -- Using this option may slow down your editor, and you may see some duplicate highlights. -- Instead of true it can also be a list of languages additional_vim_regex_highlighting = false, }, } local parser_configs = require('nvim-treesitter.parsers').get_parser_configs() parser_configs.norg = { install_info = { url = "https://github.com/nvim-neorg/tree-sitter-norg", files = { "src/parser.c", "src/scanner.cc" }, branch = "main" }, } parser_configs.norg_meta = { install_info = { url = "https://github.com/nvim-neorg/tree-sitter-norg-meta", files = { "src/parser.c" }, branch = "main" }, } parser_configs.norg_table = { install_info = { url = "https://github.com/nvim-neorg/tree-sitter-norg-table", files = { "src/parser.c" }, branch = "main" }, }
-- look_cleanios.lua drawing engine configuration file for Ion. if not gr.select_engine("de") then return end de.reset() mainfont = "xft: Sans-10" boldfont = "xft: Sans-10:weight=bold" bigfont = "xft: Sans-14" bigboldfont = "xft: Sans-14:weight=bold" de.defstyle("*", { shadow_colour = "#ffffff", highlight_colour = "#ffffff", background_colour = "#d8d8d8", foreground_colour = "#000000", padding_colour = "#d8d8d8", padding_pixels = 0, highlight_pixels = 2, shadow_pixels = 2, spacing = 0, border_style = "elevated", font = mainfont, text_align = "center", }) de.defstyle("frame", { based_on = "*", background_colour = "#e0e0e0", transparent_background = false, }) de.defstyle("frame-tiled", { based_on = "frame", shadow_pixels = 0, highlight_pixels = 0, padding_pixels = 0, spacing = 1, }) de.defstyle("tab", { based_on = "*", font = boldfont, de.substyle("active-selected", { shadow_colour = "#faff69", highlight_colour = "#faff69", background_colour = "#faff69", foreground_colour = "#000000", -- foreground_colour = "#061644", }), de.substyle("active-unselected", { shadow_colour = "#f0f0f0", highlight_colour = "#f0f0f0", background_colour = "#f0f0f0", -- #d8d8d8", foreground_colour = "#000000", }), de.substyle("inactive-selected", { shadow_colour = "#eef196", highlight_colour = "#eef196", background_colour = "#eef196", -- #eaeca6", foreground_colour = "#000000", }), de.substyle("inactive-unselected", { shadow_colour = "#d8d8d8", highlight_colour = "#d8d8d8", background_colour = "#d8d8d8", foreground_colour = "#000000", }), text_align = "center", }) de.defstyle("tab-frame", { based_on = "tab", de.substyle("*-*-*-*-activity", { shadow_colour = "#e0c0c0", highlight_colour = "#e0c0c0", background_colour = "#990000", foreground_colour = "#eeeeee", }), -- de.substyle("active-selected", { -- background_colour = "#ff0000", -- }), }) de.defstyle("tab-frame-tiled", { based_on = "tab-frame", spacing = 1, }) de.defstyle("tab-menuentry", { based_on = "tab", text_align = "left", spacing = 1, font = boldfont, }) de.defstyle("tab-menuentry-big", { based_on = "tab-menuentry", font = bigfont, padding_pixels = 0, }) de.defstyle("input-edln", { based_on = "*", de.substyle("*-cursor", { background_colour = "#000000", foreground_colour = "#d8d8d8", }), de.substyle("*-selection", { background_colour = "#ffffff", foreground_colour = "#000000", }), }) -- Settings common to some styles. de.defstyle("stdisp", { based_on = "*", shadow_pixels = 0, highlight_pixels = 0, text_align = "left", background_colour = "#000000", foreground_colour = "grey", font=basefont, de.substyle("important", { foreground_colour = "green", }), de.substyle("critical", { foreground_colour = "red", }), }) de.defstyle("actnotify", { based_on = "*", shadow_colour = "#e0c0c0", highlight_colour = "#e0c0c0", background_colour = "#990000", foreground_colour = "#eeeeee", }) gr.refresh()
local m = {} function m.run(db_info) local db = require("common.db") local log = require("common.log") local tables = require("db.table.zone_table") local dbname = db_info.db local luamysql = luasql.mysql() local con, err = luamysql:connect("", db_info.user, db_info.password, db_info.ip, db_info.port) con:execute("alter character set utf-8") con:execute("create database if not exists ".. dbname .. " DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci") con:execute("use ".. dbname) for k, v in pairs(tables) do db.create_or_update_table(con, k, v) end con:close() end return m
require("commons") -- Color lookup utils local function stringifyColorLookup(colorLookup) local result = "{\n" for _, value in ipairs(colorLookup) do result = result .. "\t{" .. value[1] .. ", \"" .. value[2] .. "\"}\n" end result = result .. "}" return result end local function wrapColorLookupTimestamps(colorLookup) local result = {} for _, value in ipairs(colorLookup) do local timestamp = value[1] while timestamp >= 1000000 do timestamp = timestamp - 1000000 end while timestamp < 0 do timestamp = timestamp + 1000000 end table.insert(result, {timestamp, value[2]}) end return result end local function sortColorLookup(colorLookup) local keys = {} for _, value in ipairs(colorLookup) do table.insert(keys, value[1]) end table.sort(keys) local result = {} for _, key in ipairs(keys) do for i, value in ipairs(colorLookup) do if key == value[1] then table.insert(result, value) table.remove(colorLookup, i) break end end end return result end local function deduplicateColorLookup(colorLookup) local result = {} for _, value in ipairs(colorLookup) do if #result == 0 or result[#result][1] ~= value[1] then table.insert(result, value) end end return result end local function rescaleColorLookup(colorLookup) local result = {} for _, value in ipairs(colorLookup) do table.insert(result, {value[1] / 1000000, value[2]}) end return result end local function normalizeColorLookup(colorLookup) colorLookup = wrapColorLookupTimestamps(colorLookup) colorLookup = sortColorLookup(colorLookup) colorLookup = deduplicateColorLookup(colorLookup) colorLookup = rescaleColorLookup(colorLookup) return colorLookup end local function createColorLookup(sunsetDuration, nightDuration, sunriseDuration, dayLut, nightLut) if sunsetDuration == 0 and sunriseDuration == 0 and (nightDuration == 0 or nightDuration == 1000000) then if nightDuration == 0 then return {{0, dayLut}} else return {{0, nightLut}} end else if sunsetDuration == 0 then sunsetDuration = 1 end if sunriseDuration == 0 then sunriseDuration = 1 end if sunsetDuration + nightDuration + sunriseDuration > 1000000 then nightDuration = 1000000 - sunsetDuration - sunriseDuration end local dayDuration = 1000000 - sunsetDuration - nightDuration - sunriseDuration local nightStart = 500000 - math.floor(nightDuration / 2) local nightEnd = 500000 + math.floor((nightDuration+1) / 2) local dayStart = nightEnd + sunriseDuration local dayEnd = nightStart - sunsetDuration local colorLookup = {} table.insert(colorLookup, {dayEnd, dayLut}) table.insert(colorLookup, {nightStart, nightLut}) table.insert(colorLookup, {nightEnd, nightLut}) table.insert(colorLookup, {dayStart, dayLut}) return normalizeColorLookup(colorLookup) end end -- Color lookups local defaultConstants = data.raw["utility-constants"]["default"] local function customizeColorLookup(colorLookupName, groupName) local dayColorSetting = settings.startup[makeSettingName(groupName, settingNames.targets.day, settingNames.options.colors)].value local nightColorSetting = settings.startup[makeSettingName(groupName, settingNames.targets.night, settingNames.options.colors)].value local dayLut = colorSetting2lut(dayColorSetting) local nightLut = colorSetting2lut(nightColorSetting) local sunsetDuration = math.floor(settings.startup[makeSettingName(groupName, settingNames.targets.sunset, settingNames.options.percent)].value * 10000) local nightDuration = math.floor(settings.startup[makeSettingName(groupName, settingNames.targets.night, settingNames.options.percent)].value * 10000) local sunriseDuration = math.floor(settings.startup[makeSettingName(groupName, settingNames.targets.sunrise, settingNames.options.percent)].value * 10000) local colorLookup if sunsetDuration + nightDuration + sunriseDuration > 1000000 then -- Acid trip mode colorLookup = {} for i = 0, 50 do table.insert(colorLookup, {0.02 * i, "__" .. modName .. "__/graphics/color_luts/acid/acid-lut-" .. (i % 5) .. ".png"}) end else colorLookup = createColorLookup(sunsetDuration, nightDuration, sunriseDuration, dayLut, nightLut) end --log(colorLookupName .. "\n" .. stringifyColorLookup(colorLookup)) defaultConstants[colorLookupName] = colorLookup end customizeColorLookup("daytime_color_lookup", settingNames.groups.game) customizeColorLookup("zoom_to_world_daytime_color_lookup", settingNames.groups.map)
local spell = {} spell["element"] = [[Support]] spell["cost"] = 20 spell["desc"] = [[Revives one ally with half their HP]] spell["target"] = [[Dead]] spell["name"] = [[Recarm]] spell["costtype"] = [[SP]] spell["blurb"] = [[ has been revived!]] function spell.activate() state.context.cost(spell.costtype, spell.cost) --Assumes targetindex was passed as a str in this case person = state.party[state.battle.target] state.battle.participants[#state.battle.participants+1] = { persona=person.persona, name=person.name, hp=person.maxhp/2, maxhp=person.maxhp, sp=person.sp, maxsp=person.maxsp, turnstatus={}, attackstatus={}, defendstatus={}, dodgestatus={}, endstatus={} } table.insert(state.battle.turns, {{ target=person.name, caster=state.battle.participants[state.battle.open], status=spell.name, blurb=person.name..spell.blurb }}) end return spell
---@class hattribute 属性系统 hattribute = { max_move_speed = 522, max_life = 999999999, max_mana = 999999999, min_life = 1, min_mana = 1, max_attack_range = 9999, min_attack_range = 0, threeBuff = { -- 每一点三围对属性的影响,默认会写一些,可以通过 hattr.setThreeBuff 方法来改变系统构成 -- 需要注意的是三围只能影响common内的大部分参数,natural及effect是无效的 primary = 1, -- 每点主属性提升1点白字攻击(默认例子,这是模拟原生平衡性常数,需要设置平衡性常数为0) str = { life = 19, -- 每点力量提升10生命(默认例子) life_back = 0.05 -- 每点力量提升0.05生命恢复(默认例子) }, agi = { defend = 0.01 -- 每点敏捷提升0.01护甲(默认例子) }, int = { mana = 6, -- 每点智力提升6魔法(默认例子) mana_back = 0.05 -- 每点力量提升0.05生命恢复(默认例子) } }, DEFAULT_SKILL_ITEM_SLOT = string.char2id("AInv"), -- 默认物品栏技能(英雄6格那个)默认认定这个技能为物品栏 } --- 为单位添加N个同样的生命魔法技能 1级设0 2级设负 负减法(搜[卡血牌bug],了解原理) ---@private hattribute.setLM = function(u, abilityId, qty) if (qty <= 0) then return end local i = 1 while (i <= qty) do cj.UnitAddAbility(u, abilityId) cj.SetUnitAbilityLevel(u, abilityId, 2) cj.UnitRemoveAbility(u, abilityId) i = i + 1 end end --- 为单位添加N个同样的攻击之书 ---@private hattribute.setAttackWhite = function(u, itemId, qty) if (u == nil or itemId == nil or qty <= 0) then return end if (his.alive(u) == true) then local i = 1 local it local hasSlot = (cj.GetUnitAbilityLevel(u, hattribute.DEFAULT_SKILL_ITEM_SLOT) >= 1) if (hasSlot == false) then cj.UnitAddAbility(u, hattribute.DEFAULT_SKILL_ITEM_SLOT) end while (i <= qty) do it = cj.CreateItem(itemId, 0, 0) cj.UnitAddItem(u, it) cj.SetWidgetLife(it, 10.00) cj.RemoveItem(it) i = i + 1 end if (hasSlot == false) then cj.UnitRemoveAbility(u, hattribute.DEFAULT_SKILL_ITEM_SLOT) end else local per = 3.00 local limit = 60.0 / per -- 一般不会超过1分钟复活 htime.setInterval( per, function(t) limit = limit - 1 if (limit < 0) then htime.delTimer(t) elseif (his.alive(u) == true) then htime.delTimer(t) local i = 1 local it local hasSlot = (cj.GetUnitAbilityLevel(u, hattribute.DEFAULT_SKILL_ITEM_SLOT) >= 1) if (hasSlot == false) then cj.UnitAddAbility(u, hattribute.DEFAULT_SKILL_ITEM_SLOT) end while (i <= qty) do it = cj.CreateItem(itemId, 0, 0) cj.UnitAddItem(u, it) cj.SetWidgetLife(it, 10.00) cj.RemoveItem(it) i = i + 1 end if (hasSlot == false) then cj.UnitRemoveAbility(u, hattribute.DEFAULT_SKILL_ITEM_SLOT) end end end ) end end --- 设置三围的影响 ---@param buff table hattribute.setThreeBuff = function(buff) if (type(buff) == "table") then hattribute.threeBuff = buff end end --- 为单位注册属性系统所需要的基础技能 --- hslk_global.attr ---@private hattribute.regAllAbility = function(whichUnit) for _, v in ipairs(hslk_global.attr.ablis_gradient) do -- 生命 cj.UnitAddAbility(whichUnit, hslk_global.attr.life.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.life.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.life.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.life.sub[v]) -- 魔法 cj.UnitAddAbility(whichUnit, hslk_global.attr.mana.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.mana.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.mana.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.mana.sub[v]) -- 绿字攻击 cj.UnitAddAbility(whichUnit, hslk_global.attr.attack_green.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.attack_green.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.attack_green.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.attack_green.sub[v]) -- 绿色属性 cj.UnitAddAbility(whichUnit, hslk_global.attr.str_green.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.str_green.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.str_green.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.str_green.sub[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.agi_green.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.agi_green.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.agi_green.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.agi_green.sub[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.int_green.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.int_green.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.int_green.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.int_green.sub[v]) -- 攻击速度 cj.UnitAddAbility(whichUnit, hslk_global.attr.attack_speed.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.attack_speed.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.attack_speed.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.attack_speed.sub[v]) -- 防御 cj.UnitAddAbility(whichUnit, hslk_global.attr.defend.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.defend.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.defend.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.defend.sub[v]) end for _, v in ipairs(hslk_global.attr.sight_gradient) do -- 视野 cj.UnitAddAbility(whichUnit, hslk_global.attr.sight.add[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.sight.add[v]) cj.UnitAddAbility(whichUnit, hslk_global.attr.sight.sub[v]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.sight.sub[v]) end end --- 为单位初始化属性系统的对象数据 --- @private hattribute.init = function(whichUnit) if (whichUnit == nil) then return false end -- init local slkData = hunit.getSlk(whichUnit) hRuntime.attribute[whichUnit] = { primary = slkData.Primary or "STR", life = cj.GetUnitState(whichUnit, UNIT_STATE_MAX_LIFE), mana = cj.GetUnitState(whichUnit, UNIT_STATE_MAX_MANA), move = cj.GetUnitDefaultMoveSpeed(whichUnit), defend = slkData.def or 0, attack_damage_type = {}, attack_speed = 0.0, attack_speed_space = slkData.cool1 or 1.50, attack_white = 0.0, attack_green = 0.0, attack_range = slkData.rangeN1 or 100, sight = slkData.sight or 1800, str_green = 0.0, agi_green = 0.0, int_green = 0.0, str_white = 0, agi_white = 0, int_white = 0, life_back = 0.0, mana_back = 0.0, resistance = 0.0, toughness = 0.0, avoid = 0.0, aim = 0.0, punish = 0.0, punish_current = 0.0, meditative = 0.0, help = 0.0, hemophagia = 0.0, hemophagia_skill = 0.0, luck = 0.0, invincible = 0.0, weight = 0.0, weight_current = 0.0, damage_extent = 0.0, damage_rebound = 0.0, cure = 0.0, knocking_oppose = 0.0, violence_oppose = 0.0, hemophagia_oppose = 0.0, hemophagia_skill_oppose = 0.0, split_oppose = 0.0, punish_oppose = 0.0, damage_rebound_oppose = 0.0, swim_oppose = 0.0, heavy_oppose = 0.0, broken_oppose = 0.0, unluck_oppose = 0.0, silent_oppose = 0.0, unarm_oppose = 0.0, fetter_oppose = 0.0, bomb_oppose = 0.0, lightning_chain_oppose = 0.0, crack_fly_oppose = 0.0, natural_fire = 0.0, natural_soil = 0.0, natural_water = 0.0, natural_ice = 0.0, natural_wind = 0.0, natural_light = 0.0, natural_dark = 0.0, natural_wood = 0.0, natural_thunder = 0.0, natural_poison = 0.0, natural_ghost = 0.0, natural_metal = 0.0, natural_dragon = 0.0, natural_insect = 0.0, natural_god = 0.0, natural_fire_oppose = 0.0, natural_soil_oppose = 0.0, natural_water_oppose = 0.0, natural_ice_oppose = 0.0, natural_wind_oppose = 0.0, natural_light_oppose = 0.0, natural_dark_oppose = 0.0, natural_wood_oppose = 0.0, natural_thunder_oppose = 0.0, natural_poison_oppose = 0.0, natural_ghost_oppose = 0.0, natural_metal_oppose = 0.0, natural_dragon_oppose = 0.0, natural_insect_oppose = 0.0, natural_god_oppose = 0.0, attack_buff = {}, attack_debuff = {}, skill_buff = {}, skill_debuff = {}, -- 特殊特效 attack_effect = {}, skill_effect = {} --[[ buff/debuff例子 attack_buff = { 攻击伤害时buff=20%几率增加自身 1.5% 的攻击速度 3 秒 add = { --这个add表示添加这一种效果,而不是数值的增减 { attr="attack_speed", odds = 20.0, val = 1.5, during = 3.0, effect = nil }, }, sub = { --这个sub表示删除这一种效果,如果效果不存在,而无动作 { attr="attack_speed", odds = 20.0, val = 1.5, during = 3.0, effect = nil }, } } skill_debuff = { 技能伤害时buff=13%几率减少目标 3.5% 的攻击速度 4.4 秒,特效是 war3mapImported\\ExplosionBIG.mdl add = { { attr="move",odds = 13.0, val = 3.5, during = 4.4, effect = 'war3mapImported\\ExplosionBIG.mdl' }, }, sub = { --这个sub表示删除这一种效果,如果效果不存在,而无动作 { attr="move",odds = 13.0, val = 3.5, during = 4.4, effect = 'war3mapImported\\ExplosionBIG.mdl' }, } } attack_effect / skill_effect同理,effect只能设定下列的值,会在属性系统自动调用: {attr="knocking",odds = 0.0, percent = 0.0, effect = nil}, {attr="violence",odds = 0.0, percent = 0.0, effect = nil}, {attr="split",odds = 0.0, percent=0.0, range = 0.0, effect = nil}, {attr="swim",odds = 0.0, val = 0.0, during = 0.0, effect = nil}, {attr="broken",odds = 0.0, val = 0.0, during = 0.0, effect = nil}, {attr="silent",odds = 0.0, val = 0.0, during = 0.0, effect = nil}, {attr="unarm",odds = 0.0, val = 0.0, during = 0.0, effect = nil}, {attr="fetter",odds = 0.0, val = 0.0, during = 0.0, effect = nil}, {attr="bomb",odds = 0.0, range = 0.0, val = 0.0, during = 0.0, effect = nil}, {attr="lightning_chain",odds = 0.0, val = 0.0, effect = nil, qty = 0, reduce = 0.0}, {attr="crack_fly",odds = 0.0, val = 0.0, during = 0.0, effect = nil, distance = 0, high = 0.0} * 至于是否同一种效果,是根据你设定的值自动计算出来的 ]] } -- 智力英雄的攻击默认为魔法,力量敏捷为物理 if (hRuntime.attribute[whichUnit].primary == "INT") then hRuntime.attribute[whichUnit].attack_damage_type = { CONST_DAMAGE_TYPE.magic } else hRuntime.attribute[whichUnit].attack_damage_type = { CONST_DAMAGE_TYPE.physical } end return true end --- @private hattribute.getAccumuDiff = function(whichUnit, attr) if (hRuntime.attributeDiff[whichUnit] == nil) then hRuntime.attributeDiff[whichUnit] = {} end return hRuntime.attributeDiff[whichUnit][attr] or 0 end --- @private hattribute.setAccumuDiff = function(whichUnit, attr, value) if (hRuntime.attributeDiff[whichUnit] == nil) then hRuntime.attributeDiff[whichUnit] = {} end hRuntime.attributeDiff[whichUnit][attr] = math.round(value) end --- @private hattribute.addAccumuDiff = function(whichUnit, attr, value) hattribute.setAccumuDiff(whichUnit, attr, hattribute.getAccumuDiff(whichUnit, attr) + value) end --- @private hattribute.subAccumuDiff = function(whichUnit, attr, value) hattribute.setAccumuDiff(whichUnit, attr, hattribute.getAccumuDiff(whichUnit, attr) - value) end -- 设定属性 --[[ 白字攻击 绿字攻击 攻速 视野 射程 力敏智 力敏智(绿) 护甲 魔抗 生命 魔法 +恢复 硬直 物暴 术暴 分裂 回避 移动力 力量 敏捷 智力 救助力 吸血 负重 各率 type(data) == table data = { 支持 加/减/乘/除/等 life = '+100', mana = '-100', life_back = '*100', mana_back = '/100', move = '=100', } during = 0.0 大于0生效;小于等于0时无限持续时间 ]] --- @private hattribute.setHandle = function(whichUnit, attr, opr, val, dur) local valType = type(val) local params = hRuntime.attribute[whichUnit] if (params == nil) then return end if (valType == "string") then -- string类型只有+-= if (opr == "+") then -- 添加 local valArr = string.explode(",", val) params[attr] = table.merge(params[attr], valArr) if (dur > 0) then htime.setTimeout( dur, function(t) htime.delTimer(t) hattribute.setHandle(whichUnit, attr, "-", val, 0) end ) end elseif (opr == "-") then -- 减少 local valArr = string.explode(",", val) for _, v in ipairs(valArr) do if (table.includes(v, params[attr])) then table.delete(v, params[attr], 1) end end if (dur > 0) then htime.setTimeout( dur, function(t) htime.delTimer(t) hattribute.setHandle(whichUnit, attr, "+", val, 0) end ) end elseif (opr == "=") then -- 设定 local old = table.clone(params[attr]) params[attr] = string.explode(",", val) if (dur > 0) then htime.setTimeout( dur, function(t) htime.delTimer(t) hattribute.setHandle(whichUnit, attr, "=", string.implode(",", old), 0) end ) end end elseif (valType == "table") then -- table类型只有+-没有别的 if (opr == "+") then -- 添加 local hkey = string.vkey(val) table.insert(params[attr], { hash = hkey, table = val }) if (dur > 0) then htime.setTimeout( dur, function(t) htime.delTimer(t) hattribute.setHandle(whichUnit, attr, "-", val, 0) end ) end elseif (opr == "-") then -- 减少 local valx = table.obj2arr(val, CONST_ATTR_BUFF_KEYS) local valxx = {} for _, xv in ipairs(valx) do table.insert(valxx, xv.value) end valx = nil local hkey = string.vkey(valxx) local hasKey = false for k, v in ipairs(params[attr]) do if (v.hash == hkey) then table.remove(params[attr], k) hasKey = true break end end if (hasKey == true) then if (dur > 0) then htime.setTimeout( dur, function(t) htime.delTimer(t) hattribute.setHandle(whichUnit, attr, "+", val, 0) end ) end end end elseif (valType == "number") then -- number local intAttr = { "life", "mana", "move", "attack_white", "attack_green", "attack_range", "sight", "defend", "str_white", "agi_white", "int_white", "str_green", "agi_green", "int_green", "punish" } local isInt = false if (table.includes(attr, intAttr)) then isInt = true end -- local diff = 0 if (opr == "+") then diff = val elseif (opr == "-") then diff = -val elseif (opr == "*") then diff = params[attr] * val - params[attr] elseif (opr == "/" and val ~= 0) then diff = params[attr] / val - params[attr] elseif (opr == "=") then diff = val - params[attr] end local isAccumuDiff = false local accumuDiff = hattribute.getAccumuDiff(whichUnit, attr) if (diff * accumuDiff > 0) then isAccumuDiff = true diff = diff + accumuDiff end --部分属性取整处理,否则失真 if (isInt and diff ~= 0) then local di, df = math.modf(math.abs(diff)) if (isAccumuDiff) then if (diff >= 0) then hattribute.setAccumuDiff(whichUnit, attr, df) else hattribute.setAccumuDiff(whichUnit, attr, -df) end else if (diff >= 0) then hattribute.addAccumuDiff(whichUnit, attr, df) else hattribute.subAccumuDiff(whichUnit, attr, df) end end if (diff >= 0) then diff = di else diff = -di end end if (diff ~= 0) then local currentVal = params[attr] local futureVal = params[attr] + diff params[attr] = futureVal if (dur > 0) then htime.setTimeout( dur, function(t) htime.delTimer(t) hattribute.setHandle(whichUnit, attr, "-", diff, 0) end ) end -- ability local tempVal = 0 local level = 0 if (attr == "life" or attr == "mana") then -- 生命 | 魔法 if (futureVal >= hattribute["max_" .. attr]) then if (currentVal >= hattribute["max_" .. attr]) then diff = 0 else diff = hattribute["max_" .. attr] - currentVal end elseif (futureVal <= hattribute["min_" .. attr]) then if (currentVal <= hattribute["min_" .. attr]) then diff = 0 else diff = hattribute["min_" .. attr] - currentVal end end tempVal = math.floor(math.abs(diff)) local max = 100000000 if (tempVal ~= 0) then while (max >= 1) do level = math.floor(tempVal / max) tempVal = math.floor(tempVal - level * max) if (diff > 0) then hattribute.setLM(whichUnit, hslk_global.attr[attr].add[max], level) else hattribute.setLM(whichUnit, hslk_global.attr[attr].sub[max], level) end max = math.floor(max / 10) end end elseif (attr == "move") then -- 移动 if (futureVal < 0) then cj.SetUnitMoveSpeed(whichUnit, 0) else if (hcamera.getModel(hunit.getOwner(whichUnit)) == "zoomin") then cj.SetUnitMoveSpeed(whichUnit, math.floor(futureVal * 0.5)) else cj.SetUnitMoveSpeed(whichUnit, math.floor(futureVal)) end end elseif (attr == "attack_white") then -- 白字攻击 local max = 100000000 if (futureVal > max or futureVal < -max) then diff = 0 end tempVal = math.floor(math.abs(diff)) if (tempVal ~= 0) then while (max >= 1) do level = math.floor(tempVal / max) tempVal = math.floor(tempVal - level * max) if (diff > 0) then hattribute.setAttackWhite(whichUnit, hslk_global.attr.item_attack_white.add[max], level) else hattribute.setAttackWhite(whichUnit, hslk_global.attr.item_attack_white.sub[max], level) end max = math.floor(max / 10) end end elseif (attr == "attack_range") then -- 攻击范围(仅仅是自动警示范围) if (futureVal < hattribute.min_attack_range) then futureVal = hattribute.min_attack_range elseif (futureVal > hattribute.max_attack_range) then futureVal = hattribute.max_attack_range end if (hcamera.getModel(hunit.getOwner(whichUnit)) == "zoomin") then futureVal = futureVal * 0.5 end cj.SetUnitAcquireRange(whichUnit, futureVal * 1.1) elseif (attr == "sight") then -- 视野 for _, gradient in ipairs(hslk_global.attr.sight_gradient) do cj.UnitRemoveAbility(whichUnit, hslk_global.attr.sight.add[gradient]) cj.UnitRemoveAbility(whichUnit, hslk_global.attr.sight.sub[gradient]) end tempVal = math.floor(math.abs(futureVal)) local sight_gradient = table.clone(hslk_global.attr.sight_gradient) if (tempVal ~= 0) then while (true) do local isFound = false for _, v in ipairs(sight_gradient) do if (tempVal >= v) then tempVal = math.floor(tempVal - v) table.delete(v, sight_gradient) if (futureVal > 0) then cj.UnitAddAbility(whichUnit, hslk_global.attr.sight.add[v]) else cj.UnitAddAbility(whichUnit, hslk_global.attr.sight.sub[v]) end isFound = true break end end if (isFound == false) then break end end end elseif (table.includes(attr, { "attack_green", "attack_speed", "defend" })) then -- 绿字攻击 攻击速度 护甲 if (futureVal < -99999999) then futureVal = -99999999 elseif (futureVal > 99999999) then futureVal = 99999999 end for _, grad in ipairs(hslk_global.attr.ablis_gradient) do local ab = hslk_global.attr[attr].add[grad] if (cj.GetUnitAbilityLevel(whichUnit, ab) > 1) then cj.SetUnitAbilityLevel(whichUnit, ab, 1) end ab = hslk_global.attr[attr].sub[grad] if (cj.GetUnitAbilityLevel(whichUnit, ab) > 1) then cj.SetUnitAbilityLevel(whichUnit, ab, 1) end end tempVal = math.floor(math.abs(futureVal)) local max = 100000000 if (tempVal ~= 0) then while (max >= 1) do level = math.floor(tempVal / max) tempVal = math.floor(tempVal - level * max) if (futureVal > 0) then if (cj.GetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].add[max]) < 1) then cj.UnitAddAbility(whichUnit, hslk_global.attr[attr].add[max]) end cj.SetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].add[max], level + 1) else if (cj.GetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].sub[max]) < 1) then cj.UnitAddAbility(whichUnit, hslk_global.attr[attr].sub[max]) end cj.SetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].sub[max], level + 1) end max = math.floor(max / 10) end end elseif (his.hero(whichUnit) and table.includes(attr, { "str_green", "agi_green", "int_green" })) then -- 绿字力量 绿字敏捷 绿字智力 if (futureVal < -99999999) then futureVal = -99999999 elseif (futureVal > 99999999) then futureVal = 99999999 end for _, grad in ipairs(hslk_global.attr.ablis_gradient) do local ab = hslk_global.attr[attr].add[grad] if (cj.GetUnitAbilityLevel(whichUnit, ab) > 1) then cj.SetUnitAbilityLevel(whichUnit, ab, 1) end ab = hslk_global.attr[attr].sub[grad] if (cj.GetUnitAbilityLevel(whichUnit, ab) > 1) then cj.SetUnitAbilityLevel(whichUnit, ab, 1) end end tempVal = math.floor(math.abs(futureVal)) local max = 100000000 if (tempVal ~= 0) then while (max >= 1) do level = math.floor(tempVal / max) tempVal = math.floor(tempVal - level * max) if (futureVal > 0) then if (cj.GetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].add[max]) < 1) then cj.UnitAddAbility(whichUnit, hslk_global.attr[attr].add[max]) end cj.SetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].add[max], level + 1) else if (cj.GetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].sub[max]) < 1) then cj.UnitAddAbility(whichUnit, hslk_global.attr[attr].sub[max]) end cj.SetUnitAbilityLevel(whichUnit, hslk_global.attr[attr].sub[max], level + 1) end max = math.floor(max / 10) end end local subAttr = string.gsub(attr, "_green", "") -- 主属性影响(<= 0自动忽略) if (hattribute.threeBuff.primary > 0) then if (string.upper(subAttr) == hhero.getPrimary(whichUnit)) then hattribute.set(whichUnit, 0, { attack_white = "+" .. diff * hattribute.threeBuff.primary }) end end -- 三围影响 local three = table.obj2arr(hattribute.threeBuff[subAttr], CONST_ATTR_KEYS) for _, d in ipairs(three) do local tempV = diff * d.value if (tempV < 0) then hattribute.set(whichUnit, 0, { [d.key] = "-" .. math.abs(tempV) }) elseif (tempV > 0) then hattribute.set(whichUnit, 0, { [d.key] = "+" .. tempV }) end end elseif (his.hero(whichUnit) and table.includes(attr, { "str_white", "agi_white", "int_white" })) then -- 白字力量 敏捷 智力 if (attr == "str_white") then cj.SetHeroStr(whichUnit, math.floor(futureVal), true) elseif (attr == "agi_white") then cj.SetHeroAgi(whichUnit, math.floor(futureVal), true) elseif (attr == "int_white") then cj.SetHeroInt(whichUnit, math.floor(futureVal), true) end local subAttr = string.gsub(attr, "_white", "") -- 主属性影响(<= 0自动忽略) if (hattribute.threeBuff.primary > 0) then if (string.upper(subAttr) == hhero.getPrimary(whichUnit)) then hattribute.set(whichUnit, 0, { attack_white = "+" .. diff * hattribute.threeBuff.primary }) end end -- 三围影响 local three = table.obj2arr(hattribute.threeBuff[subAttr], CONST_ATTR_KEYS) for _, d in ipairs(three) do local tempV = diff * d.value if (tempV < 0) then hattribute.set(whichUnit, 0, { [d.key] = "-" .. math.abs(tempV) }) elseif (tempV > 0) then hattribute.set(whichUnit, 0, { [d.key] = "+" .. tempV }) end end elseif (attr == "life_back" or attr == "mana_back") then -- 生命,魔法恢复 if (math.abs(futureVal) > 0.02 and table.includes(whichUnit, hRuntime.attributeGroup[attr]) == false) then table.insert(hRuntime.attributeGroup[attr], whichUnit) elseif (math.abs(futureVal) < 0.02) then table.delete(whichUnit, hRuntime.attributeGroup[attr]) end elseif (attr == "punish" and hunit.isOpenPunish(whichUnit)) then -- 硬直 if (currentVal > 0) then local tempPercent = futureVal / currentVal hRuntime.attribute[whichUnit].punish_current = tempPercent * hRuntime.attribute[whichUnit].punish_current else hRuntime.attribute[whichUnit].punish_current = futureVal end elseif (attr == "punish_current" and hunit.isOpenPunish(whichUnit)) then -- 硬直(current) if (futureVal > hRuntime.attribute[whichUnit].punish) then hRuntime.attribute[whichUnit].punish_current = hRuntime.attribute[whichUnit].punish elseif (futureVal <= 0) then hRuntime.attribute[whichUnit].punish_current = hRuntime.attribute[whichUnit].punish end end end end end --- 设置单位属性 ---@param whichUnit userdata ---@param during number 0表示无限 ---@param data any hattribute.set = function(whichUnit, during, data) if (whichUnit == nil) then -- 例如有时造成伤害之前把单位删除就捕捉不到这个伤害来源了 -- 虽然这里直接返回不执行即可,但是提示下可以帮助完善业务的构成~ print_stack("whichUnit is nil") return end if (hRuntime.attribute[whichUnit] == nil) then if (hattribute.init(whichUnit) == false) then return end end -- 处理data if (type(data) ~= "table") then print_err("data must be table") return end for _, arr in ipairs(table.obj2arr(data, CONST_ATTR_KEYS)) do local attr = arr.key local v = arr.value if (hRuntime.attribute[whichUnit] ~= nil and hRuntime.attribute[whichUnit][attr] ~= nil) then if (type(v) == "string") then local opr = string.sub(v, 1, 1) v = string.sub(v, 2, string.len(v)) local val = tonumber(v) if (val == nil) then val = v end hattribute.setHandle(whichUnit, attr, opr, val, during) elseif (type(v) == "table") then -- table型,如特效,buff等 if (v.add ~= nil and type(v.add) == "table") then for _, buff in ipairs(v.add) do if (buff == nil) then print_err("table effect loss[buff]!") print_stack() break end if (type(buff) ~= "table") then print_err("add type(buff) must be a table!") print_stack() break end hattribute.setHandle(whichUnit, attr, "+", buff, during) end elseif (v.sub ~= nil and type(v.sub) == "table") then for _, buff in ipairs(v.sub) do if (buff == nil) then print_err("table effect loss[buff]!") print_stack() break end if (type(buff) ~= "table") then print_err("sub type(buff) must be a table!") print_stack() break end hattribute.setHandle(whichUnit, attr, "-", buff, during) end end end end end end --- 通用get ---@param whichUnit userdata ---@param attr string ---@return any hattribute.get = function(whichUnit, attr) if (whichUnit == nil) then return nil end if (hRuntime.attribute[whichUnit] == nil) then if (hattribute.init(whichUnit) == false) then return nil end end if (attr == nil) then return hRuntime.attribute[whichUnit] end return hRuntime.attribute[whichUnit][attr] end --- 重置注册 ---@private hattribute.reRegister = function(whichUnit) local life = hRuntime.attribute[whichUnit].life local mana = hRuntime.attribute[whichUnit].mana local move = hRuntime.attribute[whichUnit].move local strGreen = hRuntime.attribute[whichUnit].str_green local agiGreen = hRuntime.attribute[whichUnit].agi_green local intGreen = hRuntime.attribute[whichUnit].int_green local strWhite = hRuntime.attribute[whichUnit].str_white local agiWhite = hRuntime.attribute[whichUnit].agi_white local intWhite = hRuntime.attribute[whichUnit].int_white local attackWhite = hRuntime.attribute[whichUnit].attack_white local attackGreen = hRuntime.attribute[whichUnit].attack_green local attackSpeed = hRuntime.attribute[whichUnit].attack_speed local defend = hRuntime.attribute[whichUnit].defend -- 注册技能 if (hattribute.init(whichUnit) == false) then return end -- 弥补属性 cj.SetHeroStr(whichUnit, cj.R2I(strWhite), true) cj.SetHeroAgi(whichUnit, cj.R2I(agiWhite), true) cj.SetHeroInt(whichUnit, cj.R2I(intWhite), true) if (move < 0) then cj.SetUnitMoveSpeed(whichUnit, 0) else if (hcamera.model == "zoomin") then cj.SetUnitMoveSpeed(whichUnit, cj.R2I(move * 0.5)) else cj.SetUnitMoveSpeed(whichUnit, cj.R2I(move)) end end hRuntime.attribute[whichUnit].life = cj.GetUnitState(whichUnit, UNIT_STATE_MAX_LIFE) hRuntime.attribute[whichUnit].mana = cj.GetUnitState(whichUnit, UNIT_STATE_MAX_MANA) hRuntime.attribute[whichUnit].defend = hslk_global.id2Value.unit[hunit.getId(whichUnit)].def or 0.0 hRuntime.attribute[whichUnit].attack_speed = 0 hRuntime.attribute[whichUnit].attack_white = 0 hRuntime.attribute[whichUnit].attack_green = 0 hRuntime.attribute[whichUnit].str_green = 0 hRuntime.attribute[whichUnit].agi_green = 0 hRuntime.attribute[whichUnit].int_green = 0 hattribute.set( whichUnit, 0, { life = "+" .. (life - cj.GetUnitState(whichUnit, UNIT_STATE_MAX_LIFE)), mana = "+" .. (mana - cj.GetUnitState(whichUnit, UNIT_STATE_MAX_LIFE)), str_green = "+" .. strGreen, agi_green = "+" .. agiGreen, int_green = "+" .. intGreen, attack_white = "+" .. attackWhite, attack_green = "+" .. attackGreen, attack_speed = "+" .. attackSpeed, defend = "+" .. defend } ) end
-- Resets game function restartGame() player.shieldImg = playerShieldImg player.img = imagesPlayerBasic[2] player.bullet = imagesBulletBasic[2] backgroundImg = backgroundImges[1] -- reset timers createEnemyTimer = ENEMY_TIMER -- moving player back to default position and reseting player opt player.x = 200 player.y = 690 player.speed = 350 player.bulletStrength = 1 player.bulletDamage = 1.0 player.life = 3 player.shield = false player.shieldDuration = 0 -- reseting game state enemySpeed = 100 -- speed of what aircrafts are moving activeEnemiesOnScreen = {} activeEnemyBulletsOnScreen = {} activePowerupOnScreen = {} activeBulletsOnScreen = {} enemyImg = imagesEnemies[1] enemyBullet = love.graphics.newImage('assets/Space Shooter/PNG/Lasers/laserRed11.png') score = 0 isAlive = true scoreUpdate = true bonusScore = false currentEnemiesAlive = 0 currentWaveCount = 0 level = 0 end
AddCSLuaFile() -- Custom Quake Entity base -- For item spawners --[[------------------------------------------------------------------------------------------------------ Necessary info --------------------------------------------------------------------------------------------------------]] ENT.Base = 'base_gmodentity' ENT.Type = 'anim' ENT.PrintName = 'cqb_ent_spawner_base' ENT.Author = 'JFAexe' ENT.Category = 'S T O L E N C O D E ™' ENT.Spawnable = false ENT.AdminOnly = false ENT.BaseModel = 'models/props_phx/construct/metal_angle360.mdl' ENT.BaseSkin = 0 ENT.BaseMaterial = 'phoenix_storms/stripes' ENT.BaseColor = Color(255, 100, 200) ENT.BaseScale = 0.4 ENT.Model = 'models/Items/BoxMRounds.mdl' ENT.Skin = 0 ENT.Material = nil ENT.Scale = 1 ENT.AmmoType = 'Pistol' ENT.AmmoAmount = 100 ENT.ExtraHeight = 0 --[[------------------------------------------------------------------------------------------------------ Base --------------------------------------------------------------------------------------------------------]] local ColorWhite = Color(255, 255, 255, 255) local ColorRed = Color(255, 0, 0, 255) ENT.RespawnTime = 0 ENT.RenderGroup = RENDERGROUP_TRANSLUCENT ENT.DrawingModel = nil function ENT:SetupDataTables() self:NetworkVar('Float', 0, 'Timer') end function ENT:Initialize() self:SetModel(self.BaseModel) self:SetModelScale(self.BaseScale) self:SetMaterial(self.BaseMaterial) self:SetColor(self.BaseColor) self:DrawShadow(false) self:PhysicsInit(SOLID_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_NONE) self:SetCollisionGroup(COLLISION_GROUP_WEAPON) self:PhysWake() self:Activate() if SERVER then self:SetTrigger(true) end self:CreateClientModel() self:SetTimer(CurTime()) end function ENT:CreateClientModel() if CLIENT then self.DrawingModel = ClientsideModel(self.Model, self.RenderGroup) local Model = self.DrawingModel Model:SetSkin(self.Skin) Model:SetMaterial(self.Material) Model:SetModelScale(self.Scale) Model:AddEffects(EF_ITEM_BLINK) end end function ENT:Think() self.RespawnTime = CQB_GetConv('cqb_sv_spawner_time', 'float') if not CLIENT then return end local Model = self.DrawingModel if CurTime() < self:GetTimer() then Model:SetMaterial('models/wireframe') Model:SetColor(ColorRed) return end Model:SetMaterial(self.Material) Model:SetColor(ColorWhite) end function ENT:Touch(ent) if ent:IsValid() and ent:IsPlayer() and SERVER and self:GetTimer() < CurTime() then self:OnPickup(ent) self:SetTimer(CurTime() + self.RespawnTime) end end function ENT:OnPickup(ent) ent:GiveAmmo(self.AmmoAmount, self.AmmoType, false) end if CLIENT then function ENT:DrawTranslucent() self:DrawModel() local Model = self.DrawingModel local CT = CurTime() local angle = (CT * 90) % 360 local height = math.sin(CT * 3) * 5 Model:SetPos(self:GetPos() + Vector(0, 0, height + 20 + self.ExtraHeight)) Model:SetAngles(Angle(0, angle, 0)) end function ENT:OnRemove() self.DrawingModel:Remove() end end
-------------------------------- -- @module SkeletonAnimation -- @extend SkeletonRenderer -- @parent_module sp -------------------------------- -- -- @function [parent=#SkeletonAnimation] setTrackCompleteListener -- @param self -- @param #spTrackEntry entry -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] findAnimation -- @param self -- @param #string name -- @return spAnimation#spAnimation ret (return value: spAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setTrackEventListener -- @param self -- @param #spTrackEntry entry -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setMix -- @param self -- @param #string fromAnimation -- @param #string toAnimation -- @param #float duration -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- /½«Ò»¸ö½Úµã¼Óµ½Ò»¸öslotÉÏ,,¿ÉÄܲ»ÄÜÓÃŶ -- @function [parent=#SkeletonAnimation] addNodeToBone -- @param self -- @param #string slotName -- @param #cc.Node childNode -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setTrackStartListener -- @param self -- @param #spTrackEntry entry -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setEndListener -- @param self -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setCompleteListener -- @param self -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- »ñµÃÒ»¸ö¹ÇÍ·µÄÊÀ½çλÖà -- @function [parent=#SkeletonAnimation] getBonePos -- @param self -- @param #string boneName -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- ÉèÖÃÒ»¸öspine¹Ç÷ÀÖеÄÒ»¸ö¹ÇÍ·µÄƤ·ô -- @function [parent=#SkeletonAnimation] setOneBoneSkin -- @param self -- @param #string boneName -- @param #string skinName -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setEventListener -- @param self -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- /add by wss -- @function [parent=#SkeletonAnimation] setDebugSlot -- @param self -- @param #bool b -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] clearTrack -- @param self -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setSProgram -- @param self -- @param #string vshName -- @param #string fshName -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- /ÉèÖÃÒ»¸ö¹ÇÍ·µÄÐýת -- @function [parent=#SkeletonAnimation] setBoneRotation -- @param self -- @param #char boneName -- @param #float r -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] getAnimationTime -- @param self -- @param #string name -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#SkeletonAnimation] clearTracks -- @param self -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setTrackEndListener -- @param self -- @param #spTrackEntry entry -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setDebugBone -- @param self -- @param #bool b -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] setStartListener -- @param self -- @param #function listener -- @return SkeletonAnimation#SkeletonAnimation self (return value: sp.SkeletonAnimation) -------------------------------- -- /»ñµÃÒ»¸ö¹ÇÍ·µÄÐýת½Ç¶È -- @function [parent=#SkeletonAnimation] getBoneAngle -- @param self -- @param #string boneName -- @return float#float ret (return value: float) -------------------------------- -- @overload self, string, string, float -- @overload self, string, spAtlas, float -- @function [parent=#SkeletonAnimation] createWithBinaryFile -- @param self -- @param #string skeletonBinaryFile -- @param #spAtlas atlas -- @param #float scale -- @return SkeletonAnimation#SkeletonAnimation ret (return value: sp.SkeletonAnimation) -------------------------------- -- -- @function [parent=#SkeletonAnimation] create -- @param self -- @return SkeletonAnimation#SkeletonAnimation ret (return value: sp.SkeletonAnimation) -------------------------------- -- @overload self, string, string, float -- @overload self, string, spAtlas, float -- @function [parent=#SkeletonAnimation] createWithJsonFile -- @param self -- @param #string skeletonJsonFile -- @param #spAtlas atlas -- @param #float scale -- @return SkeletonAnimation#SkeletonAnimation ret (return value: sp.SkeletonAnimation) return nil
CannonBehavior = {} CannonBehavior.e = {} ------------------------------------------------------ -- System events ------------------------------------------------------ function CannonBehavior:new() local u = {} setmetatable(u, self) self.__index = self return u end function CannonBehavior:onConnect(opt) self.dt = 0 self.enabled = false self.fire_interval = 1 if opt then self.fire_interval = tonumber(opt.fire_interval) or 1 self.fire_vx = tonumber(opt.fire_vx) or 100 self.fire_vy = tonumber(opt.fire_vy) or 0 end end function CannonBehavior:onUpdate(dt) self.dt = self.dt + dt if self.dt > self.fire_interval and self.enabled then local ent = self.entity local x ,y = ent.RigidBody:getLoc() local vx,vy vx = self.fire_vx vy = self.fire_vy ent.Sprite:useAnimation("shoot") ent.Sprite:play(false, function() Launcher:addFireball(x-10,y+3, vx,vy) end) self.dt = 0 end end ------------------------------------------------------ -- Entity events ------------------------------------------------------ function CannonBehavior.e:startShooting() self.CannonBehavior.enabled = true end function CannonBehavior.e:stopShooting() self.CannonBehavior.enabled = false self.Sprite:useAnimation("idle") self.Sprite:looping() end
--!strict local None = newproxy(false)::any return None
return {'hickory','hicham','hickorys','hichams'}
-- Creates a rope at the specific position, that extends in the specified direction when not attached to any entities. __ Add_Rope(pos.x,pos.y,pos.z,0.0,0.0,0.0,20.0,4,20.0,1.0,0.0,false,false,false,5.0,false,NULL) When attached, Position<vector> does not matter When attached, Angle<vector> does not matter Rope Type: 4 and bellow is a thick rope 5 and up are small metal wires 0 crashes the game Max_length - Rope is forced to this length, generally best to keep this the same as your rope length. Rigid - If max length is zero, and this is set to false the rope will become rigid (it will force a specific distance, what ever length is, between the objects). breakable - Whether or not shooting the rope will break it. unkPtr - unknown ptr, always 0 in orig scripts __ Lengths can be calculated like so: float distance = abs(x1 - x2) + abs(y1 - y2) + abs(z1 - z2); // Rope length NOTES: Rope does NOT interact with anything you attach it to, in some cases it make interact with the world AFTER it breaks (seems to occur if you set the type to -1). Rope will sometimes contract and fall to the ground like you'd expect it to, but since it doesn't interact with the world the effect is just jaring. -- @module native -- @submodule rope -- @see ADD_ROPE -- @usage Object ADD_ROPE(float x, float y, float z, float rotX, float rotY, float rotZ, float length, int ropeType, float maxLength, float minLength, float p10, BOOL p11, BOOL p12, BOOL rigid, float p14, BOOL breakWhenShot, Any* unkPtr); -- @param x float -- @param y float -- @param z float -- @param rotX float -- @param rotY float -- @param rotZ float -- @param length float -- @param ropeType int -- @param maxLength float -- @param minLength float -- @param p10 float -- @param p11 BOOL -- @param p12 BOOL -- @param rigid BOOL -- @param p14 float -- @param breakWhenShot BOOL -- @param unkPtr Any* -- @return Object function AddRope(x, y, z, rotX, rotY, rotZ, length, ropeType, maxLength, minLength, p10, p11, p12, rigid, p14, breakWhenShot, unkPtr) end -- @todo -- @module native -- @submodule rope -- @see DELETE_ROPE -- @usage void DELETE_ROPE(Object* rope); -- @param rope Object* -- @return void function DeleteRope(rope) end -- @todo -- @module native -- @submodule rope -- @see DELETE_CHILD_ROPE -- @usage Any DELETE_CHILD_ROPE(Object rope); -- @param rope Object -- @return Any function DeleteChildRope(rope) end -- Ptr is correct -- @module native -- @submodule rope -- @see DOES_ROPE_EXIST -- @usage BOOL DOES_ROPE_EXIST(Object* rope); -- @param rope Object* -- @return BOOL function DoesRopeExist(rope) end -- @todo -- @module native -- @submodule rope -- @see ROPE_DRAW_SHADOW_ENABLED -- @usage void ROPE_DRAW_SHADOW_ENABLED(Object* rope, BOOL toggle); -- @param rope Object* -- @param toggle BOOL -- @return void function RopeDrawShadowEnabled(rope, toggle) end -- Rope presets can be found in the gamefiles. One example is "ropeFamily3", it is NOT a hash but rather a string. -- @module native -- @submodule rope -- @see LOAD_ROPE_DATA -- @usage Any LOAD_ROPE_DATA(Object rope, char* rope_preset); -- @param rope Object -- @param rope_preset char* -- @return Any function LoadRopeData(rope, rope_preset) end -- @todo -- @module native -- @submodule rope -- @see PIN_ROPE_VERTEX -- @usage void PIN_ROPE_VERTEX(Object rope, int vertex, float x, float y, float z); -- @param rope Object -- @param vertex int -- @param x float -- @param y float -- @param z float -- @return void function PinRopeVertex(rope, vertex, x, y, z) end -- @todo -- @module native -- @submodule rope -- @see UNPIN_ROPE_VERTEX -- @usage Any UNPIN_ROPE_VERTEX(Object rope, int vertex); -- @param rope Object -- @param vertex int -- @return Any function UnpinRopeVertex(rope, vertex) end -- @todo -- @module native -- @submodule rope -- @see GET_ROPE_VERTEX_COUNT -- @usage int GET_ROPE_VERTEX_COUNT(Object rope); -- @param rope Object -- @return int function GetRopeVertexCount(rope) end -- Attaches entity 1 to entity 2. -- @module native -- @submodule rope -- @see ATTACH_ENTITIES_TO_ROPE -- @usage void ATTACH_ENTITIES_TO_ROPE(Object rope, Entity ent1, Entity ent2, float ent1_x, float ent1_y, float ent1_z, float ent2_x, float ent2_y, float ent2_z, float length, BOOL p10, BOOL p11, Any* p12, Any* p13); -- @param rope Object -- @param ent1 Entity -- @param ent2 Entity -- @param ent1_x float -- @param ent1_y float -- @param ent1_z float -- @param ent2_x float -- @param ent2_y float -- @param ent2_z float -- @param length float -- @param p10 BOOL -- @param p11 BOOL -- @param p12 Any* -- @param p13 Any* -- @return void function AttachEntitiesToRope(rope, ent1, ent2, ent1_x, ent1_y, ent1_z, ent2_x, ent2_y, ent2_z, length, p10, p11, p12, p13) end -- The position supplied can be anywhere, and the entity should anchor relative to that point from it's origin. -- @module native -- @submodule rope -- @see ATTACH_ROPE_TO_ENTITY -- @usage void ATTACH_ROPE_TO_ENTITY(Object rope, Entity entity, float x, float y, float z, BOOL p5); -- @param rope Object -- @param entity Entity -- @param x float -- @param y float -- @param z float -- @param p5 BOOL -- @return void function AttachRopeToEntity(rope, entity, x, y, z, p5) end -- @todo -- @module native -- @submodule rope -- @see DETACH_ROPE_FROM_ENTITY -- @usage void DETACH_ROPE_FROM_ENTITY(Object rope, Entity entity); -- @param rope Object -- @param entity Entity -- @return void function DetachRopeFromEntity(rope, entity) end -- @todo -- @module native -- @submodule rope -- @see ROPE_SET_UPDATE_PINVERTS -- @usage void ROPE_SET_UPDATE_PINVERTS(Object rope); -- @param rope Object -- @return void function RopeSetUpdatePinverts(rope) end -- @todo -- @module native -- @submodule rope -- @see GET_ROPE_LAST_VERTEX_COORD -- @usage Any GET_ROPE_LAST_VERTEX_COORD(Object rope); -- @param rope Object -- @return Any function GetRopeLastVertexCoord(rope) end -- @todo -- @module native -- @submodule rope -- @see GET_ROPE_VERTEX_COORD -- @usage Any GET_ROPE_VERTEX_COORD(Object rope, int vertex); -- @param rope Object -- @param vertex int -- @return Any function GetRopeVertexCoord(rope, vertex) end -- @todo -- @module native -- @submodule rope -- @see START_ROPE_WINDING -- @usage void START_ROPE_WINDING(Object rope); -- @param rope Object -- @return void function StartRopeWinding(rope) end -- @todo -- @module native -- @submodule rope -- @see STOP_ROPE_WINDING -- @usage void STOP_ROPE_WINDING(Object rope); -- @param rope Object -- @return void function StopRopeWinding(rope) end -- @todo -- @module native -- @submodule rope -- @see START_ROPE_UNWINDING_FRONT -- @usage void START_ROPE_UNWINDING_FRONT(Object rope); -- @param rope Object -- @return void function StartRopeUnwindingFront(rope) end -- @todo -- @module native -- @submodule rope -- @see STOP_ROPE_UNWINDING_FRONT -- @usage void STOP_ROPE_UNWINDING_FRONT(Object rope); -- @param rope Object -- @return void function StopRopeUnwindingFront(rope) end -- @todo -- @module native -- @submodule rope -- @see ROPE_CONVERT_TO_SIMPLE -- @usage void ROPE_CONVERT_TO_SIMPLE(Object rope); -- @param rope Object -- @return void function RopeConvertToSimple(rope) end -- Loads rope textures for all ropes in the current scene. -- @module native -- @submodule rope -- @see ROPE_LOAD_TEXTURES -- @usage Any ROPE_LOAD_TEXTURES(); -- @return Any function RopeLoadTextures() end -- @todo -- @module native -- @submodule rope -- @see ROPE_ARE_TEXTURES_LOADED -- @usage BOOL ROPE_ARE_TEXTURES_LOADED(); -- @return BOOL function RopeAreTexturesLoaded() end -- Unloads rope textures for all ropes in the current scene. -- @module native -- @submodule rope -- @see ROPE_UNLOAD_TEXTURES -- @usage Any ROPE_UNLOAD_TEXTURES(); -- @return Any function RopeUnloadTextures() end -- Forces a rope to a certain length. -- @module native -- @submodule rope -- @see ROPE_FORCE_LENGTH -- @usage Any ROPE_FORCE_LENGTH(Object rope, float length); -- @param rope Object -- @param length float -- @return Any function RopeForceLength(rope, length) end -- Reset a rope to a certain length. -- @module native -- @submodule rope -- @see ROPE_RESET_LENGTH -- @usage Any ROPE_RESET_LENGTH(Object rope, BOOL length); -- @param rope Object -- @param length BOOL -- @return Any function RopeResetLength(rope, length) end -- @todo -- @module native -- @submodule rope -- @see APPLY_IMPULSE_TO_CLOTH -- @usage void APPLY_IMPULSE_TO_CLOTH(float posX, float posY, float posZ, float vecX, float vecY, float vecZ, float impulse); -- @param posX float -- @param posY float -- @param posZ float -- @param vecX float -- @param vecY float -- @param vecZ float -- @param impulse float -- @return void function ApplyImpulseToCloth(posX, posY, posZ, vecX, vecY, vecZ, impulse) end -- @todo -- @module native -- @submodule rope -- @see SET_DAMPING -- @usage void SET_DAMPING(Object rope, int vertex, float value); -- @param rope Object -- @param vertex int -- @param value float -- @return void function SetDamping(rope, vertex, value) end -- seems to be frequently used with the NETWORK::NET_TO_x natives, particularly with vehicles. It is often the only ROPE:: native in a script. -- @module native -- @submodule rope -- @see ACTIVATE_PHYSICS -- @usage void ACTIVATE_PHYSICS(Entity entity); -- @param entity Entity -- @return void function ActivatePhysics(entity) end -- @todo -- @module native -- @submodule rope -- @see SET_CGOFFSET -- @usage void SET_CGOFFSET(Object rope, float x, float y, float z); -- @param rope Object -- @param x float -- @param y float -- @param z float -- @return void function SetCgoffset(rope, x, y, z) end -- @todo -- @module native -- @submodule rope -- @see GET_CGOFFSET -- @usage Vector3 GET_CGOFFSET(Object rope); -- @param rope Object -- @return Vector3 function GetCgoffset(rope) end -- @todo -- @module native -- @submodule rope -- @see SET_CG_AT_BOUNDCENTER -- @usage void SET_CG_AT_BOUNDCENTER(Object rope); -- @param rope Object -- @return void function SetCgAtBoundcenter(rope) end -- @todo -- @module native -- @submodule rope -- @see BREAK_ENTITY_GLASS -- @usage void BREAK_ENTITY_GLASS(Any p0, float p1, float p2, float p3, float p4, float p5, float p6, float p7, float p8, Any p9, BOOL p10); -- @param p0 Any -- @param p1 float -- @param p2 float -- @param p3 float -- @param p4 float -- @param p5 float -- @param p6 float -- @param p7 float -- @param p8 float -- @param p9 Any -- @param p10 BOOL -- @return void function BreakEntityGlass(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) end -- @todo -- @module native -- @submodule rope -- @see SET_DISABLE_BREAKING -- @usage Any SET_DISABLE_BREAKING(Object rope, BOOL enabled); -- @param rope Object -- @param enabled BOOL -- @return Any function SetDisableBreaking(rope, enabled) end -- sometimes used used with NET_TO_OBJ hash collision last 2 words -- @module native -- @submodule rope -- @see SET_DISABLE_FRAG_DAMAGE -- @usage void SET_DISABLE_FRAG_DAMAGE(Object object, BOOL toggle); -- @param object Object -- @param toggle BOOL -- @return void function SetDisableFragDamage(object, toggle) end
-- -- Copyright (c) 2016, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- -- extracts features from an image using a trained model require 'torch' require 'paths' require 'io' local DataLoader = require 'dataloader' if #arg < 1 then io.stderr:write('Usage: th extract-features-batch.lua [MODEL]...\n') os.exit(1) end for _, f in ipairs(arg) do if not paths.filep(f) then io.stderr:write('file not found: ' .. f .. '\n') os.exit(1) end end require 'cudnn' require 'cunn' require 'image' local models = require 'models/init' local opt = {} opt.gen = 'gen' opt.data = '/d/home/yushiyao/Place2/256x256/val' opt.dataset = 'places2' opt.nThreads = 8 opt.batchSize = 128 opt.nGPU = 2 opt.shareGradInput = true opt.featureMap = false opt.outputDir = '/d/home/yushiyao/Place2/' -- Load the model print ('loading model') local model = models.setup(opt, arg[1]) -- Setup the dataloader local loader = DataLoader.create(opt) -- The model was trained with this input normalization local meanstd = { mean = { 0.485, 0.456, 0.406 }, std = { 0.229, 0.224, 0.225 }, } local features function process_dataset(dataloader) local timer = torch.Timer() local dataTimer = torch.Timer() local size = dataloader:size() print ('Number of batches: ', size) local feature = {} feature['name'] = {} for n, sample in dataloader:run() do local dataTime = dataTimer:time().real input = copyInputs(sample) local output = model:forward(input):float() print (('Extract:[%d/%d] Time:%.3f Data:%.3f'):format(n, size, timer:time().real, dataTime)) timer:reset() dataTimer:reset() local idx if n == 1 then feature['feature'] = output else feature['feature'] = torch.cat(feature['feature'], output, 1) print (feature['feature']:size()) end for i,name in ipairs(sample.name) do table.insert(feature['name'],name) end end print ('start saving features') feature_path = paths.concat(opt.outputDir) if not paths.dir(feature_path) then print ('creating dir ', feature_path) paths.mkdir(feature_path) end torch.save(paths.concat(feature_path,'feature.t7'), feature) end function copyInputs(sample) local input = (opt.nGPU == 1 and torch.CudaTensor() or cutorch.createCudaHostTensor()) input:resize(sample.input:size()):copy(sample.input) return input end print ('start extracting feature') process_dataset(loader)
----------------------------------- -- Area: Windurst Woods -- NPC: Chat Manual -- Type: Tutorial NPC -- !pos 10.928 1.915 -40.094 241 ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) player:startEvent(6106) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
-- From https://github.com/Funk66/vim return { yamlls = { settings = { yaml = { hover = true, completion = true, validate = true, schemaStore = { enable = true, url = "https://www.schemastore.org/api/json/catalog.json", }, schemas = { ["https://raw.githubusercontent.com/awslabs/goformation/master/schema/sam.schema.json"] = "template.{yml,yaml}", ["https://json.schemastore.org/github-workflow.json"] = "/.github/workflows/*", }, }, }, }, jsonls = { init_options = { provideFormatter = false }, settings = { json = { schemas = { { fileMatch = { "package.json" }, url = "https://json.schemastore.org/package.json", }, { fileMatch = { "tsconfig.json", "tsconfig.*.json", }, url = "https://json.schemastore.org/tsconfig.json", }, { fileMatch = { ".babelrc.json", ".babelrc", "babel.config.json", }, url = "https://json.schemastore.org/babelrc.json", }, { fileMatch = { ".eslintrc.json", ".eslintrc", }, url = "https://json.schemastore.org/eslintrc.json", }, { fileMatch = { ".prettierrc", ".prettierrc.json", "prettier.config.json", }, url = "https://json.schemastore.org/prettierrc", }, { fileMatch = { ".stylelintrc", ".stylelintrc.json", "stylelint.config.json", }, url = "https://json.schemastore.org/stylelintrc", }, { fileMatch = { "*.cf.json", "cloudformation.json", }, url = "https://raw.githubusercontent.com/awslabs/goformation/v5.2.9/schema/cloudformation.schema.json", }, { fileMatch = { "serverless.template", "*.sam.json", "sam.json", }, url = "https://raw.githubusercontent.com/awslabs/goformation/v5.2.9/schema/sam.schema.json", }, { fileMatch = { ".github/workflow-templates/**.properties.json" }, url = "https://json.schemastore.org/github-workflow-template-properties.json", }, { fileMatch = { "packer.json" }, url = "https://json.schemastore.org/packer.json", }, }, }, }, }, }
-- power/register.lua --[[ Machine Registration API ]] local me = microexpansion local power = me.power -- [function] Register machine function me.register_machine(itemstring, def) -- Set after_place_node def.after_place_node = function(pos, player) if def.after_place_node then def.after_place_node(pos, player) end local meta = minetest.get_meta(pos) local nodes = me.get_connected_nodes(pos) meta:set_string("infotext", def.description.."\nNo Network") for _, pos2 in pairs(nodes) do local id = minetest.get_meta(pos2):get_string("network_id") if id ~= "" then meta:set_string("infotext", def.description.."\nNetwork ID: "..id) meta:set_string("network_id", id) end end -- Trace Network power.trace(pos) -- Set demand if def.demand then me.network_set_demand(pos, def.demand) end if type(def.machine) == "table" then power.add_machine(pos, def.machine) end end -- Set on_destruct def.on_destruct = function(pos, player) if def.on_destruct then def.on_destruct(pos, player) end local meta = minetest.get_meta(pos) if meta:get_string("network_id") ~= "" then -- Set demand me.network_set_demand(pos, 0) -- Remove item from network me.network_remove(pos) -- Retrace Network power.trace(pos) end end -- Set connects_to def.connects_to = {"group:me_connect"} -- Set me_connect group def.groups = def.groups or {} def.groups.me_connect = 1 me.register_node(itemstring, def) end -- [function] Get machine definition function me.get_def(name, key) if type(name) == "table" then local node = me.get_node(name) if node then name = node.name end end local def = minetest.registered_nodes[name] -- Check name and if registered if not name or not def then return end if key then return def[key] else return def end end
local scene = sl.Scene.empty(sl.device) local node = scene:createNode() local spectator = node:addComponent('Spectator') assert(spectator) spectator:setMovementSpeed(123) assert(spectator:movementSpeed() == 123) spectator:setMouseSensitivity(123) assert(spectator:mouseSensitivity() == 123)
-- Usage: filedecrypt.lua [file] [password] > decryptedfile -- -- Decrypts everything from [file] and writes decrypted data to stdout. -- Do not use for real decryption, because the password is easily viewable -- while decrypting. -- require("aeslua"); if (#arg ~= 2) then print("Usage: filedecrypt.lua [file] [password] > decryptedfile\n"); print("Do not use for real decryption, because the password is easily viewable while decrypting."); return 1; end local file = assert(io.open(arg[1], "r")); local cipher = file:read("*all"); local plain = aeslua.decrypt(arg[2], cipher); if (plain == nil) then print("Invalid password."); else io.write(plain); end file:close();
local helpers = require "spec.helpers" local json = require "cjson" local paseto = require "paseto.v2" local utils = require "kong.tools.utils" local encode_base64 = ngx.encode_base64 for _, strategy in helpers.each_strategy() do describe("Plugin: paseto (access) [#" .. strategy .. "]", function() local proxy_client local secret_key_1, secret_key_3 local payload_claims, footer_claims setup(function() local bp, _, dao = helpers.get_db_utils(strategy) local routes = {} for i = 1, 10 do routes[i] = bp.routes:insert { hosts = { "paseto" .. i .. ".com" }, } end local consumers = bp.consumers local consumer1 = consumers:insert({ username = "paseto_tests_consumer_1" }) local consumer3 = consumers:insert({ username = "paseto_tests_consumer_3" }) local anonymous_user = consumers:insert({ username = "nobody" }) secret_key_1, _ = paseto.generate_asymmetric_secret_key() local _, public_key_2 = paseto.generate_asymmetric_secret_key() secret_key_3, _ = paseto.generate_asymmetric_secret_key() payload_claims = { iss = "paragonie.com", jti = "87IFSGFgPNtQNNuw0AtuLttP", aud = "some-audience.com", sub = "test", iat = "2018-01-01T00:00:00+00:00", nbf = "2018-01-01T00:00:00+00:00", exp = "2099-01-01T00:00:00+00:00", data = "this is a signed message", myclaim = "required value" } footer_claims = { kid = "signature_verification_success" } dao.paseto_keys:insert { consumer_id = consumer1.id, kid = "signature_verification_fail", public_key = encode_base64(public_key_2) } dao.paseto_keys:insert { consumer_id = consumer3.id, kid = "signature_verification_success", secret_key = encode_base64(secret_key_3) } local plugins = bp.plugins plugins:insert({ name = "paseto", route_id = routes[1].id, config = {}, }) plugins:insert({ name = "ctx-checker", route_id = routes[1].id, config = { ctx_check_field = "authenticated_paseto_token" }, }) plugins:insert({ name = "paseto", route_id = routes[2].id, config = { claims_to_verify = { claim_1 = { claim = "IssuedBy", value = "paragonie.com" }, claim_2 = { claim = "IdentifiedBy", value = "87IFSGFgPNtQNNuw0AtuLttP" }, claim_3 = { claim = "ForAudience", value = "some-audience.com" }, claim_4 = { claim = "Subject", value = "test" }, claim_5 = { claim = "NotExpired", value = "true" }, claim_6 = { claim = "ValidAt", value = "true" }, claim_7 = { claim = "ContainsClaim", value = "data" }, claim_8 = { claim = "myclaim", value = "required value" }, } }, }) plugins:insert({ name = "paseto", route_id = routes[3].id, config = { run_on_preflight = false }, }) plugins:insert({ name = "paseto", route_id = routes[4].id, config = { cookie_names = { "choco", "berry" } }, }) plugins:insert({ name = "paseto", route_id = routes[5].id, config = { uri_param_names = { "token", "mypaseto" } }, }) plugins:insert({ name = "paseto", route_id = routes[6].id, config = { anonymous = anonymous_user.id }, }) plugins:insert({ name = "paseto", route_id = routes[7].id, config = { anonymous = utils.uuid() }, }) assert(helpers.start_kong { database = strategy, plugins = "bundled, paseto, ctx-checker", real_ip_header = "X-Forwarded-For", real_ip_recursive = "on", trusted_ips = "0.0.0.0/0, ::/0", nginx_conf = "spec/fixtures/custom_nginx.template", }) proxy_client = helpers.proxy_client() end) teardown(function() if proxy_client then proxy_client:close() end helpers.stop_kong() end) describe("refusals", function() it("returns 401 Unauthorized if no PASETO is found in the request", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto1.com", } }) local json_body = json.decode(assert.res_status(401, res)) assert.same({ message = "Unauthorized" }, json_body) end) it("returns 401 if the token is not in a valid PASETO format", function() local token = "v2.public" local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto1.com", } }) local body = assert.res_status(401, res) local json_body = json.decode(body) assert.same({ message = "Bad token; Invalid token format" }, json_body) end) it("returns 401 if the token footer does not contain a kid claim", function() local footer_claims_2 = { no_kid_claim = "1234" } local token = paseto.sign(secret_key_1, payload_claims, footer_claims_2) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto1.com", } }) local body = assert.res_status(401, res) local json_body = json.decode(body) assert.same({ message = "No mandatory 'kid' in claims" }, json_body) end) it("returns 403 if no key with a kid matching the claim is found", function() local footer_claims_2 = { kid = "1234" } local token = paseto.sign(secret_key_1, payload_claims, footer_claims_2) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto1.com", } }) local body = assert.res_status(403, res) local json_body = json.decode(body) assert.same({ message = "No key found for given 'kid'" }, json_body) end) it("returns 403 when signature verification fails", function() local footer_claims_2 = { kid = "signature_verification_fail" } local token = paseto.sign(secret_key_1, payload_claims, footer_claims_2) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto1.com", } }) local body = assert.res_status(403, res) local json_body = json.decode(body) assert.same({ message = "Token verification failed; Invalid signature for this message" }, json_body) end) it("returns 403 when registered claims verification fails", function() local invalid_payload_claims = { iss = "paragonie.com", jti = "87IFSGFgPNtQNNuw0AtuLttP", aud = "some-audience.com", sub = "test", iat = "2018-01-01T00:00:00+00:00", nbf = "2018-01-01T00:00:00+00:00", exp = "2018-02-01T00:00:00+00:00", data = "this is a signed message", myclaim = "required value" } local token = paseto.sign(secret_key_3, invalid_payload_claims, footer_claims) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto2.com", } }) local body = assert.res_status(403, res) local json_body = json.decode(body) assert.same({ message = "Token verification failed; Token has expired" }, json_body) end) it("returns 403 when custom claims verification fails", function() local invalid_payload_claims = { iss = "paragonie.com", jti = "87IFSGFgPNtQNNuw0AtuLttP", aud = "some-audience.com", sub = "test", iat = "2018-01-01T00:00:00+00:00", nbf = "2018-01-01T00:00:00+00:00", exp = "2099-01-01T00:00:00+00:00", data = "this is a signed message", myclaim = "invalid" } local token = paseto.sign(secret_key_3, invalid_payload_claims, footer_claims) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto2.com", } }) local body = assert.res_status(403, res) local json_body = json.decode(body) assert.same({ message = "Token verification failed; Claim 'myclaim' does not match the expected value" }, json_body) end) it("returns 401 when the token is not found in the cookie 'banana'", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto4.com", ["Cookie"] = "banana=" .. token .. "; path=/;domain=.paseto4.com", } }) local json_body = json.decode(assert.res_status(401, res)) assert.same({ message = "Unauthorized" }, json_body) end) it("returns 403 when the token in cookies is malformed", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto4.com", ["Cookie"] = "berry=" .. "invalid" .. token .. "; path=/;domain=.paseto4.com", } }) local json_body = json.decode(assert.res_status(403, res)) assert.same({ message = "Token verification failed; Invalid message header" }, json_body) end) it("returns 401 when the token is not found in the URL parameter 'mytoken'", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request/?mytoken=" .. token, headers = { ["Host"] = "paseto5.com", } }) local json_body = json.decode(assert.res_status(401, res)) assert.same({ message = "Unauthorized" }, json_body) end) it("returns Unauthorized on OPTIONS requests if run_on_preflight is true", function() local res = assert(proxy_client:send { method = "OPTIONS", path = "/request", headers = { ["Host"] = "paseto1.com" } }) local json_body = json.decode(assert.res_status(401, res)) assert.same({ message = "Unauthorized" }, json_body) end) end) describe("successful requests", function() it("proxies the request on token verification", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto1.com", } }) local body = json.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request on token and claims verification", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto2.com", } }) local body = json.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request when the token is found in the cookie 'choco'", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto4.com", ["Cookie"] = "choco=" .. token .. "; path=/;domain=.paseto4.com", } }) local body = json.decode(assert.res_status(200, res)) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request when the token is found in the cookie 'berry'", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto4.com", ["Cookie"] = "berry=" .. token .. "; path=/;domain=.paseto4.com", } }) local body = json.decode(assert.res_status(200, res)) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request when the token is found in URL parameters", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request/?paseto=" .. token, headers = { ["Host"] = "paseto1.com", } }) local body = json.decode(assert.res_status(200, res)) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request when the token is found in a custom URL parameter", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local res = assert(proxy_client:send { method = "GET", path = "/request/?token=" .. token, headers = { ["Host"] = "paseto5.com", } }) local body = json.decode(assert.res_status(200, res)) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("returns 200 on OPTIONS requests if run_on_preflight is false", function() local res = assert(proxy_client:send { method = "OPTIONS", path = "/request", headers = { ["Host"] = "paseto3.com" } }) assert.res_status(200, res) end) end) describe("ctx.authenticated_paseto_token", function() it("is added to ngx.ctx when authenticated", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto1.com", } }) assert.res_status(200, res) local header = assert.header("ctx-checker-authenticated-paseto-token", res) assert.equal(token, header) end) end) describe("config.anonymous", function() it("proxies the request with valid credentials and anonymous", function() local token = paseto.sign(secret_key_3, payload_claims, footer_claims) local authorization = "Bearer " .. token local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "paseto6.com" } }) local body = json.decode(assert.res_status(200, res)) assert.equal("paseto_tests_consumer_3", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request with invalid credentials and anonymous", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto6.com" } }) local body = json.decode(assert.res_status(200, res)) assert.equal("true", body.headers["x-anonymous-consumer"]) assert.equal("nobody", body.headers["x-consumer-username"]) end) it("errors when the specified anonymous user doesn't exist", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "paseto7.com" } }) assert.response(res).has.status(500) end) end) end) describe("Plugin: paseto (access) [#" .. strategy .. "]", function() local client local user1 local user2 local anonymous local paseto_token local payload_claims, footer_claims setup(function() local bp, _, dao = helpers.get_db_utils(strategy) local service1 = bp.services:insert({ path = "/request" }) local route1 = bp.routes:insert { hosts = { "logical-and.com" }, service = service1, } bp.plugins:insert { name = "paseto", route_id = route1.id, } bp.plugins:insert { name = "key-auth", route_id = route1.id, } anonymous = bp.consumers:insert { username = "Anonymous", } user1 = bp.consumers:insert { username = "Mickey", } user2 = bp.consumers:insert { username = "Aladdin", } local service2 = bp.services:insert({ path = "/request" }) local route2 = bp.routes:insert { hosts = { "logical-or.com" }, service = service2, } bp.plugins:insert { name = "paseto", route_id = route2.id, config = { anonymous = anonymous.id, }, } bp.plugins:insert { name = "key-auth", route_id = route2.id, config = { anonymous = anonymous.id, }, } bp.keyauth_credentials:insert { key = "Mouse", consumer_id = user1.id, } local secret_key = paseto.generate_asymmetric_secret_key() dao.paseto_keys:insert { consumer_id = user2.id, kid = "123456789", secret_key = encode_base64(secret_key) } payload_claims = { iss = "paragonie.com", jti = "87IFSGFgPNtQNNuw0AtuLttP", aud = "some-audience.com", sub = "test", iat = "2018-01-01T00:00:00+00:00", nbf = "2018-01-01T00:00:00+00:00", exp = "2099-01-01T00:00:00+00:00", data = "this is a signed message", myclaim = "required value" } footer_claims = { kid = "123456789" } paseto_token = "Bearer " .. paseto.sign(secret_key, payload_claims, footer_claims) assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", custom_plugins = "paseto", })) client = helpers.proxy_client() end) teardown(function() if client then client:close() end helpers.stop_kong() end) describe("multiple auth without anonymous, logical AND", function() it("passes with all credentials provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["apikey"] = "Mouse", ["Authorization"] = paseto_token, } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert(id == user1.id or id == user2.id) end) it("fails 401, with only the first credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["apikey"] = "Mouse", } }) assert.response(res).has.status(401) end) it("fails 401, with only the second credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["Authorization"] = paseto_token, } }) assert.response(res).has.status(401) end) it("fails 401, with no credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", } }) assert.response(res).has.status(401) end) end) describe("multiple auth with anonymous, logical OR", function() it("passes with all credentials provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["apikey"] = "Mouse", ["Authorization"] = paseto_token, } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert(id == user1.id or id == user2.id) end) it("passes with only the first credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["apikey"] = "Mouse", } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert.equal(user1.id, id) end) it("passes with only the second credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["Authorization"] = paseto_token, } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert.equal(user2.id, id) end) it("passes with no credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", } }) assert.response(res).has.status(200) assert.request(res).has.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.equal(id, anonymous.id) end) end) end) end
--[[ Copyright (C) Udorn (Blackhand) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] --[[ ScanModule to be integrated in a ScanTask for sniping auctions. --]] vendor.SniperScanModule = {} vendor.SniperScanModule.prototype = {} vendor.SniperScanModule.metatable = {__index = vendor.SniperScanModule.prototype} local log = vendor.Debug:new("SniperScanModule") --[[ Creates a new instance. --]] function vendor.SniperScanModule:new(itemModel) local instance = setmetatable({}, self.metatable) instance.itemModel = itemModel-- or vendor.Scanner.scanFrame.itemModel return instance end --[[ Notifies the beginning of the scan. The info struct contains: itemLinkKey, name, minLevel, maxLevel, invTypeIndex, classIndex, subclassIndex, isUsable, qualityIndex --]] function vendor.SniperScanModule.prototype:StartScan(info) log:Debug("StartScan name [%s]", info.name) self.info = info end --[[ Notifies the termination of the scan. --]] function vendor.SniperScanModule.prototype:StopScan(complete) log:Debug("StopScan name [%s] complete [%s] itemLinkKey [%s]", self.info.name, complete, self.info.itemLinkKey) end --[[ Notifies the ScanModule that a page is about to be read. --]] function vendor.SniperScanModule.prototype:StartPage(page) end --[[ Notifies the ScanModule that a page is now finished. --]] function vendor.SniperScanModule.prototype:StopPage() end --[[ Notifies about the given auction data read. The auctions will be notified once for each index. --]] function vendor.SniperScanModule.prototype:NotifyAuction(itemLinkKey, itemLink, index, name, texture, count, quality, canUse, level, minBid, minIncrement, buyout, bidAmount, highBidder, owner, saleStatus, timeLeft) local askForBuy, reason, sniperId, doBid, doBuyout, reasonSort = vendor.Sniper:ItemScanned(index, itemLink, name, highBidder) if (askForBuy) then log:Debug("askForBuy index [%s] minBid: %d bidAmount: %d buyout: %d", index, minBid or 777, bidAmount or 777, buyout or 777) local bid = minBid if (bidAmount and bidAmount > 0) then bid = bidAmount + minIncrement end log:Debug("add item to itemModel [%s]", self.itemModel) self.itemModel:AddItem(itemLink, itemLinkKey, name, texture, timeLeft, count, minBid, minIncrement, buyout or 0, bidAmount, owner, reason, sniperId, index, quality, highBidder, reasonSort) log:Debug("item was added") end end
-- Generated by LairTool tatooine_evil_settlement_neutral_medium_theater = Lair:new { mobiles = {{"evil_settler",4},{"domestic_eopie", 1}}, spawnLimit = 12, buildingsVeryEasy = {"object/building/poi/tatooine_evil_settlers_large2.iff","object/building/poi/tatooine_evil_settlers_large3.iff"}, buildingsEasy = {"object/building/poi/tatooine_evil_settlers_large2.iff","object/building/poi/tatooine_evil_settlers_large3.iff"}, buildingsMedium = {"object/building/poi/tatooine_evil_settlers_large2.iff","object/building/poi/tatooine_evil_settlers_large3.iff"}, buildingsHard = {"object/building/poi/tatooine_evil_settlers_large2.iff","object/building/poi/tatooine_evil_settlers_large3.iff"}, buildingsVeryHard = {"object/building/poi/tatooine_evil_settlers_large2.iff","object/building/poi/tatooine_evil_settlers_large3.iff"}, mobType = "npc", buildingType = "theater" } addLairTemplate("tatooine_evil_settlement_neutral_medium_theater", tatooine_evil_settlement_neutral_medium_theater)
object_tangible_furniture_decorative_wod_sm_potted_plant_09 = object_tangible_furniture_decorative_shared_wod_sm_potted_plant_09:new { } ObjectTemplates:addTemplate(object_tangible_furniture_decorative_wod_sm_potted_plant_09, "object/tangible/furniture/decorative/wod_sm_potted_plant_09.iff")
require ("map") require ("file") require ("control") require ("interface") require ("player") TICKRATE = 1/80 function love.run() if love.math then love.math.setRandomSeed(os.time()) end if love.load then love.load(arg) end local previous = love.timer.getTime() local lag = 0.0 while true do local current = love.timer.getTime() local elapsed = current - previous previous = current lag = lag + elapsed if love.event then love.event.pump() for name, a,b,c,d,e,f in love.event.poll() do if name == "quit" then if not love.quit or not love.quit() then return a end end love.handlers[name](a,b,c,d,e,f) end end while lag >= TICKRATE do if love.update then love.update(TICKRATE) end lag = lag - TICKRATE end if love.graphics and love.graphics.isActive() then love.graphics.clear(love.graphics.getBackgroundColor()) love.graphics.origin() if love.draw then love.draw(lag / TICKRATE) end love.graphics.present() end end end function mindMain() function love.load() loadVars() loadSave() loadRecources() loadMapLayer1(nil) loadMapCollisions(nil, nil) end function love.draw() love.graphics.setFont(font_26) --interfaceDrawRightString() console_string[1] = "DELTA_TIME = " .. dt mapDraw() drawPlayer() mapDrawUp() interfaceDrawMode() --drawPlayer() end function love.update(dt) testWherePlayer() local count = 0 controlKeyboard() movePlayer() console_string[3] = "PLAYER_X = " .. player.x .. "; PLAYER_Y = " .. player.y console_string[4] = "PLAYER_MUST_X = " .. player.must_x .. "; PLAYER_MUST_Y = " .. player.must_y console_string[6] = "PLAYER_POS_X = " .. player.pos_x .. "; PLAYER_POS_Y = " .. player.pos_y if mode_teleport == true then console_string[7] = "MODE_TELEPORT = true" else console_string[7] = "MODE_TELEPORT = false" end end --end end
local Debugger = require("hotswitch-hs/lib/common/Debugger") local TimeChecker = require("hotswitch-hs/lib/common/TimeChecker") local CanvasConstants = require("hotswitch-hs/lib/common/CanvasConstants") local doesShowOnMainScreen = true local function calcBaseCanvasFrame(orderedWindows) local panelH = #orderedWindows * CanvasConstants.ROW_HEIGHT + CanvasConstants.PADDING * 4 local targetScreenFrame if doesShowOnMainScreen then targetScreenFrame = hs.screen.mainScreen():frame() else targetScreenFrame = hs.screen.primaryScreen():frame() end local panelX = targetScreenFrame.x + targetScreenFrame.w / 2 - CanvasConstants.PANEL_W / 2 local panelY = targetScreenFrame.y + targetScreenFrame.h / 2 - panelH / 2 local baseCanvasFrame = { x = panelX, y = panelY, h = panelH, w = CanvasConstants.PANEL_W } return baseCanvasFrame end local function setShowingOnMainScreen(flag) doesShowOnMainScreen = flag end return { calcBaseCanvasFrame = calcBaseCanvasFrame, setShowingOnMainScreen = setShowingOnMainScreen, }
local combat = Combat() combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_BLUE) combat:setParameter(COMBAT_PARAM_DISPEL, CONDITION_CURSED) combat:setParameter(COMBAT_PARAM_AGGRESSIVE, false) local spell = Spell("instant") function spell.onCastSpell(creature, variant) return combat:execute(creature, variant) end spell:name("Cure Curse") spell:words("exana mort") spell:group("healing") spell:vocation("paladin;true", "royal paladin;true") spell:id(147) spell:cooldown(6000) spell:groupCooldown(1000) spell:level(80) spell:mana(40) spell:isSelfTarget(true) spell:isAggressive(false) spell:isPremium(true) spell:needLearn(false) spell:register()
local name = "car_cyan" local definition = ... definition.description = "Cyan car" definition.inventory_image = "inv_car_cyan.png" definition.wield_image = "inv_car_cyan.png" definition.textures = {"car_cyan.png"} vehicle_mash.register_vehicle("vehicle_mash:"..name, definition)
require("iuplua") multitext = iup.text{ multiline = "YES", expand = "YES" } item_open = iup.item{title="Open"} item_save = iup.item{title="Save"} item_exit = iup.item{title="Exit"} function item_exit:action() return iup.CLOSE end file_menu = iup.menu{item_open,item_save,iup.separator{},item_exit} sub1_menu = iup.submenu{file_menu, title = "File"} menu = iup.menu{sub1_menu} vbox = iup.vbox{ multitext } dlg = iup.dialog{ vbox, title = "Simple Notepad", size = "QUARTERxQUARTER", menu = menu } dlg:showxy(iup.CENTER,iup.CENTER) dlg.usersize = nil -- to be able to run this script inside another context if (iup.MainLoopLevel()==0) then iup.MainLoop() iup.Close() end
-- @module ae.ui.SlideRightGesture -- @group UI -- @brief Slide right gesture. local SlideRightGesture = ae.oo.class() -- @func -- @brief Creates a slide right gesture with no listener. -- @return The gesture. -- @func -- @brief Creates a slide right gesture. -- @param listener The function called when the gesture is detected. -- @return The gesture. function SlideRightGesture.new(listener) local self = ae.oo.new(SlideRightGesture) SlideRightGesture.construct(self,listener) return self end -- @func -- @brief Creates a slide right gesture with no listener. -- @func -- @brief Creates a slide right gesture. -- @param listener The function called when the gesture is detected. function SlideRightGesture.construct(self,listener) self.listener = listener self.triggerDistance = 0.1 self.touchDownX = {} end -- @brief Sets the listener. -- @param listener The listener. function SlideRightGesture:setListener(listener) self.listener = listener end -- @brief Invoked on touch down event. -- @param pointerId The pointer identifier. -- @param x The X-coordinate at which the event occured. -- @param y The Y-coordinate at which the event occured. function SlideRightGesture:touchDown(pointerId,x,y) self.touchDownX[pointerId] = x end -- @brief Invoked on touch move event. -- @param pointerId The pointer identifier. -- @param x The X-coordinate at which the event occured. -- @param y The Y-coordinate at which the event occured. function SlideRightGesture:touchMove(pointerId,x,y) end -- @brief Invoked on touch up event. -- @param pointerId The pointer identifier. -- @param x The X-coordinate at which the event occured. -- @param y The Y-coordinate at which the event occured. function SlideRightGesture:touchUp(pointerId,x,y) if self.touchDownX[pointerId] then local distance = x - self.touchDownX[pointerId] if distance >= self.triggerDistance and self.listener then self.listener(pointerId) return true end end self.touchDownX[pointerId] = nil return false end -- @brief Gets a string which represents the gesture. -- @return The string representing the gesture. function SlideRightGesture:__tostring() return ae.oo.tostring('ae.ui.SlideRightGesture', 'triggerDistance=' .. tostring(self.triggerDistance) .. ', listener=' .. tostring(self.listener),super.__tostring(self)) end return SlideRightGesture
--[[ VeKtor, Background Music Engine replacement local E = unpack(select(2, ...)); --Import: Engine ]] BINDING_HEADER_VEKTOR = GetAddOnMetadata(..., "Title") local AddOnName, Engine = ... local AddOn = LibStub("AceAddon-3.0"):NewAddon(AddOnName, "AceConsole-3.0") Engine[1] = AddOn _G[AddOnName] = Engine function AddOn:OnInitialize() AddOn:Print("initialized") end -- simple postpone init trigger local f=CreateFrame("Frame") f:RegisterEvent("PLAYER_LOGIN") f:SetScript("OnEvent", function() AddOn:Initialize() end)
local M = {} function M.config() require("indent_blankline").setup({ char = "│", use_treesitter = true, show_current_context = true, filetype_exclude = { "NvimTree", "Preview", "__doc__", "dashboard", "dashpreview", "fzf", "help", "log", "man", "markdown", "nerdtree", "peekaboo", "sagahover", "startify", "terminal", "translator", "vista", "packer", "aerial", "lspinfo", "lspsagafinder", "Trouble", }, buftype_exclude = { "terminal", "man", "trouble" }, context_patterns = { "class", "function", "method", "if", "table", "dictionary", "list", "parameters", "expression_list", "for_statement" }, }) end return setmetatable({}, { __call = function() return M.config() end, })
class("ActivityBossSPFScene", import(".ActivityBossSceneTemplate")).getUIName = function (slot0) return "ActivityBossSPFUI" end return class("ActivityBossSPFScene", import(".ActivityBossSceneTemplate"))
local Native = require('lib.native.native') ---@class FogModifier : Agent local FogModifier = class('FogModifier', assert(require('lib.oop.agent'))) ---<static> createRect ---@param forWhichPlayer Player ---@param state FogState ---@param where Rect ---@param useSharedVision boolean ---@param afterUnits boolean ---@return FogModifier function FogModifier:createRect(forWhichPlayer, state, where, useSharedVision, afterUnits) return FogModifier:fromUd(Native.CreateFogModifierRect(getUd(forWhichPlayer), state, getUd(where), useSharedVision, afterUnits)) end ---<static> createRadius ---@param forWhichPlayer Player ---@param state FogState ---@param centerx float ---@param centerY float ---@param radius float ---@param useSharedVision boolean ---@param afterUnits boolean ---@return FogModifier function FogModifier:createRadius(forWhichPlayer, state, centerx, centerY, radius, useSharedVision, afterUnits) return FogModifier:fromUd(Native.CreateFogModifierRadius(getUd(forWhichPlayer), state, centerx, centerY, radius, useSharedVision, afterUnits)) end ---<static> createRadiusLoc ---@param forWhichPlayer Player ---@param state FogState ---@param center Location ---@param radius float ---@param useSharedVision boolean ---@param afterUnits boolean ---@return FogModifier function FogModifier:createRadiusLoc(forWhichPlayer, state, center, radius, useSharedVision, afterUnits) return FogModifier:fromUd(Native.CreateFogModifierRadiusLoc(getUd(forWhichPlayer), state, getUd(center), radius, useSharedVision, afterUnits)) end ---destroy ---@return void function FogModifier:destroy() return Native.DestroyFogModifier(getUd(self)) end ---start ---@return void function FogModifier:start() return Native.FogModifierStart(getUd(self)) end ---stop ---@return void function FogModifier:stop() return Native.FogModifierStop(getUd(self)) end return FogModifier
local theming_configs = { "bufferline", "dashboard", "symbolsoutline", "nord", "lualine", "blankline", "transparent" } local others_configs = {"presence", "autosave", "neoscroll", "spotify"} local coding_configs = { "treesitter", "gps", "gitsigns", "lspconfig", "lspsign", "null", "betteresc", "snippets", "cmp", "autopairs" } local workflow_configs = { "twilight", "zenmode", "colorizer", "telescope", "nvimtree", "toggleterm" } function load_configs(category, configs) for _, config in ipairs(configs) do pcall(require, "configs." .. category .. "." .. config) end end load_configs("theming", theming_configs) load_configs("others", others_configs) load_configs("coding", coding_configs) load_configs("workflow", workflow_configs)
local CoreGui = game:GetService("CoreGui") local RunService = game:GetService("RunService") local CorePackages = game:GetService("CorePackages") local InGameMenuDependencies = require(CorePackages.InGameMenuDependencies) local Roact = InGameMenuDependencies.Roact local t = InGameMenuDependencies.t local UIBlox = InGameMenuDependencies.UIBlox local EducationalModal = UIBlox.App.Dialog.Modal.EducationalModal local withStyle = UIBlox.Core.Style.withStyle local EducationalPopupDialog = Roact.PureComponent:extend("EducationalPopupDialog") EducationalPopupDialog.validateProps = t.strictInterface({ bodyContents = t.array(t.strictInterface({ icon = t.union(t.string, t.table), text = t.string, layoutOrder = t.integer, isSystemMenuIcon = t.optional(t.boolean), })), cancelText = t.string, confirmText = t.string, titleText = t.string, titleBackgroundImageProps = t.strictInterface({ image = t.string, imageHeight = t.number, }), screenSize = t.Vector2, onDismiss = t.callback, onCancel = t.callback, onConfirm = t.callback, blurBackground = t.boolean, visible = t.boolean, }) EducationalPopupDialog.defaultProps = { blurBackground = false, } function EducationalPopupDialog:render() return withStyle(function(style) return Roact.createElement(Roact.Portal, { target = CoreGui, }, { InGameMenuEducationalPopupDialog = Roact.createElement("ScreenGui", { IgnoreGuiInset = true, OnTopOfCoreBlur = self.props.blurBackground, Enabled = self.props.visible, ZIndexBehavior = Enum.ZIndexBehavior.Sibling, }, { Overlay = Roact.createElement("TextButton", { AutoButtonColor = false, BackgroundColor3 = style.Theme.Overlay.Color, BackgroundTransparency = style.Theme.Overlay.Transparency, BorderSizePixel = 0, Size = UDim2.fromScale(1, 1), Text = "", }), Popup = Roact.createElement(EducationalModal, { bodyContents = self.props.bodyContents, cancelText = self.props.cancelText, confirmText = self.props.confirmText, titleText = self.props.titleText, titleBackgroundImageProps = self.props.titleBackgroundImageProps, screenSize = self.props.screenSize, onDismiss = self.props.onDismiss, onCancel = self.props.onCancel, onConfirm = self.props.onConfirm, }) }) }) end) end function EducationalPopupDialog:updateBlur() local shouldBlur = self.props.blurBackground and self.props.visible RunService:SetRobloxGuiFocused(shouldBlur) end function EducationalPopupDialog:didMount() self:updateBlur() end function EducationalPopupDialog:didUpdate() self:updateBlur() end function EducationalPopupDialog:willUnmount() if self.props.blurBackground then RunService:SetRobloxGuiFocused(false) end end return EducationalPopupDialog
---@class EquipOwn_Change local EquipOwn_Change = DClass("EquipOwn_Change", BaseComponent) _G.EquipOwn_Change = EquipOwn_Change function EquipOwn_Change:ctor() self.messager = Messager.new(self) end function EquipOwn_Change:addListener() self.messager:addListener(Msg.EQUIP_UPDATE_SHOWEQUIPS, self.updateShowList) end function EquipOwn_Change:onDispose() self.messager:dispose() end function EquipOwn_Change:onStart() self:addListener() self:onInit() end function EquipOwn_Change:onInit() self.cpn_Place = self:createComponent(self.nodes.nodePlace, EquipOwn_ChangePlace) self:addEventHandler(self.nodes.btnSelectSuit.onClick, self.onBtnSelectSuitClick) self:addEventHandler(self.nodes.btnPlace.onClick, self.onBtnPlaceClick) self:addEventHandler(self.nodes.btnSuit.onClick, self.onBtnSuitClick) self:addEventHandler(self.nodes.btnSortPlace.onClick, self.onBtnSortClick) self:addEventHandler(self.nodes.btnEquipSuit.onClick, self.onEquipSuitClick) self:addEventHandler(self.nodes.btnCloseTopViews.onClick, self.onCloseTopView) self:onInitUI() end function EquipOwn_Change:onOpen() self.cpn_Place:onInitUI() end ---打开套装筛选 function EquipOwn_Change:onBtnSelectSuitClick() MsgCenter.sendMessage(Msg.EQUIP_OPEN_SELECTSUIT, self.suitId) end EquipOwn_Change.sortList = {Lang(51030004), Lang(51030042)}--"星级" "等级" function EquipOwn_Change:onInitUI() self:updateShowList(0) self.curSelectSort = self.sortList[1] self:onSortPlaceChange() self.nodes.btnCloseTopViews.gameObject:SetActive(false) self:onCloseTopView() self.showPlaceState = false self:showPlaceNode(true) end function EquipOwn_Change:updateShowList(suit) if self.suitId == suit then return else self.suitId = suit end local txt_CurSuit = self.nodes.btnSelectSuit.transform:Find("Text"):GetComponent(typeof(Text)) local img_Icon = self.nodes.btnSelectSuit.transform:Find("Image_Icon"):GetComponent(typeof(Image)) local config = Config.EquipSuit[suit] if config then txt_CurSuit.text = config.suit else txt_CurSuit.text = Lang(GL_EquipOwnChangeSuitPopup_SuoYou)--"所有" end end function EquipOwn_Change:showPlaceNode(showPlace) if self.showPlaceState == showPlace then return end self.showPlaceState = showPlace self.nodes.btnPlace.transform:Find("Image").gameObject:SetActive(showPlace) self.nodes.btnSuit.transform:Find("Image").gameObject:SetActive(not showPlace) self.nodes.nodePlace:SetActive(showPlace) if showPlace then self.cpn_Place:onInitUI() else --self.cpn_Suit:onInitUI() end end function EquipOwn_Change:onBtnPlaceClick() self:showPlaceNode(true) end function EquipOwn_Change:onBtnSuitClick() self:showPlaceNode(false) end function EquipOwn_Change:onBtnSortClick() if self.nodes.viewSortPlace.gameObject.activeSelf then self:onCloseTopView() end self.nodes.btnCloseTopViews.gameObject:SetActive(true) self:showSortPlaceView() end function EquipOwn_Change:onEquipSuitClick() if self.nodes.viewEquipSuit.gameObject.activeSelf then self:onCloseTopView() end self.nodes.btnCloseTopViews.gameObject:SetActive(true) self:showEquipSuitView() end function EquipOwn_Change:onCloseTopView() self.nodes.viewSortPlace.scrollRect.gameObject:SetActive(false) self.nodes.viewEquipSuit.scrollRect.gameObject:SetActive(false) self.nodes.btnCloseTopViews.gameObject:SetActive(false) end ---展示 位置页签内排序 function EquipOwn_Change:showSortPlaceView() self.nodes.viewSortPlace.scrollRect.gameObject:SetActive(true) self.listSortItem = {} self.nodes.viewSortPlace:InitPool( #self.sortList, function(index, obj) local str = self.sortList[index] local btn = obj:GetComponent(typeof(Button)) local txt = obj.transform:Find("Text"):GetComponent(typeof(Text)) local select = obj.transform:Find("Image_Select") txt.text = str select.gameObject:SetActive(str == self.curSelectSort) local data = {} data.key = str data.select = select self:addEventHandler( btn.onClick, function() for index, value in ipairs(self.listSortItem) do local check = value.key == data.key value.select.gameObject:SetActive(check) if check and self.curSelectSort ~= value.key then self.curSelectSort = value.key self:onSortPlaceChange() end end self:onCloseTopView() end ) table.insert(self.listSortItem, data) end ) end ---排序规则刷新 function EquipOwn_Change:onSortPlaceChange() local txt = self.nodes.btnSortPlace.transform:Find("Text"):GetComponent(typeof(Text)) txt.text = self.curSelectSort MsgCenter.sendMessage(Msg.EQUIP_CHANGEPLACE_SORT, self.curSelectSort) end ---展示 更换套装 function EquipOwn_Change:showEquipSuitView() self.nodes.viewEquipSuit.scrollRect.gameObject:SetActive(true) self.listSuitItem = {} local sortList = {} self.nodes.viewEquipSuit:InitPool( #sortList, function(index, obj) local str = sortList[index] local btn = obj:GetComponent(typeof(Button)) local txt = obj.transform:Find("Text"):GetComponent(typeof(Text)) local select = obj.transform:Find("Image_Select") txt.text = str select.gameObject:SetActive(str == self.curSelectSuit) local data = {} data.key = str data.select = select self:addEventHandler( btn.onClick, function() for index, value in ipairs(self.listSuitItem) do local check = value.key == data.key value.select.gameObject:SetActive(check) if check and self.curSelectSuit ~= value.key then self.curSelectSuit = value.key self:onSuitChange() end end self:onCloseTopView() end ) table.insert(self.listSuitItem, data) end ) end ---排序规则刷新 function EquipOwn_Change:onSuitChange() local txt = self.nodes.btnEquipSuit.transform:Find("Text"):GetComponent(typeof(Text)) txt.text = self.curSelectSuit end
local namespace = require('namespace') local ComponentRemovedEv = namespace.class("ComponentRemovedEv") function ComponentRemovedEv:initialize(entity, componentName) self.entity = entity self.componentName = componentName end return ComponentRemovedEv
include('shared.lua') local function Include(e2, directives, includes, scripts) if scripts[e2] then return end local code = file.Read("expression2/" .. e2 .. ".txt") -- removed CLIENT as this is client file -- local code -- if CLIENT the code = file.Read("expression2/" .. e2 .. ".txt") if not code then return false, "Could not find include '" .. e2 .. ".txt'" end local status, err, buffer = PreProcessor.Execute(code, directives) if not status then return "include '" .. e2 .. "' -> " .. err end local status, tokens = Tokenizer.Execute(buffer) if not status then return "include '" .. e2 .. "' -> " .. tokens end local status, tree, dvars, files = Parser.Execute(tokens) if not status then return "include '" .. e2 .. "' -> " .. tree end includes[e2] = code scripts[e2] = { tree } for i = 1, #files do local error = Include(files[i], directives, includes, scripts) if error then return error end end end function wire_expression2_validate(buffer) -- removed CLIENT as this is client file -- if CLIENT and if not e2_function_data_received then return "Loading extensions. Please try again in a few seconds..." end -- invoke preprocessor local status, directives, buffer = PreProcessor.Execute(buffer) if not status then return directives end -- decompose directives local inports, outports, persists = directives.inputs, directives.outputs, directives.persist -- removed CLIENT as this is client file -- if CLIENT then RunConsoleCommand("wire_expression2_scriptmodel", directives.model or "") -- end -- invoke tokenizer (=lexer) local status, tokens = Tokenizer.Execute(buffer) if not status then return tokens end -- invoke parser local status, tree, dvars, files = Parser.Execute(tokens) if not status then return tree end -- prepare includes local includes, scripts = {}, {} for i = 1, #files do local error = Include(files[i], directives, includes, scripts) if error then return error end end -- invoke compiler local status, script, instance = Compiler.Execute(tree, inports[3], outports[3], persists[3], dvars, scripts) if not status then return script end return nil, includes end -- string.GetTextSize shits itself if the string is both wide and tall, -- so we have to explode it around \n and add the sizes together -- since it works fine for strings that are wide but not tall local function wtfgarry( str ) local w, h = 0, 0 local expl = string.Explode( "\n", str ) for i=1,#expl do local _w, _h = surface.GetTextSize( expl[i] ) w = math.max(w,_w) h = h + _h end return w, h end local h_of_lower = 100 -- height of the lower section (the prfbench/percent bar section) function ENT:GetWorldTipBodySize() local data = self:GetOverlayData() if not data then return 100, 20 end local w_total,h_total = wtfgarry( data.txt ) h_total = h_total + 18 local prfbench = data.prfbench local prfcount = data.prfcount local timebench = data.timebench local e2_hardquota = GetConVar("wire_expression2_quotahard"):GetInt() local e2_softquota = GetConVar("wire_expression2_quotasoft"):GetInt() -- ops text local hardtext = (prfcount / e2_hardquota > 0.33) and "(+" .. tostring(math.Round(prfcount / e2_hardquota * 100)) .. "%)" or "" local str = string.format("%i ops, %i%% %s", prfbench, prfbench / e2_softquota * 100, hardtext) h_of_lower = 0 local w,h = surface.GetTextSize( str ) w_total = math.max(w_total,w) h_total = h_total + h + 18 h_of_lower = h_of_lower + h + 18 -- cpu time text local str = string.format("cpu time: %ius", timebench*1000000) local w,h = surface.GetTextSize( str ) w_total = math.max(w_total,w) h_total = h_total + h + 20 h_of_lower = h_of_lower + h + 20 + 18 return w_total, math.min(h_total,ScrH() - (h_of_lower + 32*2)) end function ENT:DrawWorldTipBody( pos ) local data = self:GetOverlayData() if not data then return end local txt = data.txt local err = data.error -- this isn't used (yet), might do something with it later local white = Color(255,255,255,255) local black = Color(0,0,0,255) local w_total, yoffset = 0, pos.min.y ------------------- -- Name ------------------- local w,h = wtfgarry( txt ) h = h + pos.edgesize h = math.min(h,pos.size.h - (h_of_lower+pos.footersize.h)) render.SetScissorRect( pos.min.x + 16, pos.min.y, pos.max.x - 16, pos.min.y + h, true ) draw.DrawText( txt, "GModWorldtip", pos.min.x + pos.size.w/2, yoffset + 9, white, TEXT_ALIGN_CENTER ) render.SetScissorRect( 0, 0, ScrW(), ScrH(), false ) w_total = math.max( w_total, w ) yoffset = yoffset + h surface.SetDrawColor( black ) surface.DrawLine( pos.min.x, yoffset, pos.max.x, yoffset ) ------------------- -- prfcount/benchmarking/etc ------------------- local prfbench = data.prfbench local prfcount = data.prfcount local timebench = data.timebench local e2_hardquota = GetConVar("wire_expression2_quotahard"):GetInt() local e2_softquota = GetConVar("wire_expression2_quotasoft"):GetInt() -- fancy percent bar local w = pos.size.w - pos.edgesize * 2 -- ops text local hardtext = (prfcount / e2_hardquota > 0.33) and "(+" .. tostring(math.Round(prfcount / e2_hardquota * 100)) .. "%)" or "" local str = string.format("%i ops, %i%% %s", prfbench, prfbench / e2_softquota * 100, hardtext) draw.DrawText( str, "GModWorldtip", pos.min.x + pos.size.w/2, yoffset + 9, white, TEXT_ALIGN_CENTER ) local _,h = surface.GetTextSize( str ) yoffset = yoffset + h + pos.edgesize -- fancy percent bar local softquota_width = w * 0.7 local quota_width = softquota_width * math.min(prfbench/e2_softquota,1) + (w - softquota_width + 1) * (prfcount/e2_hardquota) local y = yoffset surface.SetDrawColor( Color(0,170,0,255) ) surface.DrawRect( pos.min.x + pos.edgesize, y, softquota_width, 20 ) surface.SetDrawColor( Color(170,0,0,255) ) surface.DrawRect( pos.min.x + pos.edgesize + softquota_width - 1, y, w - softquota_width + 2, 20 ) surface.SetDrawColor( Color(0,0,0,200) ) surface.DrawRect( pos.min.x + pos.edgesize, y, quota_width, 20 ) surface.SetDrawColor( black ) surface.DrawLine( pos.min.x + pos.edgesize, y, pos.min.x + pos.edgesize + w, y ) surface.DrawLine( pos.min.x + pos.edgesize + w, y, pos.min.x + pos.edgesize + w, y + 20 ) surface.DrawLine( pos.min.x + pos.edgesize + w, y + 20, pos.min.x + pos.edgesize, y + 20 ) surface.DrawLine( pos.min.x + pos.edgesize, y + 20, pos.min.x + pos.edgesize, y ) yoffset = yoffset + 20 -- cpu time text local str = string.format("cpu time: %ius", timebench*1000000) draw.DrawText( str, "GModWorldtip", pos.min.x + pos.size.w/2, yoffset + 9, white, TEXT_ALIGN_CENTER ) end
return function() hs.osascript.applescript([[ if application "Terminal" is running then tell application "Terminal" do script "" activate end tell else tell application "Terminal" activate end tell end if ]]) end
-- pacman -S clangd require('lspconfig').clangd.setup{}
-- Export everything from legends mode --[====[ exportlegends ============= Controls legends mode to export data - especially useful to set-and-forget large worlds, or when you want a map of every site when there are several hundred. The 'info' option exports more data than is possible in vanilla, to a :file:`region-date-legends_plus.xml` file developed to extend :forums:`World Viewer <128932>` and other legends utilities. Options: :info: Exports the world/gen info, the legends XML, and a custom XML with more information :custom: Exports a custom XML with more information :sites: Exports all available site maps :maps: Exports all seventeen detailed maps :all: Equivalent to calling all of the above, in that order ]====] --luacheck-flags: strictsubtype local gui = require 'gui' local script = require 'gui.script' local args = {...} local vs = dfhack.gui.getCurViewscreen() local MAPS = { "Standard biome+site map", "Elevations including lake and ocean floors", "Elevations respecting water level", "Biome", "Hydrosphere", "Temperature", "Rainfall", "Drainage", "Savagery", "Volcanism", "Current vegetation", "Evil", "Salinity", "Structures/fields/roads/etc.", "Trade", "Nobility and Holdings", "Diplomacy", } function getItemSubTypeName(itemType, subType) if (dfhack.items.getSubtypeCount(itemType)) <= 0 then return tostring(-1) end local subtypename = dfhack.items.getSubtypeDef(itemType, subType) if (subtypename == nil) then return tostring(-1) else return escape_xml(tostring(subtypename.name):lower()) end end function table_contains(self, element) for _, value in pairs(self) do if value == element then return true end end return false end function table_containskey(self, key) for value, _ in pairs(self) do if value == key then return true end end return false end function escape_xml(str) return str:gsub('&', '&amp;'):gsub('<', '&lt;'):gsub('>', '&gt;') end --luacheck: skip function progress_ipairs(vector, desc, interval) desc = desc or 'item' interval = interval or 10000 local cb = ipairs(vector) return function(vector, k, ...) if k and #vector >= interval and (k % interval == 0 or k == #vector - 1) then print((' %s %i/%i (%0.f%%)'):format(desc, k, #vector, k * 100 / #vector)) end return cb(vector, k) end, vector, nil end -- wrapper that returns "unknown N" for df.enum_type[BAD_VALUE], -- instead of returning nil or causing an error local df_enums = {} --as:df setmetatable(df_enums, { __index = function(self, enum) if not df[enum] or df[enum]._kind ~= 'enum-type' then error('invalid enum: ' .. enum) end local t = {} setmetatable(t, { __index = function(self, k) return df[enum][k] or 'unknown ' .. k end }) return t end, __newindex = function() error('read-only') end }) --create an extra legends xml with extra data, by Mason11987 for World Viewer function export_more_legends_xml() local month = dfhack.world.ReadCurrentMonth() + 1 --days and months are 1-indexed local day = dfhack.world.ReadCurrentDay() local year_str = string.format('%0'..math.max(5, string.len(''..df.global.cur_year))..'d', df.global.cur_year) local date_str = year_str..string.format('-%02d-%02d', month, day) local problem_elements = {} local filename = df.global.world.cur_savegame.save_dir.."-"..date_str.."-legends_plus.xml" local file = io.open(filename, 'w') if not file then qerror("could not open file: " .. filename) end file:write("<?xml version=\"1.0\" encoding='UTF-8'?>\n") file:write("<df_world>\n") file:write("<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name))).."</name>\n") file:write("<altname>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(df.global.world.world_data.name,1))).."</altname>\n") file:write("<landmasses>\n") for landmassK, landmassV in progress_ipairs(df.global.world.world_data.landmasses, 'landmass') do file:write("\t<landmass>\n") file:write("\t\t<id>"..landmassV.index.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(landmassV.name,1))).."</name>\n") file:write("\t\t<coord_1>"..landmassV.min_x..","..landmassV.min_y.."</coord_1>\n") file:write("\t\t<coord_2>"..landmassV.max_x..","..landmassV.max_y.."</coord_2>\n") file:write("\t</landmass>\n") end file:write("</landmasses>\n") file:write("<mountain_peaks>\n") for mountainK, mountainV in progress_ipairs(df.global.world.world_data.mountain_peaks, 'mountain') do file:write("\t<mountain_peak>\n") file:write("\t\t<id>"..mountainK.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(mountainV.name,1))).."</name>\n") file:write("\t\t<coords>"..mountainV.pos.x..","..mountainV.pos.y.."</coords>\n") file:write("\t\t<height>"..mountainV.height.."</height>\n") file:write("\t\t<is_volcano>"..tostring(mountainV.flags.is_volcano).."</is_volcano>\n") file:write("\t</mountain_peak>\n") end file:write("</mountain_peaks>\n") file:write("<regions>\n") for regionK, regionV in progress_ipairs(df.global.world.world_data.regions, 'region') do file:write("\t<region>\n") file:write("\t\t<id>"..regionV.index.."</id>\n") file:write("\t\t<coords>") for xK, xVal in ipairs(regionV.region_coords.x) do file:write(xVal..","..regionV.region_coords.y[xK].."|") end file:write("</coords>\n") local evilness = "neutral" if regionV.evil then evilness = "evil" elseif regionV.good then evilness = "good" end file:write("\t\t<evilness>"..evilness.."</evilness>\n") for forceK, forceVal in ipairs(regionV.forces) do file:write("\t\t<force_id>"..forceVal.."</force_id>\n") end file:write("\t</region>\n") end file:write("</regions>\n") file:write("<underground_regions>\n") for regionK, regionV in progress_ipairs(df.global.world.world_data.underground_regions, 'underground region') do file:write("\t<underground_region>\n") file:write("\t\t<id>"..regionV.index.."</id>\n") file:write("\t\t<coords>") for xK, xVal in ipairs(regionV.region_coords.x) do file:write(xVal..","..regionV.region_coords.y[xK].."|") end file:write("</coords>\n") file:write("\t</underground_region>\n") end file:write("</underground_regions>\n") file:write("<rivers>\n") for riverK, riverV in progress_ipairs(df.global.world.world_data.rivers, 'river') do file:write("\t<river>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(riverV.name, 1))).."</name>\n") file:write("\t\t<path>") for pathK, pathV in progress_ipairs(riverV.path.x, 'river section') do file:write(pathV..","..riverV.path.y[pathK]..",") file:write(riverV.flow[pathK]..",") file:write(riverV.exit_tile[pathK]..",") file:write(riverV.elevation[pathK].."|") end file:write("</path>\n") file:write("\t\t<end_pos>"..riverV.end_pos.x..","..riverV.end_pos.y.."</end_pos>\n") file:write("\t</river>\n") end file:write("</rivers>\n") file:write("<creature_raw>\n") for creatureK, creatureV in ipairs (df.global.world.raws.creatures.all) do file:write("\t<creature>\n") file:write("\t\t<creature_id>"..creatureV.creature_id.."</creature_id>\n") file:write("\t\t<name_singular>"..escape_xml(dfhack.df2utf(creatureV.name[0])).."</name_singular>\n") file:write("\t\t<name_plural>"..escape_xml(dfhack.df2utf(creatureV.name[1])).."</name_plural>\n") for flagK, flagV in ipairs (df.creature_raw_flags) do file:write("\t\t<"..flagV:lower()..">"..tostring(creatureV.flags[flagV]).."</"..flagV:lower()..">\n") end file:write("\t</creature>\n") end file:write("</creature_raw>\n") file:write("<sites>\n") for siteK, siteV in progress_ipairs(df.global.world.world_data.sites, 'site') do file:write("\t<site>\n") for k,v in pairs(siteV) do if (k == "id" or k == "civ_id" or k == "cur_owner_id") then file:write("\t\t<"..k..">"..tostring(v).."</"..k..">\n") elseif (k == "buildings") then if (#siteV.buildings > 0) then file:write("\t\t<structures>\n") for buildingK, buildingV in ipairs(siteV.buildings) do file:write("\t\t\t<structure>\n") file:write("\t\t\t\t<id>"..buildingV.id.."</id>\n") file:write("\t\t\t\t<type>"..df_enums.abstract_building_type[buildingV:getType()]:lower().."</type>\n") if table_containskey(buildingV,"name") then file:write("\t\t\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(buildingV.name, 1))).."</name>\n") file:write("\t\t\t\t<name2>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(buildingV.name))).."</name2>\n") end if df.abstract_building_templest:is_instance(buildingV) then file:write("\t\t\t\t<deity_type>"..buildingV.deity_type.."</deity_type>\n") if buildingV.deity_type == df.temple_deity_type.Deity then file:write("\t\t\t\t<deity>"..buildingV.deity_data.Deity.."</deity>\n") elseif buildingV.deity_type == df.temple_deity_type.Religion then file:write("\t\t\t\t<religion>"..buildingV.deity_data.Religion.."</religion>\n") end end if df.abstract_building_dungeonst:is_instance(buildingV) then file:write("\t\t\t\t<dungeon_type>"..buildingV.dungeon_type.."</dungeon_type>\n") end for inhabitabntK,inhabitabntV in pairs(buildingV.inhabitants) do file:write("\t\t\t\t<inhabitant>"..inhabitabntV.histfig_id.."</inhabitant>\n") end file:write("\t\t\t</structure>\n") end file:write("\t\t</structures>\n") end end end file:write("\t</site>\n") end file:write("</sites>\n") file:write("<world_constructions>\n") for wcK, wcV in progress_ipairs(df.global.world.world_data.constructions.list, 'construction') do file:write("\t<world_construction>\n") file:write("\t\t<id>"..wcV.id.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(wcV.name,1))).."</name>\n") file:write("\t\t<type>"..(df_enums.world_construction_type[wcV:getType()]):lower().."</type>\n") file:write("\t\t<coords>") for xK, xVal in ipairs(wcV.square_pos.x) do file:write(xVal..","..wcV.square_pos.y[xK].."|") end file:write("</coords>\n") file:write("\t</world_construction>\n") end file:write("</world_constructions>\n") file:write("<artifacts>\n") for artifactK, artifactV in progress_ipairs(df.global.world.artifacts.all, 'artifact') do file:write("\t<artifact>\n") file:write("\t\t<id>"..artifactV.id.."</id>\n") local item = artifactV.item if df.item_constructed:is_instance(item) then file:write("\t\t<item_type>"..tostring(df_enums.item_type[item:getType()]):lower().."</item_type>\n") if (item:getSubtype() ~= -1) then --luacheck: skip file:write("\t\t<item_subtype>"..escape_xml(dfhack.df2utf(item.subtype.name)).."</item_subtype>\n") end for improvementK,impovementV in pairs(item.improvements) do if df.itemimprovement_writingst:is_instance(impovementV) then for writingk,writingV in pairs(impovementV.contents) do file:write("\t\t<writing>"..writingV.."</writing>\n") end elseif df.itemimprovement_pagesst:is_instance(impovementV) then file:write("\t\t<page_count>"..impovementV.count.."</page_count>\n") for writingk,writingV in pairs(impovementV.contents) do file:write("\t\t<writing>"..writingV.."</writing>\n") end end end end if (table_containskey(item,"description")) then file:write("\t\t<item_description>"..dfhack.df2utf(item.description:lower()).."</item_description>\n") end if item:getMaterial() ~= -1 then file:write("\t\t<mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(item:getMaterial(), item:getMaterialIndex()))).."</mat>\n") end file:write("\t</artifact>\n") end file:write("</artifacts>\n") file:write("<historical_figures>\n") for hfK, hfV in progress_ipairs(df.global.world.history.figures, 'historical figure') do file:write("\t<historical_figure>\n") file:write("\t\t<id>"..hfV.id.."</id>\n") file:write("\t\t<sex>"..hfV.sex.."</sex>\n") if hfV.race >= 0 then file:write("\t\t<race>"..escape_xml(dfhack.df2utf(df.creature_raw.find(hfV.race).name[0])).."</race>\n") end file:write("\t</historical_figure>\n") end file:write("</historical_figures>\n") file:write("<identities>\n") for idK, idV in progress_ipairs(df.global.world.identities.all, 'identity') do file:write("\t<identity>\n") file:write("\t\t<id>"..idV.id.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(idV.name,1))).."</name>\n") local id_tag = df.identity_type.attrs[idV.type].id_tag if id_tag then file:write("\t\t<"..id_tag..">"..idV[id_tag].."</"..id_tag..">\n") else dfhack.printerr ("Unknown df.identity_type value encountered: "..tostring(idV.type)..". Please report to DFHack team.") end if idV.race >= 0 then file:write("\t\t<race>"..(df.global.world.raws.creatures.all[idV.race].creature_id):lower().."</race>\n") end if idV.race >= 0 and idV.caste >= 0 then file:write("\t\t<caste>"..(df.global.world.raws.creatures.all[idV.race].caste[idV.caste].caste_id):lower().."</caste>\n") end file:write("\t\t<birth_year>"..idV.birth_year.."</birth_year>\n") file:write("\t\t<birth_second>"..idV.birth_year.."</birth_second>\n") if idV.profession >= 0 then file:write("\t\t<profession>"..(df_enums.profession[idV.profession]):lower().."</profession>\n") end file:write("\t\t<entity_id>"..idV.entity_id.."</entity_id>\n") file:write("\t</identity>\n") end file:write("</identities>\n") file:write("<entity_populations>\n") for entityPopK, entityPopV in progress_ipairs(df.global.world.entity_populations, 'entity population') do file:write("\t<entity_population>\n") file:write("\t\t<id>"..entityPopV.id.."</id>\n") for raceK, raceV in ipairs(entityPopV.races) do local raceName = (df.global.world.raws.creatures.all[raceV].creature_id):lower() file:write("\t\t<race>"..raceName..":"..entityPopV.counts[raceK].."</race>\n") end file:write("\t\t<civ_id>"..entityPopV.civ_id.."</civ_id>\n") file:write("\t</entity_population>\n") end file:write("</entity_populations>\n") file:write("<entities>\n") for entityK, entityV in progress_ipairs(df.global.world.entities.all, 'entity') do file:write("\t<entity>\n") file:write("\t\t<id>"..entityV.id.."</id>\n") if entityV.race >= 0 then file:write("\t\t<race>"..(df.global.world.raws.creatures.all[entityV.race].creature_id):lower().."</race>\n") end file:write("\t\t<type>"..(df_enums.historical_entity_type[entityV.type]):lower().."</type>\n") if entityV.type == df.historical_entity_type.Religion or entityV.type == df.historical_entity_type.MilitaryUnit then -- Get worshipped figures if (entityV.relations ~= nil and entityV.relations.deities ~= nil) then for k,v in pairs(entityV.relations.deities) do file:write("\t\t<worship_id>"..v.."</worship_id>\n") end end end if entityV.type == df.historical_entity_type.MilitaryUnit then -- Get favorite weapons if (entityV.resources ~= nil and entityV.resources.weapon_type ~= nil) then for weaponK,weaponID in pairs(entityV.resources.weapon_type) do file:write("\t\t<weapon>"..getItemSubTypeName(df.item_type.WEAPON, weaponID).."</weapon>\n") end end end if entityV.type == df.historical_entity_type.Guild then -- Get profession for professionK,professionV in pairs(entityV.guild_professions) do file:write("\t\t<profession>"..df_enums.profession[professionV.profession]:lower().."</profession>\n") end end for id, link in pairs(entityV.entity_links) do file:write("\t\t<entity_link>\n") for k, v in pairs(link) do if (k == "type") then file:write("\t\t\t<"..k..">"..tostring(df_enums.entity_entity_link_type[v]).."</"..k..">\n") else file:write("\t\t\t<"..k..">"..v.."</"..k..">\n") end end file:write("\t\t</entity_link>\n") end for positionK,positionV in pairs(entityV.positions.own) do file:write("\t\t<entity_position>\n") file:write("\t\t\t<id>"..positionV.id.."</id>\n") if positionV.name[0] ~= "" then file:write("\t\t\t<name>"..escape_xml(positionV.name[0]).."</name>\n") end if positionV.name_male[0] ~= "" then file:write("\t\t\t<name_male>"..escape_xml(positionV.name_male[0]).."</name_male>\n") end if positionV.name_female[0] ~= "" then file:write("\t\t\t<name_female>"..escape_xml(positionV.name_female[0]).."</name_female>\n") end if positionV.spouse[0] ~= "" then file:write("\t\t\t<spouse>"..positionV.spouse[0].."</spouse>\n") end if positionV.spouse_male[0] ~= "" then file:write("\t\t\t<spouse_male>"..positionV.spouse_male[0].."</spouse_male>\n") end if positionV.spouse_female[0] ~= "" then file:write("\t\t\t<spouse_female>"..positionV.spouse_female[0].."</spouse_female>\n") end file:write("\t\t</entity_position>\n") end for assignmentK,assignmentV in pairs(entityV.positions.assignments) do file:write("\t\t<entity_position_assignment>\n") for k, v in pairs(assignmentV) do if (k == "id" or k == "histfig" or k == "position_id" or k == "squad_id") then file:write("\t\t\t<"..k..">"..v.."</"..k..">\n") end end file:write("\t\t</entity_position_assignment>\n") end for idx,id in pairs(entityV.histfig_ids) do file:write("\t\t<histfig_id>"..id.."</histfig_id>\n") end for id, link in ipairs(entityV.children) do file:write("\t\t<child>"..link.."</child>\n") end if #entityV.claims.border.x > 0 then file:write("\t\t<claims>") for xK, xVal in ipairs(entityV.claims.border.x) do file:write(xVal..","..entityV.claims.border.y[xK].."|") end file:write("</claims>\n") end if (table_containskey(entityV,"occasion_info") and entityV.occasion_info ~= nil) then for occasionK, occasionV in pairs(entityV.occasion_info.occasions) do file:write("\t\t<occasion>\n") file:write("\t\t\t<id>"..occasionV.id.."</id>\n") file:write("\t\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(occasionV.name,1))).."</name>\n") file:write("\t\t\t<event>"..occasionV.event.."</event>\n") for scheduleK, scheduleV in pairs(occasionV.schedule) do file:write("\t\t\t<schedule>\n") file:write("\t\t\t\t<id>"..scheduleK.."</id>\n") file:write("\t\t\t\t<type>"..df_enums.occasion_schedule_type[scheduleV.type]:lower().."</type>\n") if(scheduleV.type == df.occasion_schedule_type.THROWING_COMPETITION) then file:write("\t\t\t\t<item_type>"..df_enums.item_type[scheduleV.reference]:lower().."</item_type>\n") file:write("\t\t\t\t<item_subtype>"..getItemSubTypeName(scheduleV.reference,scheduleV.reference2).."</item_subtype>\n") else file:write("\t\t\t\t<reference>"..scheduleV.reference.."</reference>\n") file:write("\t\t\t\t<reference2>"..scheduleV.reference2.."</reference2>\n") end for featureK, featureV in pairs(scheduleV.features) do file:write("\t\t\t\t<feature>\n") if(df_enums.occasion_schedule_feature[featureV.feature] ~= nil) then file:write("\t\t\t\t\t<type>"..df_enums.occasion_schedule_feature[featureV.feature]:lower().."</type>\n") else file:write("\t\t\t\t\t<type>"..featureV.feature.."</type>\n") end file:write("\t\t\t\t\t<reference>"..featureV.reference.."</reference>\n") file:write("\t\t\t\t</feature>\n") end file:write("\t\t\t</schedule>\n") end file:write("\t\t</occasion>\n") end end file:write("\t</entity>\n") end file:write("</entities>\n") file:write("<historical_events>\n") for ID, event in progress_ipairs(df.global.world.history.events, 'event') do if df.history_event_add_hf_entity_linkst:is_instance(event) or df.history_event_add_hf_site_linkst:is_instance(event) or df.history_event_add_hf_hf_linkst:is_instance(event) or df.history_event_add_hf_entity_linkst:is_instance(event) or df.history_event_topicagreement_concludedst:is_instance(event) or df.history_event_topicagreement_rejectedst:is_instance(event) or df.history_event_topicagreement_madest:is_instance(event) or df.history_event_body_abusedst:is_instance(event) or df.history_event_change_creature_typest:is_instance(event) or df.history_event_change_hf_jobst:is_instance(event) or df.history_event_change_hf_statest:is_instance(event) or df.history_event_created_buildingst:is_instance(event) or df.history_event_creature_devouredst:is_instance(event) or df.history_event_hf_does_interactionst:is_instance(event) or df.history_event_hf_learns_secretst:is_instance(event) or df.history_event_hist_figure_new_petst:is_instance(event) or df.history_event_hist_figure_reach_summitst:is_instance(event) or df.history_event_item_stolenst:is_instance(event) or df.history_event_remove_hf_entity_linkst:is_instance(event) or df.history_event_remove_hf_site_linkst:is_instance(event) or df.history_event_replaced_buildingst:is_instance(event) or df.history_event_masterpiece_created_arch_designst:is_instance(event) or df.history_event_masterpiece_created_dye_itemst:is_instance(event) or df.history_event_masterpiece_created_arch_constructst:is_instance(event) or df.history_event_masterpiece_created_itemst:is_instance(event) or df.history_event_masterpiece_created_item_improvementst:is_instance(event) or df.history_event_masterpiece_created_foodst:is_instance(event) or df.history_event_masterpiece_created_engravingst:is_instance(event) or df.history_event_masterpiece_lostst:is_instance(event) or df.history_event_entity_actionst:is_instance(event) or df.history_event_hf_act_on_buildingst:is_instance(event) or df.history_event_artifact_createdst:is_instance(event) or df.history_event_assume_identityst:is_instance(event) or df.history_event_create_entity_positionst:is_instance(event) or df.history_event_diplomat_lostst:is_instance(event) or df.history_event_merchantst:is_instance(event) or df.history_event_war_peace_acceptedst:is_instance(event) or df.history_event_war_peace_rejectedst:is_instance(event) or df.history_event_hist_figure_woundedst:is_instance(event) or df.history_event_hist_figure_diedst:is_instance(event) then file:write("\t<historical_event>\n") file:write("\t\t<id>"..event.id.."</id>\n") file:write("\t\t<type>"..tostring(df_enums.history_event_type[event:getType()]):lower().."</type>\n") for k,v in pairs(event) do if k == "year" or k == "seconds" or k == "flags" or k == "id" or (k == "region" and not df.history_event_hf_does_interactionst:is_instance(event)) or k == "region_pos" or k == "layer" or k == "feature_layer" or k == "subregion" or k == "anon_1" or k == "anon_2" or k == "flags2" or k == "unk1" then -- do notting for these keys elseif df.history_event_add_hf_entity_linkst:is_instance(event) and k == "link_type" then file:write("\t\t<"..k..">"..df_enums.histfig_entity_link_type[v]:lower().."</"..k..">\n") elseif df.history_event_add_hf_entity_linkst:is_instance(event) and k == "position_id" then local entity = df.historical_entity.find(event.civ) if (entity ~= nil and event.civ > -1 and v > -1) then for entitypositionsK, entityPositionsV in ipairs(entity.positions.own) do if entityPositionsV.id == v then file:write("\t\t<position>"..escape_xml(tostring(entityPositionsV.name[0]):lower()).."</position>\n") break end end else file:write("\t\t<position>-1</position>\n") end elseif df.history_event_create_entity_positionst:is_instance(event) and k == "position" then local entity = df.historical_entity.find(event.site_civ) if (entity ~= nil and v > -1) then for entitypositionsK, entityPositionsV in ipairs(entity.positions.own) do if entityPositionsV.id == v then file:write("\t\t<position>"..escape_xml(tostring(entityPositionsV.name[0]):lower()).."</position>\n") break end end else file:write("\t\t<position>-1</position>\n") end elseif df.history_event_remove_hf_entity_linkst:is_instance(event) and k == "link_type" then file:write("\t\t<"..k..">"..df_enums.histfig_entity_link_type[v]:lower().."</"..k..">\n") elseif df.history_event_remove_hf_entity_linkst:is_instance(event) and k == "position_id" then local entity = df.historical_entity.find(event.civ) if (entity ~= nil and event.civ > -1 and v > -1) then for entitypositionsK, entityPositionsV in ipairs(entity.positions.own) do if entityPositionsV.id == v then file:write("\t\t<position>"..escape_xml(tostring(entityPositionsV.name[0]):lower()).."</position>\n") break end end else file:write("\t\t<position>-1</position>\n") end elseif df.history_event_add_hf_hf_linkst:is_instance(event) and k == "type" then file:write("\t\t<link_type>"..df_enums.histfig_hf_link_type[v]:lower().."</link_type>\n") elseif df.history_event_add_hf_site_linkst:is_instance(event) and k == "type" then file:write("\t\t<link_type>"..df_enums.histfig_site_link_type[v]:lower().."</link_type>\n") elseif df.history_event_remove_hf_site_linkst:is_instance(event) and k == "type" then file:write("\t\t<link_type>"..df_enums.histfig_site_link_type[v]:lower().."</link_type>\n") elseif (df.history_event_item_stolenst:is_instance(event) or df.history_event_masterpiece_created_itemst:is_instance(event) or df.history_event_masterpiece_created_item_improvementst:is_instance(event) or df.history_event_masterpiece_created_dye_itemst:is_instance(event) ) and k == "item_type" then file:write("\t\t<item_type>"..df_enums.item_type[v]:lower().."</item_type>\n") elseif (df.history_event_item_stolenst:is_instance(event) or df.history_event_masterpiece_created_itemst:is_instance(event) or df.history_event_masterpiece_created_item_improvementst:is_instance(event) or df.history_event_masterpiece_created_dye_itemst:is_instance(event) ) and k == "item_subtype" then if event.item_type > -1 and v > -1 then file:write("\t\t<"..k..">"..getItemSubTypeName(event.item_type,v).."</"..k..">\n") end elseif df.history_event_masterpiece_created_foodst:is_instance(event) and k == "item_subtype" then --if event.item_type > -1 and v > -1 then file:write("\t\t<item_type>food</item_type>\n") file:write("\t\t<"..k..">"..getItemSubTypeName(df.item_type.FOOD,v).."</"..k..">\n") --end elseif df.history_event_item_stolenst:is_instance(event) and k == "mattype" then if (v > -1) then if (dfhack.matinfo.decode(event.mattype, event.matindex) == nil) then file:write("\t\t<mattype>"..event.mattype.."</mattype>\n") file:write("\t\t<matindex>"..event.matindex.."</matindex>\n") else file:write("\t\t<mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.mattype, event.matindex))).."</mat>\n") end end elseif (df.history_event_artifact_possessedst:is_instance(event) or df.history_event_poetic_form_createdst:is_instance(event) or df.history_event_musical_form_createdst:is_instance(event) or df.history_event_dance_form_createdst:is_instance(event) or df.history_event_written_content_composedst:is_instance(event) or df.history_event_artifact_claim_formedst:is_instance(event) or df.history_event_artifact_givenst:is_instance(event) or df.history_event_entity_dissolvedst:is_instance(event) or df.history_event_item_stolenst:is_instance(event) or df.history_event_artifact_createdst:is_instance(event)) and k == "circumstance" then file:write("\t\t<circumstance>\n") file:write("\t\t\t<type>"..event.circumstance.type.."</type>\n") if event.circumstance.type == df.unit_thought_type.Death then file:write("\t\t\t<death>"..event.circumstance.data.Death.."</death>\n") elseif event.circumstance.type == df.unit_thought_type.Prayer then file:write("\t\t\t<prayer>"..event.circumstance.data.Prayer.."</prayer>\n") elseif event.circumstance.type == df.unit_thought_type.DreamAbout then file:write("\t\t\t<dream_about>"..event.circumstance.data.DreamAbout.."</dream_about>\n") elseif event.circumstance.type == df.unit_thought_type.Defeated then file:write("\t\t\t<defeated>"..event.circumstance.data.Defeated.."</defeated>\n") elseif event.circumstance.type == df.unit_thought_type.Murdered then file:write("\t\t\t<murdered>"..event.circumstance.data.Murdered.."</murdered>\n") elseif event.circumstance.type == df.unit_thought_type.HistEventCollection then file:write("\t\t\t<hist_event_collection>"..event.circumstance.data.HistEventCollection.."</hist_event_collection>\n") end file:write("\t\t</circumstance>\n") elseif (df.history_event_artifact_possessedst:is_instance(event) or df.history_event_poetic_form_createdst:is_instance(event) or df.history_event_musical_form_createdst:is_instance(event) or df.history_event_dance_form_createdst:is_instance(event) or df.history_event_written_content_composedst:is_instance(event) or df.history_event_artifact_claim_formedst:is_instance(event) or df.history_event_artifact_givenst:is_instance(event) or df.history_event_entity_dissolvedst:is_instance(event) or df.history_event_item_stolenst:is_instance(event) or df.history_event_artifact_createdst:is_instance(event)) and k == "reason" then file:write("\t\t<reason>\n") file:write("\t\t\t<type>"..df.history_event_reason[event.reason.type].."</type>\n") if event.reason.type == df.history_event_reason.glorify_hf then file:write("\t\t\t<glorify_hf>"..event.reason.data.glorify_hf.."</glorify_hf>\n") elseif event.reason.type == df.history_event_reason.artifact_is_heirloom_of_family_hfid then file:write("\t\t\t<artifact_is_heirloom_of_family_hfid>"..event.reason.data.artifact_is_heirloom_of_family_hfid.."</artifact_is_heirloom_of_family_hfid>\n") elseif event.reason.type == df.history_event_reason.artifact_is_symbol_of_entity_position then file:write("\t\t\t<artifact_is_symbol_of_entity_position>"..event.reason.data.artifact_is_symbol_of_entity_position.."</artifact_is_symbol_of_entity_position>\n") end file:write("\t\t</reason>\n") elseif (df.history_event_masterpiece_created_itemst:is_instance(event) or df.history_event_masterpiece_created_item_improvementst:is_instance(event) or df.history_event_masterpiece_created_foodst:is_instance(event) or df.history_event_masterpiece_created_dye_itemst:is_instance(event) ) and k == "mat_type" then if (v > -1) then if (dfhack.matinfo.decode(event.mat_type, event.mat_index) == nil) then file:write("\t\t<mat_type>"..event.mat_type.."</mat_type>\n") file:write("\t\t<mat_index>"..event.mat_index.."</mat_index>\n") else file:write("\t\t<mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.mat_type, event.mat_index))).."</mat>\n") end end elseif df.history_event_masterpiece_created_item_improvementst:is_instance(event) and k == "imp_mat_type" then if (v > -1) then if (dfhack.matinfo.decode(event.imp_mat_type, event.imp_mat_index) == nil) then file:write("\t\t<imp_mat_type>"..event.imp_mat_type.."</imp_mat_type>\n") file:write("\t\t<imp_mat_index>"..event.imp_mat_index.."</imp_mat_index>\n") else file:write("\t\t<imp_mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.imp_mat_type, event.imp_mat_index))).."</imp_mat>\n") end end elseif df.history_event_masterpiece_created_dye_itemst:is_instance(event) and k == "dye_mat_type" then if (v > -1) then if (dfhack.matinfo.decode(event.dye_mat_type, event.dye_mat_index) == nil) then file:write("\t\t<dye_mat_type>"..event.dye_mat_type.."</dye_mat_type>\n") file:write("\t\t<dye_mat_index>"..event.dye_mat_index.."</dye_mat_index>\n") else file:write("\t\t<dye_mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.dye_mat_type, event.dye_mat_index))).."</dye_mat>\n") end end elseif df.history_event_item_stolenst:is_instance(event) and k == "matindex" then --skip elseif df.history_event_item_stolenst:is_instance(event) and k == "item" and v == -1 then --skip elseif (df.history_event_masterpiece_created_itemst:is_instance(event) or df.history_event_masterpiece_created_item_improvementst:is_instance(event) ) and k == "mat_index" then --skip elseif df.history_event_masterpiece_created_item_improvementst:is_instance(event) and k == "imp_mat_index" then --skip elseif (df.history_event_war_peace_acceptedst:is_instance(event) or df.history_event_war_peace_rejectedst:is_instance(event) or df.history_event_topicagreement_concludedst:is_instance(event) or df.history_event_topicagreement_rejectedst:is_instance(event) or df.history_event_topicagreement_madest:is_instance(event) ) and k == "topic" then file:write("\t\t<topic>"..tostring(df_enums.meeting_topic[v]):lower().."</topic>\n") elseif df.history_event_masterpiece_created_item_improvementst:is_instance(event) and k == "improvement_type" then file:write("\t\t<improvement_type>"..df_enums.improvement_type[v]:lower().."</improvement_type>\n") elseif ((df.history_event_hist_figure_reach_summitst:is_instance(event) and k == "group") or (df.history_event_hist_figure_new_petst:is_instance(event) and k == "group") or (df.history_event_body_abusedst:is_instance(event) and k == "bodies")) then for detailK,detailV in pairs(v) do file:write("\t\t<"..k..">"..detailV.."</"..k..">\n") end elseif df.history_event_hist_figure_new_petst:is_instance(event) and k == "pets" then for detailK,detailV in pairs(v) do file:write("\t\t<"..k..">"..escape_xml(dfhack.df2utf(df.creature_raw.find(detailV).name[0])).."</"..k..">\n") end elseif df.history_event_body_abusedst:is_instance(event) and (k == "abuse_data") then if event.abuse_type == df.history_event_body_abusedst.T_abuse_type.Impaled then file:write("\t\t<item_type>"..tostring(df_enums.item_type[event.abuse_data.Impaled.item_type]):lower().."</item_type>\n") file:write("\t\t<item_subtype>"..getItemSubTypeName(event.abuse_data.Impaled.item_type,event.abuse_data.Impaled.item_subtype).."</item_subtype>\n") if (event.abuse_data.Impaled.mat_type > -1) then if (dfhack.matinfo.decode(event.abuse_data.Impaled.mat_type, event.abuse_data.Impaled.mat_index) == nil) then file:write("\t\t<mat_type>"..event.abuse_data.Impaled.mat_type.."</mat_type>\n") file:write("\t\t<mat_index>"..event.abuse_data.Impaled.mat_index.."</mat_index>\n") else file:write("\t\t<item_mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.abuse_data.Impaled.mat_type, event.abuse_data.Impaled.mat_index))).."</item_mat>\n") end end elseif event.abuse_type == df.history_event_body_abusedst.T_abuse_type.Piled then file:write("\t\t<pile_type>"..df.history_event_body_abusedst.T_abuse_data.T_Piled.T_pile_type [event.abuse_data.Piled.pile_type].."</pile_type>\n") elseif event.abuse_type == df.history_event_body_abusedst.T_abuse_type.Flayed then file:write("\t\t<structure>"..tostring(event.abuse_data.Flayed.structure).."</structure>\n") elseif event.abuse_type == df.history_event_body_abusedst.T_abuse_type.Hung then file:write("\t\t<tree>"..tostring(event.abuse_data.Hung.tree).."</tree>\n") file:write("\t\t<mat_type>"..event.abuse_data.Hung.mat_type.."</mat_type>\n") file:write("\t\t<mat_index>"..event.abuse_data.Hung.mat_index.."</mat_index>\n") elseif event.abuse_type == df.history_event_body_abusedst.T_abuse_type.Mutilated then -- For completeness. No fields elseif event.abuse_type == df.history_event_body_abusedst.T_abuse_type.Animated then file:write("\t\t<interaction>"..tostring(event.abuse_data.Animated.interaction).."</interaction>\n") end elseif df.history_event_assume_identityst:is_instance(event) and k == "identity" then local identity = df.identity.find(v) if identity then if identity.type == df.identity_type.HidingCurse or identity.type == df.identity_type.Unk_1 or identity.type == df.identity_type.TrueName or identity.type == df.identity_type.Unk_4 or identity.type == df.identity_type.Identity then if identity.histfig_id ~= -1 then file:write("\t\t<identity_histfig_id>"..identity.histfig_id.."</identity_histfig_id>\n") end elseif identity.type == df.identity_type.FalseIdentity then if identity.nemesis_id ~= -1 then file:write("\t\t<identity_nemesis_id>"..identity.nemesis_id.."</identity_nemesis_id>\n") end else dfhack.printerr ("Unknown df.identity_type value encountered:"..tostring (identity.type)..". Please report to DFHack team.") end file:write("\t\t<identity_name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(identity.name))).."</identity_name>\n") local craw = df.creature_raw.find(identity.race) if craw then file:write("\t\t<identity_race>"..(craw.creature_id):lower().."</identity_race>\n") file:write("\t\t<identity_caste>"..(craw.caste[identity.caste].caste_id):lower().."</identity_caste>\n") end end elseif df.history_event_masterpiece_created_arch_constructst:is_instance(event) and k == "building_type" then file:write("\t\t<building_type>"..df_enums.building_type[v]:lower().."</building_type>\n") elseif df.history_event_masterpiece_created_arch_constructst:is_instance(event) and k == "building_subtype" then if (df_enums.building_type[event.building_type]:lower() == "furnace") then file:write("\t\t<building_subtype>"..df_enums.furnace_type[v]:lower().."</building_subtype>\n") elseif v > -1 then file:write("\t\t<building_subtype>"..tostring(v).."</building_subtype>\n") end elseif k == "race" then if v > -1 then file:write("\t\t<race>"..escape_xml(dfhack.df2utf(df.global.world.raws.creatures.all[v].name[0])).."</race>\n") end elseif k == "caste" then if v > -1 then file:write("\t\t<caste>"..(df.global.world.raws.creatures.all[event.race].caste[v].caste_id):lower().."</caste>\n") end elseif k == "interaction" and df.history_event_hf_does_interactionst:is_instance(event) then if #df.global.world.raws.interactions[v].sources > 0 then local str_1 = df.global.world.raws.interactions[v].sources[0].hist_string_1 if string.sub (str_1, 1, 1) == " " and string.sub (str_1, string.len (str_1), string.len (str_1)) == " " then str_1 = string.sub (str_1, 2, string.len (str_1) - 1) end file:write("\t\t<interaction_action>"..str_1..df.global.world.raws.interactions[v].sources[0].hist_string_2.."</interaction_action>\n") end elseif k == "interaction" and df.history_event_hf_learns_secretst:is_instance(event) then if #df.global.world.raws.interactions[v].sources > 0 then file:write("\t\t<secret_text>"..df.global.world.raws.interactions[v].sources[0].name.."</secret_text>\n") end elseif df.history_event_hist_figure_diedst:is_instance(event) and k == "weapon" then for detailK,detailV in pairs(v) do if (detailK == "item") then if detailV > -1 then file:write("\t\t<"..detailK..">"..detailV.."</"..detailK..">\n") local thisItem = df.item.find(detailV) if (thisItem ~= nil) then if (thisItem.flags.artifact == true) then for refk,refv in pairs(thisItem.general_refs) do if (df.general_ref_is_artifactst:is_instance(refv)) then file:write("\t\t<artifact_id>"..refv.artifact_id.."</artifact_id>\n") break end end end end end elseif (detailK == "item_type") then if event.weapon.item > -1 then file:write("\t\t<"..detailK..">"..tostring(df_enums.item_type[detailV]):lower().."</"..detailK..">\n") end elseif (detailK == "item_subtype") then if event.weapon.item > -1 and detailV > -1 then file:write("\t\t<"..detailK..">"..getItemSubTypeName(event.weapon.item_type,detailV).."</"..detailK..">\n") end elseif (detailK == "mattype") then if (detailV > -1) then file:write("\t\t<mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.weapon.mattype, event.weapon.matindex))).."</mat>\n") end elseif (detailK == "matindex") then elseif (detailK == "shooter_item") then if detailV > -1 then file:write("\t\t<"..detailK..">"..detailV.."</"..detailK..">\n") local thisItem = df.item.find(detailV) if thisItem ~= nil then if (thisItem.flags.artifact == true) then for refk,refv in pairs(thisItem.general_refs) do if (df.general_ref_is_artifactst:is_instance(refv)) then file:write("\t\t<shooter_artifact_id>"..refv.artifact_id.."</shooter_artifact_id>\n") break end end end end end elseif (detailK == "shooter_item_type") then if event.weapon.shooter_item > -1 then file:write("\t\t<"..detailK..">"..tostring(df_enums.item_type[detailV]):lower().."</"..detailK..">\n") end elseif (detailK == "shooter_item_subtype") then if event.weapon.shooter_item > -1 and detailV > -1 then file:write("\t\t<"..detailK..">"..getItemSubTypeName(event.weapon.shooter_item_type,detailV).."</"..detailK..">\n") end elseif (detailK == "shooter_mattype") then if (detailV > -1) then file:write("\t\t<shooter_mat>"..dfhack.df2utf(dfhack.matinfo.toString(dfhack.matinfo.decode(event.weapon.shooter_mattype, event.weapon.shooter_matindex))).."</shooter_mat>\n") end elseif (detailK == "shooter_matindex") then --skip elseif detailK == "slayer_race" or detailK == "slayer_caste" then --skip else file:write("\t\t<"..detailK..">"..detailV.."</"..detailK..">\n") end end elseif df.history_event_hist_figure_diedst:is_instance(event) and k == "death_cause" then file:write("\t\t<"..k..">"..df_enums.death_type[v]:lower().."</"..k..">\n") elseif df.history_event_change_hf_jobst:is_instance(event) and (k == "new_job" or k == "old_job") then file:write("\t\t<"..k..">"..df_enums.profession[v]:lower().."</"..k..">\n") elseif df.history_event_change_creature_typest:is_instance(event) and (k == "old_race" or k == "new_race") and v >= 0 then file:write("\t\t<"..k..">"..escape_xml(dfhack.df2utf(df.global.world.raws.creatures.all[v].name[0])).."</"..k..">\n") elseif tostring(v):find ("<") then if not problem_elements[tostring(event._type)] then problem_elements[tostring(event._type)] = {} end if not problem_elements[tostring(event._type)][k] then problem_elements [tostring(event._type)][k] = true end file:write("\t\t<"..k..">please report compound element for correction</"..k..">\n") else file:write("\t\t<"..k..">"..tostring(v).."</"..k..">\n") end end file:write("\t</historical_event>\n") end end file:write("</historical_events>\n") file:write("<historical_event_relationships>\n") for ID, set in progress_ipairs(df.global.world.history.relationship_events, 'relationship_event') do for k = 0, set.next_element - 1 do file:write("\t<historical_event_relationship>\n") file:write("\t\t<event>"..set.event[k].."</event>\n") file:write("\t\t<relationship>"..set.relationship[k].."</relationship>\n") file:write("\t\t<source_hf>"..set.source_hf[k].."</source_hf>\n") file:write("\t\t<target_hf>"..set.target_hf[k].."</target_hf>\n") file:write("\t\t<year>"..set.year[k].."</year>\n") file:write("\t</historical_event_relationship>\n") end end file:write("</historical_event_relationships>\n") file:write("<historical_event_relationship_supplements>\n") for ID, event in progress_ipairs(df.global.world.history.relationship_event_supplements, 'relationship_event_supplement') do file:write("\t<historical_event_relationship_supplement>\n") file:write("\t\t<event>"..event.event.."</event>\n") file:write("\t\t<occasion_type>"..event.occasion_type.."</occasion_type>\n") file:write("\t\t<site>"..event.site.."</site>\n") file:write("\t\t<unk_1>"..event.unk_1.."</unk_1>\n") file:write("\t</historical_event_relationship_supplement>\n") end file:write("</historical_event_relationship_supplements>\n") file:write("<historical_event_collections>\n") file:write("</historical_event_collections>\n") file:write("<historical_eras>\n") file:write("</historical_eras>\n") file:write("<written_contents>\n") for wcK, wcV in progress_ipairs(df.global.world.written_contents.all) do file:write("\t<written_content>\n") file:write("\t\t<id>"..wcV.id.."</id>\n") file:write("\t\t<title>"..escape_xml(dfhack.df2utf(wcV.title)).."</title>\n") file:write("\t\t<page_start>"..wcV.page_start.."</page_start>\n") file:write("\t\t<page_end>"..wcV.page_end.."</page_end>\n") for refK, refV in pairs(wcV.refs) do file:write("\t\t<reference>\n") file:write("\t\t\t<type>"..df_enums.general_ref_type[refV:getType()].."</type>\n") if df.general_ref_artifact:is_instance(refV) then file:write("\t\t\t<id>"..refV.artifact_id.."</id>\n") -- artifact elseif df.general_ref_entity:is_instance(refV) then file:write("\t\t\t<id>"..refV.entity_id.."</id>\n") -- entity elseif df.general_ref_historical_eventst:is_instance(refV) then file:write("\t\t\t<id>"..refV.event_id.."</id>\n") -- event elseif df.general_ref_sitest:is_instance(refV) then file:write("\t\t\t<id>"..refV.site_id.."</id>\n") -- site elseif df.general_ref_subregionst:is_instance(refV) then file:write("\t\t\t<id>"..refV.region_id.."</id>\n") -- region elseif df.general_ref_historical_figurest:is_instance(refV) then file:write("\t\t\t<id>"..refV.hist_figure_id.."</id>\n") -- hist figure elseif df.general_ref_written_contentst:is_instance(refV) then file:write("\t\t\t<id>"..refV.written_content_id.."</id>\n") elseif df.general_ref_poetic_formst:is_instance(refV) then file:write("\t\t\t<id>"..refV.poetic_form_id.."</id>\n") -- poetic form elseif df.general_ref_musical_formst:is_instance(refV) then file:write("\t\t\t<id>"..refV.musical_form_id.."</id>\n") -- musical form elseif df.general_ref_dance_formst:is_instance(refV) then file:write("\t\t\t<id>"..refV.dance_form_id.."</id>\n") -- dance form elseif df.general_ref_interactionst:is_instance(refV) then -- TODO INTERACTION elseif df.general_ref_knowledge_scholar_flagst:is_instance(refV) then -- TODO KNOWLEDGE_SCHOLAR_FLAG elseif df.general_ref_value_levelst:is_instance(refV) then -- TODO VALUE_LEVEL elseif df.general_ref_languagest:is_instance(refV) then -- TODO LANGUAGE elseif df.general_ref_abstract_buildingst:is_instance(refV) then -- TODO ABSTRACT_BUILDING else print("unknown reference",refV:getType(),df_enums.general_ref_type[refV:getType()]) --for k,v in pairs(refV) do print(k,v) end end file:write("\t\t</reference>\n") end file:write("\t\t<type>"..(df_enums.written_content_type[wcV.type] or wcV.type).."</type>\n") for styleK, styleV in pairs(wcV.styles) do file:write("\t\t<style>"..(df_enums.written_content_style[styleV] or styleV).."</style>\n") end file:write("\t\t<author>"..wcV.author.."</author>\n") file:write("\t</written_content>\n") end file:write("</written_contents>\n") file:write("<poetic_forms>\n") for formK, formV in progress_ipairs(df.global.world.poetic_forms.all, 'poetic form') do file:write("\t<poetic_form>\n") file:write("\t\t<id>"..formV.id.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(formV.name,1))).."</name>\n") file:write("\t</poetic_form>\n") end file:write("</poetic_forms>\n") file:write("<musical_forms>\n") for formK, formV in progress_ipairs(df.global.world.musical_forms.all, 'musical form') do file:write("\t<musical_form>\n") file:write("\t\t<id>"..formV.id.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(formV.name,1))).."</name>\n") file:write("\t</musical_form>\n") end file:write("</musical_forms>\n") file:write("<dance_forms>\n") for formK, formV in progress_ipairs(df.global.world.dance_forms.all, 'dance form') do file:write("\t<dance_form>\n") file:write("\t\t<id>"..formV.id.."</id>\n") file:write("\t\t<name>"..escape_xml(dfhack.df2utf(dfhack.TranslateName(formV.name,1))).."</name>\n") file:write("\t</dance_form>\n") end file:write("</dance_forms>\n") file:write("</df_world>\n") file:close() local problem_elements_exist = false for i, element in pairs (problem_elements) do for k, field in pairs (element) do dfhack.printerr (i.." element '"..k.."' attempted to be processed as simple type.") end problem_elements_exist = true end if problem_elements_exist then dfhack.printerr ("Some elements could not be interpreted correctly because they were not simple elements.") dfhack.printerr ("These elements are reported above. Please notify the DFHack community of these value pairs.") dfhack.printerr ("Note that these issues have not invalidated the XML file: it ought to still be usable.") end end -- export information and XML ('p, x') function export_legends_info() print(' Exporting: World map/gen info') gui.simulateInput(vs, 'LEGENDS_EXPORT_MAP') print(' Exporting: Legends xml') gui.simulateInput(vs, 'LEGENDS_EXPORT_XML') print(" Exporting: Extra legends_plus xml") export_more_legends_xml() end function export_detailed_maps() script.start(function() for i = 1, #MAPS do local vs = dfhack.gui.getViewscreenByType(df.viewscreen_export_graphical_mapst, 0) if not vs then local legends_vs = dfhack.gui.getViewscreenByType(df.viewscreen_legendsst, 0) or qerror("Could not find legends screen") gui.simulateInput(legends_vs, 'LEGENDS_EXPORT_DETAILED_MAP') end vs = dfhack.gui.getViewscreenByType(df.viewscreen_export_graphical_mapst, 0) or qerror("Could not find map export screen") vs.sel_type = i - 1 print(' Exporting map: ' .. MAPS[i]) gui.simulateInput(vs, 'SELECT') while dfhack.gui.getCurViewscreen() == vs do script.sleep(10, 'frames') end end end) end -- export site maps function export_site_maps() local vs = dfhack.gui.getCurViewscreen() if ((dfhack.gui.getCurFocus() ~= "legends" ) and (not table_contains(vs, "main_cursor"))) then -- Using open-legends vs = vs.parent --luacheck: retype end if df.viewscreen_legendsst:is_instance(vs) then print(' Exporting: All possible site maps') vs.main_cursor = 1 gui.simulateInput(vs, 'SELECT') for i=1, #vs.sites do gui.simulateInput(vs, 'LEGENDS_EXPORT_MAP') gui.simulateInput(vs, 'STANDARDSCROLL_DOWN') end gui.simulateInput(vs, 'LEAVESCREEN') else qerror('this command can only be used in Legends mode') end end -- main() if dfhack.gui.getCurFocus() == "legends" or dfhack.gui.getCurFocus() == "dfhack/lua/legends" then -- either native legends mode, or using the open-legends.lua script if args[1] == "all" then export_legends_info() export_site_maps() export_detailed_maps() elseif args[1] == "info" then export_legends_info() elseif args[1] == "custom" then export_more_legends_xml() elseif args[1] == "maps" then export_detailed_maps() elseif args[1] == "sites" then export_site_maps() else qerror('Valid arguments are "all", "info", "custom", "maps" or "sites"') end elseif args[1] == "maps" and dfhack.gui.getCurFocus() == "export_graphical_map" then export_detailed_maps() else qerror('exportlegends must be run from the main legends view') end
--player stats Player = { HP = 5, ATK = 1, DEF = 1, MAXHP = 5 } --inventory Inventory = { Stick = {NAME = 'Stick', ATK = 1, DEF = 0, EQUIPPED = false} } --enemies Enemies = { Goblin = {HP = 3, ATK = 1, DEF = 0, MAXHP = 3} } --checked acts La = false Check = false Follow = false --Config LowEnd = false
#!/usr/bin/lua5.3 m = io.read("*number") n = io.read("*number") function isPrime(x) if x <= 1 then return false end if ('23579'):find(tostring(x)) then return true end for i = 2, math.ceil(math.sqrt(math.sqrt(x)+x)) do if x % i == 0 then return false end end return true end cnt = 0 x = 2 while cnt < n do if isPrime(x) then cnt = cnt + 1 if cnt >= m then io.write(x) if (cnt - m + 1) % 10 == 0 then io.write('\n') elseif cnt < n then io.write(' ') end end end if x >= 10 then if ('179'):find(tostring(x)) then x = x + 2 elseif x % 10 == 3 then x = x + 4 else x = x + 1 end else x = x + 1 end end
Account = model 'account' { email = field 'string' {length=254}, username = field 'string' {length=64}, passsalt = field 'string' {length=128}, passhash = field 'string' {length=256}, photourl = field 'string' {length=128}, accountstate = field 'integer' {}, balance = field 'float' {} } Station = model 'station' { city = field 'string' {length=32}, state = field 'string' {length=2}, latitude = field 'float' {}, longitude = field 'float' {}, } StationMonthlyStats = model 'station_monthly_stats' { stationid = field 'integer' {primary=true}, month = field 'integer' {primary=true}, temp = field 'float' {}, rain = field 'float' {}, }
-- Player Note processing and saving function ElderScrollsOfAlts:ShowCharacterNote(self) local charactername = ElderScrollsOfAlts.savedVariables.selected.charactername --Select the Row ElderScrollsOfAlts.debugMsg("ShowCharacterNote:"," SelChar=",tostring(ElderScrollsOfAlts.savedVariables.selected.charactername) ) ElderScrollsOfAlts.debugMsg("ShowCharacterNote:"," SelRow=",tostring(ElderScrollsOfAlts.view.selectedPlayerRow) ) local selectedPlayer = ElderScrollsOfAlts.view.playerLines[ElderScrollsOfAlts.savedVariables.selected.charactername] ElderScrollsOfAlts.debugMsg("ShowCharacterNote: selectedPlayer="..tostring(selectedPlayer) ) ElderScrollsOfAlts.view.selectedPlayerData = selectedPlayer ElderScrollsOfAlts:ShowGuiCharacterNote(self) end function ElderScrollsOfAlts:ShowGuiCharacterNote(self) if(ElderScrollsOfAlts.view.selectedPlayerData==nil)then ElderScrollsOfAlts.errorMsg("failed to get selected character to display note") return end ESOA_GUI2_Notes:SetHidden(false) ESOA_GUI2_Notes:ClearAnchors() ESOA_GUI2_Notes:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, self:GetLeft(), self:GetTop()+100 --ElderScrollsOfAlts.savedVariables.uibutton.left, --ElderScrollsOfAlts.savedVariables.uibutton.top ) ) ESOA_GUI2_Notes:SetHeight( 150 ) ESOA_GUI2_Notes:SetWidth( 300 ) local pNote = ElderScrollsOfAlts.view.selectedPlayerData["note"] --debugMsg("selectedData="..tostring(selectedData)) if( pNote == nil ) then -- end local sVal = zo_strformat("(<<C:1>>)", ElderScrollsOfAlts.view.selectedPlayerData["name"] ) ESOA_GUI2_Notes_WhoAmI:SetText(sVal) ESOA_GUI2_Notes_WhoAmI:SetText(sVal) ESOA_GUI2_Notes_Index_Note:SetText("") ESOA_GUI2_Notes_Category_Edit:SetText("") ESOA_GUI2_Notes_Order_Edit:SetText("") ElderScrollsOfAlts:ResetNote() end function ElderScrollsOfAlts:ResetNote() local tplayer = ElderScrollsOfAlts.view.selectedPlayerData if( tplayer == nil ) then ElderScrollsOfAlts.errorMsg("failed to get selected character for note") return end ESOA_GUI2_Notes_Index_Note:SetText("") ESOA_GUI2_Notes_Category_Edit:SetText("") ESOA_GUI2_Notes_Order_Edit:SetText("") local note = tplayer.note if( note ~= nil ) then ESOA_GUI2_Notes_Index_Note:SetText(note) end local catH = tplayer.category if(catH == nil) then catH = ElderScrollsOfAlts.CATEGORY_ALL end ESOA_GUI2_Notes_Category_Edit:SetText(catH) local playersorder = tplayer.playersorder if( playersorder ~= nil ) then ESOA_GUI2_Notes_Order_Edit:SetText(playersorder) end -- end -- function ElderScrollsOfAlts:SaveNote() local tplayer = ElderScrollsOfAlts.view.selectedPlayerData if( tplayer == nil ) then ElderScrollsOfAlts.errorMsg("failed to get selected character to save note") return end tplayer.note = ESOA_GUI2_Notes_Index_Note:GetText() ElderScrollsOfAlts.view.currentnote = tplayer.note ElderScrollsOfAlts.SavePlayerData( tplayer.rawname, "note", tplayer.note) -- ORDER -- local selOrder = ESOA_GUI2_Notes_Order_Edit:GetText() if(selOrder==nil or selOrder=="")then selOrder = 0 end selOrder = tonumber(selOrder) tplayer.playersorder = selOrder ElderScrollsOfAlts.SavePlayerData( tplayer.rawname, "playersorder", tplayer.playersorder) ElderScrollsOfAlts.view.currentorder = tplayer.playersorder -- CATEGORY -- local selCat = ESOA_GUI2_Notes_Category_Edit:GetText() if(selCat==nil or selCat=="")then selCat = ElderScrollsOfAlts.CATEGORY_ALL end tplayer.category = selCat -- OUTPUT -- ElderScrollsOfAlts.outputMsg( zo_strformat("ESOA, saved note, order=<<1>>/cat=<<2>>", tostring(selOrder) , tostring(selCat) ) ) -- FINISH -- ElderScrollsOfAlts.SavePlayerData( tplayer.rawname, "category", tplayer.category) ElderScrollsOfAlts.view.currentcategory = tplayer.category -- -- ElderScrollsOfAlts.outputMsg("ESOA, saved note") --ElderScrollsOfAlts.RefreshViewableTable() ElderScrollsOfAlts:ShowSetView() end function ElderScrollsOfAlts:CloseNote(self) ElderScrollsOfAlts.view.selectedPlayerRow = nil ESOA_GUI2_Notes_Index_Note:SetText("") ESOA_GUI2_Notes_Category_Edit:SetText("") ESOA_GUI2_Notes_Order_Edit:SetText("") ESOA_GUI2_Notes:SetHidden(true) end --EOF
test_static() print("test_cclosure return", test_cclosure({name = "chendong", email = "baisaichen@live.com"})) print("int_static == ", int_static) print("int_static == ", get_userdata_property(int_static)) set_userdata_property(int_static, 100) print("int_static == ", get_userdata_property(int_static)) print("this is print()") print_debug("this is print_debug()") print_warning("this is print_warning") print_error("this is print_error")
hook.Add("PlayerSetModel","pimpmybot",function(ply) if ply:SteamID() == "BOT" then ply:SetModel("models/AntLion.mdl") -- modify models/AntLion.mdl by any model end end)
local mongodb = require("libs/mongodb"); function onRequest(headers, matches, requestText) local mdbConn = mongodb.new("mongodb://localhost:27017/"):connect(); local collection = mdbConn:getCollection("taplection", "users"); local result = collection:find({ _id = { ["$oid"] = "57359c4fad475040b80057d1" } }); collection:close(); mdbConn:disconnect(); return Helix.success({ data = result }); end
function DIALOG() NODE(0) SAY("Wow! Today is my lucky day!") ANSWER("Won?",1) ANSWER("Piss off! Leave me in peace!",100) NODE(1) SAY("You can say that again! I cleaned them out! In the lottery! 10 000 Credits in one shot. Madness!") ANSWER("I can see, Lucky streak.",2) NODE(2) SAY("I am gonna celebrate. I've earned it! Yippeeh!") ENDDIALOG() NODE(100) SAY("Nobody is going to spoil my day! Today is my lucky day!") ENDDIALOG() end
require "lightspeed".setup { ignore_case = false, exit_after_idle_msecs = {unlabeled = 1000, labeled = nil}, -- s/x grey_out_search_area = true, highlight_unique_chars = true, jump_on_partial_input_safety_timeout = 400, match_only_the_start_of_same_char_seqs = true, substitute_chars = {["\r"] = "¬"}, -- Leaving the appropriate list empty effectively disables -- "smart" mode, and forces auto-jump to be on or off. -- safe_labels = { . . . }, -- labels = { . . . }, cycle_group_fwd_key = "<space>", cycle_group_bwd_key = "<tab>", -- f/t limit_ft_matches = 4, repeat_ft_with_target_char = false }
att.PrintName = "The Great Journey" att.Icon = Material("snowysnowtime/2k/ico/sgico/greatjourney.png", "smooth mips") att.Description = "Great Journey for the CAWS" att.Desc_Pros = { " The Great Journey waits for no one, brother." } att.Desc_Cons = { } att.Slot = "skin_hcesg" att.Free = true att.ActivateElements = {"greatjourney"} att.AttachSound = "attch/snow/halo/h1/forward.wav" att.DetachSound = "attch/snow/halo/h1/back.wav"
local mock_time = require("deftest.mock.time") local time_string = require("eva.libs.time_string") local eva = require("eva.eva") return function() describe("Eva Promocode", function() before(function() eva.init("/resources/tests/eva_tests.json") mock_time.mock() mock_time.set(0) end) it("Basic code redeem", function() assert(eva.promocode.is_can_redeem("AWSOME") == true) assert(eva.wallet.get("exp") == 0) eva.promocode.redeem_code("AWSOME") assert(eva.wallet.get("exp") == 100) assert(eva.promocode.is_can_redeem("AWSOME") == false) end) it("Code redeem with time restrictions", function() local time = time_string.parse_ISO("2019-09-07Z") mock_time.set(time) assert(eva.promocode.is_can_redeem("DEFOLD") == false) assert(eva.promocode.redeem_code("DEFOLD") == false) assert(eva.wallet.get("gold") == 0) local time2 = time_string.parse_ISO("2019-11-07Z") mock_time.set(time2) assert(eva.promocode.is_can_redeem("DEFOLD") == true) assert(eva.promocode.redeem_code("DEFOLD") == true) assert(eva.wallet.get("gold") == 10) end) end) end
local Native = require('lib.stdlib.native') local converter = require('lib.stdlib.enum.converter') ---@class minimapicon local minimapicon = { } return minimapicon
voiceData = {} radioData = {} callData = {} mumbleConfig = { debug = false, -- enable debug msgs voiceModes = { {2.5, "Whisper"}, -- Whisper speech distance in gta distance units {8.0, "Normal"}, -- Normal speech distance in gta distance units {20.0, "Shouting"}, -- Shout speech distance in gta distance units }, speakerRange = 1.5, -- Speaker distance in gta distance units (how close you need to be to another player to hear other players on the radio or phone) callSpeakerEnabled = true, -- Allow players to hear all talking participants of a phone call if standing next to someone that is on the phone radioSpeakerEnabled = true, -- Allow players to hear all talking participants in a radio if standing next to someone that has a radio spectateAudioEnabled = true, -- Allow overriding a players location if the current gameplay camera is over a certain distance away. (Spectate mode for instance) radioEnabled = true, -- Enable or disable using the radio micClicks = true, -- Are clicks enabled or not micClickOn = true, -- Is click sound on active micClickOff = true, -- Is click sound off active micClickVolume = 0.1, -- How loud a mic click is radioClickMaxChannel = 100, -- Set the max amount of radio channels that will have local radio clicks enabled controls = { -- Change default key binds proximity = { key = 20, -- Z }, -- Switch proximity mode radio = { pressed = false, -- don't touch key = 137, -- capital }, -- Use radio speaker = { key = 20, -- Z secondary = 21, -- LEFT SHIFT } -- Toggle speaker mode (phone calls) }, radioChannelNames = { -- Add named radio channels (Defaults to [channel number] MHz) [1] = "LEO Tac 1", [2] = "LEO Tac 2", [3] = "EMS Tac 1", [4] = "EMS Tac 2", [500] = "Hurr Durr 500 Hurr Durr", }, callChannelNames = { -- Add named call channels (Defaults to [channel number]) }, -- use3dAudio = false, -- (currently doesn't work properly) make sure setr voice_use3dAudio true and setr voice_useSendingRangeOnly true is in your server.cfg (currently doesn't work properly) } resourceName = GetCurrentResourceName() if IsDuplicityVersion() then function DebugMsg(msg) if mumbleConfig.debug then print("\x1b[32m[" .. resourceName .. "]\x1b[0m ".. msg) end end else function DebugMsg(msg) if mumbleConfig.debug then print("[" .. resourceName .. "] ".. msg) end end -- Update config properties from another script function SetMumbleProperty(key, value) if mumbleConfig[key] ~= nil and mumbleConfig[key] ~= "controls" and mumbleConfig[key] ~= "radioChannelNames" then mumbleConfig[key] = value if key == "callSpeakerEnabled" then SendNUIMessage({ speakerOption = mumbleConfig.callSpeakerEnabled }) end end end function SetRadioChannelName(channel, name) local channel = tonumber(channel) if channel ~= nil and name ~= nil and name ~= "" then if not mumbleConfig.radioChannelNames[channel] then mumbleConfig.radioChannelNames[channel] = tostring(name) end end end function SetCallChannelName(channel, name) local channel = tonumber(channel) if channel ~= nil and name ~= nil and name ~= "" then if not mumbleConfig.callChannelNames[channel] then mumbleConfig.callChannelNames[channel] = tostring(name) end end end -- Make exports available on first tick exports("SetMumbleProperty", SetMumbleProperty) exports("SetTokoProperty", SetMumbleProperty) exports("SetRadioChannelName", SetRadioChannelName) exports("SetCallChannelName", SetCallChannelName) end function GetPlayersInRadioChannel(channel) local channel = tonumber(channel) local players = false if channel ~= nil then if radioData[channel] ~= nil then players = radioData[channel] end end return players end function GetPlayersInRadioChannels(...) local channels = { ... } local players = {} for i = 1, #channels do local channel = tonumber(channels[i]) if channel ~= nil then if radioData[channel] ~= nil then players[#players + 1] = radioData[channel] end end end return players end function GetPlayersInAllRadioChannels() return radioData end function GetPlayersInPlayerRadioChannel(serverId) local players = false if serverId ~= nil then if voiceData[serverId] ~= nil then local channel = voiceData[serverId].radio if channel > 0 then if radioData[channel] ~= nil then players = radioData[channel] end end end end return players end exports("GetPlayersInRadioChannel", GetPlayersInRadioChannel) exports("GetPlayersInRadioChannels", GetPlayersInRadioChannels) exports("GetPlayersInAllRadioChannels", GetPlayersInAllRadioChannels) exports("GetPlayersInPlayerRadioChannel", GetPlayersInPlayerRadioChannel)
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BseUseTool_pb', package.seeall) local BSEUSETOOL = protobuf.Descriptor(); local BSEUSETOOL_SESSIONID_FIELD = protobuf.FieldDescriptor(); local BSEUSETOOL_SLOT_FIELD = protobuf.FieldDescriptor(); BSEUSETOOL_SESSIONID_FIELD.name = "sessionId" BSEUSETOOL_SESSIONID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseUseTool.sessionId" BSEUSETOOL_SESSIONID_FIELD.number = 1 BSEUSETOOL_SESSIONID_FIELD.index = 0 BSEUSETOOL_SESSIONID_FIELD.label = 2 BSEUSETOOL_SESSIONID_FIELD.has_default_value = false BSEUSETOOL_SESSIONID_FIELD.default_value = "" BSEUSETOOL_SESSIONID_FIELD.type = 9 BSEUSETOOL_SESSIONID_FIELD.cpp_type = 9 BSEUSETOOL_SLOT_FIELD.name = "slot" BSEUSETOOL_SLOT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseUseTool.slot" BSEUSETOOL_SLOT_FIELD.number = 2 BSEUSETOOL_SLOT_FIELD.index = 1 BSEUSETOOL_SLOT_FIELD.label = 2 BSEUSETOOL_SLOT_FIELD.has_default_value = false BSEUSETOOL_SLOT_FIELD.default_value = 0 BSEUSETOOL_SLOT_FIELD.type = 5 BSEUSETOOL_SLOT_FIELD.cpp_type = 1 BSEUSETOOL.name = "BseUseTool" BSEUSETOOL.full_name = ".com.xinqihd.sns.gameserver.proto.BseUseTool" BSEUSETOOL.nested_types = {} BSEUSETOOL.enum_types = {} BSEUSETOOL.fields = {BSEUSETOOL_SESSIONID_FIELD, BSEUSETOOL_SLOT_FIELD} BSEUSETOOL.is_extendable = false BSEUSETOOL.extensions = {} BseUseTool = protobuf.Message(BSEUSETOOL) _G.BSEUSETOOL_PB_BSEUSETOOL = BSEUSETOOL
-------------------------------------------------------------------------------- -- Easydoorbell Speaker Entity Clientside Init -------------------------------------------------------------------------------- include( "shared.lua" ) function ENT:Draw() self:DrawModel() end
-------------------------------- -- @module MenuItemFont -- @extend MenuItemLabel -- @parent_module cc -------------------------------- -- Returns the name of the Font.<br> -- js getFontNameObj<br> -- js NA -- @function [parent=#MenuItemFont] getFontNameObj -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Set the font name .<br> -- c++ can not overload static and non-static member functions with the same parameter types.<br> -- so change the name to setFontNameObj.<br> -- js setFontName<br> -- js NA -- @function [parent=#MenuItemFont] setFontNameObj -- @param self -- @param #string name -- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont) -------------------------------- -- Initializes a menu item from a string with a target/selector. -- @function [parent=#MenuItemFont] initWithString -- @param self -- @param #string value -- @param #function callback -- @return bool#bool ret (return value: bool) -------------------------------- -- get font size .<br> -- js getFontSize<br> -- js NA -- @function [parent=#MenuItemFont] getFontSizeObj -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Set font size.<br> -- c++ can not overload static and non-static member functions with the same parameter types.<br> -- so change the name to setFontSizeObj.<br> -- js setFontSize<br> -- js NA -- @function [parent=#MenuItemFont] setFontSizeObj -- @param self -- @param #int size -- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont) -------------------------------- -- Set the default font name. -- @function [parent=#MenuItemFont] setFontName -- @param self -- @param #string name -- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont) -------------------------------- -- Get default font size. -- @function [parent=#MenuItemFont] getFontSize -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Get the default font name. -- @function [parent=#MenuItemFont] getFontName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Set default font size. -- @function [parent=#MenuItemFont] setFontSize -- @param self -- @param #int size -- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont) -------------------------------- -- js ctor -- @function [parent=#MenuItemFont] MenuItemFont -- @param self -- @return MenuItemFont#MenuItemFont self (return value: cc.MenuItemFont) return nil
function _G.RELOAD(...) return require("plenary.reload").reload_module(...) end function _G.R(name) RELOAD(name) return require(name) end
--[[ Copyright (C) 2013 Lex Robinson This code is freely available under the MIT License. See the LICENSE file for more information. --]] function EFFECT:Init(edata) self.pos = edata:GetOrigin(); self.amount = edata:GetScale(); self.start = CurTime(); self.length = 3; self.finish = self.start + self.length; print("I'm an effect!"); surface.SetFont("DermaLarge") local w, h = surface.GetTextSize(self.amount); self.x = -w / 2; self.y = -h; end function EFFECT:Think() self.pos = self.pos + vector_up * FrameTime() * 20;-- + self.ang:Forward() * 0.01 * math.sin(CurTime()); return CurTime() < self.finish; end function EFFECT:Render() local ea = EyeAngles(); local angle = Angle(90, ea.y - 180, 0); angle:RotateAroundAxis(angle:Up(), 90); self.ang = angle; cam.Start3D2D(self.pos, angle, 0.2); surface.SetTextColor(255, 255, 255, Lerp((self.finish - CurTime()) / self.length, 0, 255)); surface.SetFont("DermaLarge") surface.SetTextPos(self.x, self.y); surface.DrawText(self.amount); cam.End3D2D(); end print("I've been loaded!")
-- Rectangle.lua -- babyjeans -- --- Rectangle = class("Rectangle") function Rectangle:init(x, y, w, h) self.x = x self.y = y self.w = w self.h = h end function Rectangle:min() return { x=self.x, y=self.y } end function Rectangle:max() return { x=self.x+self.w, y=self.y+self.h } end function Rectangle:contains(x, y) return x >= self.x and x <= self.x + self.w and y >= self.y and y <= self.y + self.h end function Rectangle:intersects(otherRect) local min = self:min() local max = self:max() local otherMin = otherRect:min() local otherMax = otherRect:max() if min.x > otherMax.x or max.x < otherMin.x or min.y > otherMax.y or max.y < otherMin.y then return false end return true end return Rectangle
--[[--------------------------------------------------------- Super Cooking Panic for Garry's Mod by Xperidia (2020) -----------------------------------------------------------]] AddCSLuaFile() function GM.PlayerMeta:IsValidPlayingState() return self:Alive() and self:Team() ~= TEAM_SPECTATOR and self:Team() ~= TEAM_UNASSIGNED end function GM.PlayerMeta:IsHoldingIngredient() return self.GetHeldIngredient and IsValid(self:GetHeldIngredient()) end
local v,s,t,f = require("Vec2"),require("Size"),true,false return {"Array",{"Phyx.Disk","circle","Dynamic",v(0,0),0,v(0,0),90,1,0.4,0.4,0,0,f,v(0,-10),f,f,0,f,"Model/duality.clip|s5",v(0,0)}}
local Timer = require 'vendor/timer' local sound = require 'vendor/TEsound' return { name = 'hempleaf', position_offset = { x = 0, y = 0 }, height = 7, width = 16, damage = 18, antigravity = true, jumpkill = false, hp = 2, tokens = 0, tokenTypes = { -- p is probability ceiling and this list should be sorted by it, with the last being 1 { item = 'coin', v = 1, p = 0.9 }, { item = 'health', v = 1, p = 1 } }, animations = { dying = { right = {'once', {'2-3,1'}, 0.25}, left = {'once', {'2-3,1'}, 0.25} }, default = { right = {'loop', {'1,1'}, 0.25}, left = {'loop', {'1,1'}, 0.25} }, hurt = { right = {'loop', {'1,1'}, 0.25}, left = {'loop', {'1,1'}, 0.25} }, attack = { right = {'loop', {'1,1'}, 0.25}, left = {'loop', {'1,1'}, 0.25} }, }, enter = function( enemy ) enemy.maxx = enemy.position.x + 220 enemy.minx = enemy.position.x - 220 enemy.maxy = enemy.position.y + 220 enemy.miny = enemy.position.y - 220 end, update = function( dt, enemy, player, level ) if enemy.dead then return end if enemy.state == 'attack' then enemy:die() end if enemy.position.x > enemy.maxx then enemy:die() elseif enemy.position.x < enemy.minx then enemy:die() end if enemy.position.y > enemy.maxy then enemy:die() elseif enemy.position.y < enemy.miny then enemy:die() end if math.abs(enemy.velocity.y) < 1 then enemy:die() end local angle = math.atan2(((player.position.y+24) - enemy.position.y), (player.position.x+10 - enemy.position.x)) local dx = 200 * math.cos(angle) local dy = 100 * math.sin(angle) enemy.position.x = enemy.position.x + (dx * dt) enemy.position.y = enemy.position.y + (dy * dt) end }
--[[ © 2021 Tony Ferguson, do not share, re-distribute or modify without permission of its author ( devultj@gmail.com - Tony Ferguson, http://www.tferguson.co.uk/ ) ]] local DARKRP = {} DARKRP.name = "DarkRP" DARKRP.gamemodeCallback = function() return DarkRP and true or false end DARKRP.isPolice = function( player ) return player:isCP() end DARKRP.addMoney = function( player, amount ) return player:addMoney( amount ) end DARKRP.getJobName = function( player ) return team.GetName( player:Team() ) end DARKRP.getJobCategory = function( player ) return player:getJobTable().category end DARKRP.notify = function( player, text, notificationType, notificationTime ) return DarkRP.notify( player, notificationType, notificationTime or 4, text ) end DARKRP.getJobList = function() return RPExtraTeams end DARKRP.getCategoryIndex = function() return "category" end dHeists.gamemodes:addGamemode( DARKRP )
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("game.rules.fog_of_war.actions", function() local Actions = require "game.rules.fog_of_war.actions" local Position = require "game.rules.world.position" local mockStore = require "moonpie.test_helpers.mock_store" describe("ACTION: updatePerspective", function() local visibilityMap = require "game.rules.field_of_view.visibility_map" it("takes a perspective and updates it's fog of war for each position", function() local perspective = {} local vm = visibilityMap:new() vm:setVisible(Position(1, 1, 1)) local state = { fieldOfView = { [perspective] = vm } } mockStore(state) local action = Actions.updatePerspective(perspective) assert.equals("FOG_OF_WAR_UPDATE_PERSPECTIVE", action.type) assert.thunk_dispatches_type("FOG_OF_WAR_UPDATE_POSITION", action) end) end) describe("game.rules.fog_of_war.actions.update", function() it("takes a perspective, position, and tile information seen to track in FoW database", function() local entity, position, tile = {}, {}, {} local action = Actions.updatePosition(entity, position, tile) assert.equals("FOG_OF_WAR_UPDATE_POSITION", action.type) assert.equals(entity, action.payload.perspective) assert.equals(position, action.payload.position) assert.equals(tile, action.payload.tile) end) it("can take a hashKey for position", function() local entity, hash, tile = {}, 1234, {} local action = Actions.updatePosition(entity, hash, tile) assert.equals(hash, action.payload.positionHashKey) end) end) end)
#!/usr/bin/env luajit -- package.path = "../?.lua;../?/init.lua;" .. package.path package.path = package.path .. ";" .. os.getenv("P4_WORKSPACE") .. "/DebLua/?.lua" require "lua_shell" local wd = pshell.pwd() local git_dir = os.getenv("LXGIT") package.path = git_dir.."/?.lua;".. package.path -- package.path = git_dir.."/?.lua;".. git_dir .."/glua/init.lua;"..package.path local gl = require 'glua.init' local gui = require 'glua.gui' local CWD = "" ---- Main ---------------------------------------------------------------------- function main() Log.Init(CWD .. "gl_simple.log") Log.SetTimestamp("%H:%M:%S > ") Log.f("initialize display") -- gl.utInitContextVersion(2, 1) gl.utInitDisplayString('rgba double depth>=32 samples~8') gl.utInitWindowSize(400, 300) gl.utInitWindowPosition(100, 100) Log.f("glutCreateWindow") local window = gl.utCreateWindow("gl_simple") gl.ClearColor(.2, .2, .2, 1) gl.Enable(gl.BLEND) gl.BlendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) local font = gui.font{size = 48} local guiProgram = gl.program{ [gl.VERTEX_SHADER] = gl.path('glua.shaders.gui', 'vert'), [gl.FRAGMENT_SHADER] = gl.path('glua.shaders.gui', 'frag') }() guiProgram.color = {1, 1, .5, 1} guiProgram.alphaMask = true local text = font:array(guiProgram, 'Hello world!') gl.utDisplayFunc(function () gl.Clear(gl.COLOR_BUFFER_BIT + gl.DEPTH_BUFFER_BIT) text() gl.utSwapBuffers() end) gl.utReshapeFunc(function (w, h) guiProgram.modelViewProjectionMatrix = gl.ortho(0, w, h, 0, -1, 0) gl.Viewport(0, 0, w, h) end) Log.f("glutMainLoop() start") gl.utMainLoop() Log.f("glutMainLoop() end") end
fx_version 'bodacious' game 'gta5' name 'prof_motoristaPub' description '' server_scripts { '@vrp/lib/utils.lua', 'config/config.lua', 'server/main.lua' } ui_page 'html/index.html' client_scripts { '@vrp/lib/utils.lua', 'config/unloadType.lua', 'config/busType.lua', 'config/routes/*.lua', 'config/config.lua', 'client/*.lua', } files { 'html/*.*' }
--- just a silly wrapper for the kepler file logger --EVENTS: --[[ <initialize source="core"> log this </initialize> ]] --[[ <loadUtilities source="core"> finish: log this </loadUtilities> ]] --[[ <loadConfig source="core"> finish: log this </loadConfig> ]] --[[ <loadCore source="core"> finish: log this </loadCore> ]] --[[ <loadPlugins source="core"> finish: log this </loadPlugins> ]] --[[ <shutdown source="core"> log this. </loadPlugins> ]] local multiplog = {} --all the supported logging destinations local multiplog_call = function(key) return function(notself, a, b, c) for i=1, #multiplog do local thislog = multiplog[i] thislog[key](thislog, a, b, c) end end end require "logging" logger = setmetatable({ init = function(self) local logpath = cf("log_file") or "logs/webylene.log" local log_to_console = cf('verbose') if not logpath:match("^" .. webylene.path_separator) then logpath = webylene.path .. webylene.path_separator .. logpath end require "logging.file" local file_logger, logger_err = logging.file(logpath) if file_logger then table.insert(multiplog, file_logger) else --fallback to console logging log_to_console = true end if log_to_console then require "logging.console" table.insert(multiplog, logging.console()) end if logger_err then self:error("logger: " .. logger_err) self:info("logger: Falling back on logging to console.") end --log important webylene loading events for i, ev in pairs({"Utilities", "Config", "Core", "Plugins"}) do event:addFinishListener('load' .. ev, function() self:info(ev .. " loaded without incident.") end) end event:addStartListener("initialize", function() self:info("initializing") end) event:addFinishListener("initialize", function() self:info("initialized without incident.") end) event:addStartListener("shutdown", function() self:info("shutting down.") end) end }, logging) --oh my what an upstanding first-class citizen you are. for _, key in pairs{ 'log', 'debug', 'info', 'warn', 'error', 'fatal', 'setLevel' } do logger[key]=multiplog_call(key) end
return require 'hydro.solver.grhd-behavior'(require 'hydro.solver.fvsolver')
local _, nCore = ... function nCore:RegisterDefaultSetting(key, value) if nCoreDB == nil then nCoreDB = {} end if nCoreDB[key] == nil then nCoreDB[key] = value end end function nCore:SetDefaultOptions() nCore:RegisterDefaultSetting("AltBuy", true) nCore:RegisterDefaultSetting("ArchaeologyHelper", true) nCore:RegisterDefaultSetting("AutoGreed", true) nCore:RegisterDefaultSetting("AutoQuest", true) nCore:RegisterDefaultSetting("Dressroom", true) nCore:RegisterDefaultSetting("Durability", true) nCore:RegisterDefaultSetting("ErrorFilter", true) nCore:RegisterDefaultSetting("Fonts", true) nCore:RegisterDefaultSetting("ObjectiveTracker", true) nCore:RegisterDefaultSetting("MapCoords", true) nCore:RegisterDefaultSetting("MoveTalkingHeads", true) nCore:RegisterDefaultSetting("QuestTracker", true) nCore:RegisterDefaultSetting("Skins", true) nCore:RegisterDefaultSetting("SpellID", true) nCore:RegisterDefaultSetting("VignetteAlert", true) end function nCore:LockInCombat(frame) frame:SetScript("OnUpdate", function(self) if not InCombatLockdown() then self:Enable() else self:Disable() end end) end function nCore:RegisterControl(control, parentFrame) if ( ( not parentFrame ) or ( not control ) ) then return; end parentFrame.controls = parentFrame.controls or {}; tinsert(parentFrame.controls, control); end local prevControl function nCore:CreateLabel(cfg) --[[ { type = "Label", name = "LabelName", parent = Options, label = L.LabelText, fontObject = "GameFontNormalLarge", relativeTo = LeftSide, relativePoint = "TOPLEFT", offsetX = 16, offsetY = -16, }, --]] cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -16 cfg.relativeTo = cfg.relativeTo or prevControl cfg.fontObject = cfg.fontObject or "GameFontNormalLarge" local label = cfg.parent:CreateFontString(cfg.name, "ARTWORK", cfg.fontObject) label:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) label:SetText(cfg.label) prevControl = label return label end function nCore:CreateCheckBox(cfg) --[[ { type = "CheckBox", name = "Test", parent = parent, label = L.TestLabel, tooltip = L.TestTooltip, isCvar = nil or True, var = "TestVar", needsRestart = nil or True, disableInCombat = nil or True, func = function(self) -- Do stuff here. end, initialPoint = "TOPLEFT", relativeTo = frame, relativePoint, "BOTTOMLEFT", offsetX = 0, offsetY = -6, }, --]] cfg.initialPoint = cfg.initialPoint or "TOPLEFT" cfg.relativePoint = cfg.relativePoint or "BOTTOMLEFT" cfg.offsetX = cfg.offsetX or 0 cfg.offsetY = cfg.offsetY or -6 cfg.relativeTo = cfg.relativeTo or prevControl local checkBox = CreateFrame("CheckButton", cfg.name, cfg.parent, "InterfaceOptionsCheckButtonTemplate") checkBox:SetPoint(cfg.initialPoint, cfg.relativeTo, cfg.relativePoint, cfg.offsetX, cfg.offsetY) checkBox.Text:SetText(cfg.label) checkBox.GetValue = function(self) return checkBox:GetChecked() end checkBox.SetValue = function(self) checkBox:SetChecked(nCoreDB[cfg.var]) end checkBox.var = cfg.var checkBox.isCvar = cfg.isCvar if cfg.needsRestart then checkBox.restart = false end if cfg.tooltip then if cfg.needsRestart then cfg.tooltip = cfg.tooltip.." "..RED_FONT_COLOR:WrapTextInColorCode(REQUIRES_RELOAD) end checkBox.tooltipText = cfg.tooltip end if cfg.disableInCombat then nCore:LockInCombat(checkBox) end checkBox:SetScript("OnClick", function(self) local checked = self:GetChecked() PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON) checkBox.value = checked if cfg.needsRestart then checkBox.restart = not checkBox.restart end if cfg.func then cfg.func(self) end end) nCore:RegisterControl(checkBox, cfg.parent) prevControl = checkBox return checkBox end
--- -- @class PANEL -- @section DCardTTT2 local PANEL = {} local MODE_DEFAULT = ShopEditor.MODE_DEFAULT local MODE_ADDED = ShopEditor.MODE_ADDED local MODE_INHERIT_ADDED = ShopEditor.MODE_INHERIT_ADDED local MODE_INHERIT_REMOVED = ShopEditor.MODE_INHERIT_REMOVED --- -- @ignore function PANEL:Init() self:SetContentAlignment(5) self:SetTall(22) self:SetMouseInputEnabled(true) self:SetKeyboardInputEnabled(true) self:SetCursor("hand") self:SetFont("DermaTTT2TextLarge") -- remove label and overwrite function self:SetText("") self.SetText = function(slf, text) slf.data.text = text end self.data = { title = "", icon = nil, mode = MODE_DEFAULT } end --- -- @return string -- @realm client function PANEL:GetText() return self.data.text end --- -- @param Material icon -- @realm client function PANEL:SetIcon(icon) self.data.icon = icon end --- -- @return Matieral -- @realm client function PANEL:GetIcon() return self.data.icon end --- -- @param number mode -- @param[default=false] boolean triggerFunction -- @realm client function PANEL:SetMode(mode, triggerFunction) if triggerFunction then self:OnModeChanged(self.data.mode or MODE_DEFAULT, mode or MODE_DEFAULT) end self.data.mode = mode or MODE_DEFAULT end --- -- @return number -- @realm client function PANEL:GetMode() return self.data.mode end --- -- @param number keyCode -- @realm client function PANEL:OnMouseReleased(keyCode) if keyCode == MOUSE_LEFT then if self:GetMode() == MODE_DEFAULT then self:SetMode(MODE_ADDED, true) elseif self:GetMode() == MODE_INHERIT_REMOVED then self:SetMode(MODE_INHERIT_ADDED, true) elseif self:GetMode() == MODE_ADDED then self:SetMode(MODE_DEFAULT, true) elseif self:GetMode() == MODE_INHERIT_ADDED then self:SetMode(MODE_INHERIT_REMOVED, true) end end self.BaseClass.OnMouseReleased(self, keyCode) end --- -- @param number oldMode -- @param number newMode -- @realm client function PANEL:OnModeChanged(oldMode, newMode) end --- -- @return boolean -- @realm client function PANEL:IsDown() return self.Depressed end --- -- @ignore function PANEL:Paint(w, h) derma.SkinHook("Paint", "CardTTT2", self, w, h) return false end derma.DefineControl("DCardTTT2", "A special button used for the shop editor", PANEL, "DLabelTTT2")
local print = print local ipairs = ipairs local io = io local os = os local oop = require "loop.base" module("latt.ConsoleResultViewer", oop.class) function __new(self, result) return oop.rawnew(self, { result = result, }) end function show(self) print("==============================================") print("LATT (Lua Automated Testing Tool) version 1.0\n") print("Time: "..os.difftime(self.result.stopTime, self.result.startTime).." second(s)\n") if self.result.failureCounter ~= 0 then print("There were "..self.result.failureCounter.." failure(s):") for i, failure in ipairs(self.result.failures) do print(i..") "..failure.testCaseName.." - "..failure.testName) print(failure.errorMessage.."\n") end print("FAILURES!!!") print("Tests run: "..self.result.testCounter..", Failures: "..self.result.failureCounter.."") else print("OK ("..self.result.testCounter.." tests)") end print("==============================================") end function showAsError(self) if self.result.failureCounter ~= 0 then io.stderr:write("==============================================\n") io.stderr:write("LATT (Lua Automated Testing Tool) version 1.0\n") io.stderr:write("Time: "..os.difftime(self.result.stopTime, self.result.startTime).." second(s)\n") io.stderr:write("There were "..self.result.failureCounter.." failure(s):\n") for i, failure in ipairs(self.result.failures) do io.stderr:write(i..") "..failure.testCaseName.." - "..failure.testName.."\n") io.stderr:write(failure.errorMessage.."\n") end io.stderr:write("FAILURES!!!\n") io.stderr:write("Tests run: "..self.result.testCounter..", Failures: "..self.result.failureCounter.."\n") io.stderr:write("==============================================\n") end end