content
stringlengths
5
1.05M
local M = {} M.state = { target_pane = nil, COMMAND_CHARS_LIMIT = 10000 } M.set_target_pane = function (pane) M.state.target_pane = pane end local CONSTANTS = { visual = 'visual', visual_line = 'visual_line', visual_block = 'visual_block' } -- list_panes_text is output of 'tmux list-panes -a' local get_current_tmux_pane_id = function (list_panes_text, tmux_pane_id) local tmux_pane_pattern = string.gsub(tmux_pane_id, '%%', '%%%%') -- escape nightmare for l in string.gmatch(list_panes_text, '[^\n]+') do if string.find(l, tmux_pane_pattern) then local pane_id = string.sub(l, 0, string.find(l, ' ')-1) local sessid, winid, paneid = string.match(pane_id, '(.+):(%d+).(%d+):') return sessid, winid, paneid end end end local capture_command = function (command) local proc = assert(io.popen(command), "Failed to run command="..command) local text = proc:read('*a') proc:close() return text end -- Guess is other pane in current window. local guess_target_pane = function () local pane_text = capture_command('tmux list-panes -a') local tmux_pane_env = os.getenv('TMUX_PANE') if not tmux_pane_env then return end local sessid, winid, paneid = get_current_tmux_pane_id(pane_text, tmux_pane_env) local guessed_target_pane = sessid..':'..winid..'.'..math.floor(1-paneid) return guessed_target_pane end local get_target_pane = function () if M.state.target_pane then return M.state.target_pane end local guessed_target_pane = guess_target_pane() M.set_target_pane(guessed_target_pane) return guessed_target_pane end local get_buffer_lines = function (start_line, end_line) local buffer = vim.api.nvim_get_current_buf() local buffer_lines = vim.api.nvim_buf_get_lines(buffer, start_line-1, end_line, true) return buffer_lines end local vim_api_ext = { visualmode = function () return vim.api.nvim_eval('visualmode()') end, get_filetype = function () return vim.api.nvim_eval('&filetype') end } local map_visual_mode = function (visual_mode_char) if visual_mode_char == 'v' then return CONSTANTS.visual elseif visual_mode_char == 'V' then return CONSTANTS.visual_line elseif visual_mode_char == string.char(22) then -- 22 is code for ^V, i.e. visual block mode return CONSTANTS.visual_block end end local get_last_visual_mode = function () local last_visual_mode_char = vim_api_ext.visualmode() local last_visual_mode = map_visual_mode(last_visual_mode_char) return last_visual_mode end local join_table = function (table, sep) local sep = sep or '\n' local result = '' for k,v in pairs(table) do result = result..v..sep end return result end local get_selected_text = function (visual_mode) local visual_mode = visual_mode or get_last_visual_mode() local buffer = vim.api.nvim_get_current_buf() local sel_start, sel_end = vim.api.nvim_buf_get_mark(buffer, '<'), vim.api.nvim_buf_get_mark(buffer, '>') local sel_start_line, sel_end_line = sel_start[1], sel_end[1] local sel_start_column, sel_end_column = sel_start[2], sel_end[2] local lines = get_buffer_lines(sel_start_line, sel_end_line) if visual_mode == CONSTANTS.visual then lines[1] = lines[1]:sub(sel_start_column+1) lines[#lines] = lines[#lines]:sub(1, sel_start_line == sel_end_line and sel_end_column-sel_start_column+1 or sel_end_column+1) elseif visual_mode == CONSTANTS.visual_block then for k,v in pairs(lines) do lines[k] = lines[k]:sub(sel_start_column+1, sel_end_column+1) end end local selection = join_table(lines) return selection end local escape = function (text) return text:gsub('"', '\\"'):gsub('[$]', '\\$') end local get_buffer_path = function () return '/dev/shm/vimslime_buffer.'..os.time()..'.txt' end M.paste_type = {} M.paste_type.text = function (text) local text = text or get_selected_text() local escaped_text = escape(text) if #text < M.state.COMMAND_CHARS_LIMIT then os.execute('tmux set-buffer -b vimslime -- "'..tostring(escaped_text)..'"') else local buffer_path = get_buffer_path() local handle = assert(io.open(buffer_path, 'w'), "Failed to open buffer_path="..buffer_path) handle:write(escaped_text) handle:close() os.execute('tmux load-buffer -b vimslime '..buffer_path) os.remove(buffer_path) end os.execute('tmux paste-buffer -r -d -b vimslime -t '..get_target_pane()) end local function wait_for_cpaste_entry(target_pane, wait_time_seconds) local wait_time_seconds = wait_time_seconds or 0.01 local pane_text = capture_command('tmux capture-pane -p -E - -S 0 -t '..target_pane) local entry_prompt = string.match(pane_text, "Pasting code;[^\n]*\n:\n$") if not entry_prompt and wait_time_seconds < 1 then os.execute('sleep '..wait_time_seconds..'s') wait_for_cpaste_entry(target_pane, wait_time_seconds*2) end end M.paste_type.python = function (text) local text = text or get_selected_text() M.paste_type.text('%cpaste\n') wait_for_cpaste_entry(get_target_pane()) M.paste_type.text(tostring(text)..'\n') M.paste_type.text('--\n') end M.paste = function () local filetype = vim.api.nvim_buf_get_option(0, 'filetype') local f = M.paste_type[filetype] if f then f() else M.paste_type.text() end end return M
--- -- Plan module -- @classmod fourmi.plan -- @author Benoit Giannangeli -- @license MIT -- @copyright Benoit Giannangeli 2019 local colors = require "term.colors" local log = require "fourmi.log" local planMt = { --- -- Run the plan -- @tparam plan self __call = function(self) local time = os.clock() log.info("\n" .. colors.green("🐜 Running plan " .. colors.bright(colors.blue(self.__name))) .. colors.dim(colors.cyan( (self.__description and "\n" .. self.__description .. ": " or " ") .. self.__task.__name )) ) if not self.task then error("Task is undefined for plan " .. self.__name) end local results = {self.__task:run()} log.info( "\n🐜 Plan " .. colors.bright(colors.blue(self.__name)) .. " completed with " .. colors.yellow(#results) .. " result" .. (#results > 1 and "s" or "") .. " in " .. colors.yellow(string.format("%.03f", os.clock() - time) .. "s") ) for _, res in ipairs(results) do log.info("\t→ " .. colors.dim(colors.cyan(tostring(res)))) end end, __index = { --- -- Set plan's task -- @tparam plan self -- @tparam task task task = function(self, task) self.__task = task return self end, --- -- Set plan's description -- @tparam plan self -- @tparam string description description = function(self, description) self.__description = description return self end, --- -- Set plan's name -- @tparam plan self -- @tparam string name name = function(self, name) self.__name = name return self end, -- Aliases desc = function(self, ...) return self:description(...) end, }, } local function plan(name) return setmetatable({ __name = name, }, planMt) end return plan
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB --Cache global variables --Lua functions local _G = _G local pairs, type, unpack, assert = pairs, type, unpack, assert local tremove, tContains, tinsert, wipe = tremove, tContains, tinsert, table.wipe local lower, format = string.lower, string.format --WoW API / Variables local CreateFrame = CreateFrame local IsAddOnLoaded = IsAddOnLoaded local UnitIsDeadOrGhost, InCinematic = UnitIsDeadOrGhost, InCinematic local GetBindingFromClick, RunBinding = GetBindingFromClick, RunBinding local PurchaseSlot, GetBankSlotCost = PurchaseSlot, GetBankSlotCost local MoneyFrame_Update = MoneyFrame_Update local SetCVar, EnableAddOn, DisableAddOn = SetCVar, EnableAddOn, DisableAddOn local ReloadUI, PlaySound, StopMusic = ReloadUI, PlaySound, StopMusic local StaticPopup_Resize = StaticPopup_Resize local AutoCompleteEditBox_OnEnterPressed = AutoCompleteEditBox_OnEnterPressed local AutoCompleteEditBox_OnTextChanged = AutoCompleteEditBox_OnTextChanged local ChatEdit_FocusActiveWindow = ChatEdit_FocusActiveWindow local STATICPOPUP_TEXTURE_ALERT = STATICPOPUP_TEXTURE_ALERT local STATICPOPUP_TEXTURE_ALERTGEAR = STATICPOPUP_TEXTURE_ALERTGEAR local YES, NO, OKAY, CANCEL, ACCEPT, DECLINE = YES, NO, OKAY, CANCEL, ACCEPT, DECLINE --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: ElvUIBindPopupWindowCheckButton local LibStub = LibStub E.PopupDialogs = {} E.StaticPopup_DisplayedFrames = {} E.PopupDialogs['ELVUI_UPDATE_AVAILABLE'] = { text = L["ElvUI is five or more revisions out of date. You can download the newest version from www.tukui.org. Get premium membership and have ElvUI automatically updated with the Tukui Client!"], hasEditBox = 1, OnShow = function(self) self.editBox:SetAutoFocus(false) self.editBox.width = self.editBox:GetWidth() self.editBox:Width(220) self.editBox:SetText("http://www.tukui.org/dl.php") self.editBox:HighlightText() ChatEdit_FocusActiveWindow(); end, OnHide = function(self) self.editBox:Width(self.editBox.width or 50) self.editBox.width = nil end, hideOnEscape = 1, button1 = OKAY, OnAccept = E.noop, EditBoxOnEnterPressed = function(self) ChatEdit_FocusActiveWindow(); self:GetParent():Hide(); end, EditBoxOnEscapePressed = function(self) ChatEdit_FocusActiveWindow(); self:GetParent():Hide(); end, EditBoxOnTextChanged = function(self) if(self:GetText() ~= "http://www.tukui.org/dl.php") then self:SetText("http://www.tukui.org/dl.php") end self:HighlightText() self:ClearFocus() ChatEdit_FocusActiveWindow(); end, OnEditFocusGained = function(self) self:HighlightText() end, showAlert = 1, } E.PopupDialogs["ELVUI_EDITBOX"] = { text = E.title, button1 = OKAY, hasEditBox = 1, OnShow = function(self, data) self.editBox:SetAutoFocus(false) self.editBox.width = self.editBox:GetWidth() self.editBox:Width(280) self.editBox:AddHistoryLine("text") self.editBox.temptxt = data self.editBox:SetText(data) self.editBox:HighlightText() self.editBox:SetJustifyH("CENTER") end, OnHide = function(self) self.editBox:Width(self.editBox.width or 50) self.editBox.width = nil self.temptxt = nil end, EditBoxOnEnterPressed = function(self) self:GetParent():Hide(); end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide(); end, EditBoxOnTextChanged = function(self) if(self:GetText() ~= self.temptxt) then self:SetText(self.temptxt) end self:HighlightText() self:ClearFocus() end, OnAccept = E.noop, timeout = 0, whileDead = 1, preferredIndex = 3, hideOnEscape = 1, } E.PopupDialogs['CLIENT_UPDATE_REQUEST'] = { text = L["Detected that your ElvUI Config addon is out of date. This may be a result of your Tukui Client being out of date. Please visit our download page and update your Tukui Client, then reinstall ElvUI. Not having your ElvUI Config addon up to date will result in missing options."], button1 = OKAY, OnAccept = E.noop, showAlert = 1, } E.PopupDialogs['CLIQUE_ADVERT'] = { text = L["Using the healer layout it is highly recommended you download the addon Clique if you wish to have the click-to-heal function."], button1 = YES, OnAccept = E.noop, showAlert = 1, } E.PopupDialogs["CONFIRM_LOSE_BINDING_CHANGES"] = { text = CONFIRM_LOSE_BINDING_CHANGES, button1 = OKAY, button2 = CANCEL, OnAccept = function() E:GetModule('ActionBars'):ChangeBindingProfile() E:GetModule('ActionBars').bindingsChanged = nil; end, OnCancel = function() if ( ElvUIBindPopupWindowCheckButton:GetChecked() ) then ElvUIBindPopupWindowCheckButton:SetChecked(); else ElvUIBindPopupWindowCheckButton:SetChecked(1); end end, timeout = 0, whileDead = 1, showAlert = 1, }; E.PopupDialogs['TUKUI_ELVUI_INCOMPATIBLE'] = { text = L["Oh lord, you have got ElvUI and Tukui both enabled at the same time. Select an addon to disable."], OnAccept = function() DisableAddOn("ElvUI"); ReloadUI() end, OnCancel = function() DisableAddOn("Tukui"); ReloadUI() end, button1 = 'ElvUI', button2 = 'Tukui', timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs['DISABLE_INCOMPATIBLE_ADDON'] = { text = L["Do you swear not to post in technical support about something not working without first disabling the addon/module combination first?"], OnAccept = function() E.global.ignoreIncompatible = true; end, OnCancel = function() E:StaticPopup_Hide('DISABLE_INCOMPATIBLE_ADDON'); E:StaticPopup_Show('INCOMPATIBLE_ADDON', E.PopupDialogs['INCOMPATIBLE_ADDON'].addon, E.PopupDialogs['INCOMPATIBLE_ADDON'].module) end, button1 = L["I Swear"], button2 = DECLINE, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs['INCOMPATIBLE_ADDON'] = { text = L["INCOMPATIBLE_ADDON"], OnAccept = function() DisableAddOn(E.PopupDialogs['INCOMPATIBLE_ADDON'].addon); ReloadUI(); end, OnCancel = function() E.private[lower(E.PopupDialogs['INCOMPATIBLE_ADDON'].module)].enable = false; ReloadUI(); end, button3 = L["Disable Warning"], OnAlt = function () E:StaticPopup_Hide('INCOMPATIBLE_ADDON') E:StaticPopup_Show('DISABLE_INCOMPATIBLE_ADDON'); end, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs['PIXELPERFECT_CHANGED'] = { text = L["You have changed the Thin Border Theme option. You will have to complete the installation process to remove any graphical bugs."], button1 = ACCEPT, OnAccept = E.noop, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs['CONFIGAURA_SET'] = { text = L["Because of the mass confusion caused by the new aura system I've implemented a new step to the installation process. This is optional. If you like how your auras are setup go to the last step and click finished to not be prompted again. If for some reason you are prompted repeatedly please restart your game."], button1 = ACCEPT, OnAccept = E.noop, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs['FAILED_UISCALE'] = { text = L["You have changed your UIScale, however you still have the AutoScale option enabled in ElvUI. Press accept if you would like to disable the Auto Scale option."], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() E.global.general.autoScale = false; ReloadUI(); end, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["CONFIG_RL"] = { text = L["One or more of the changes you have made require a ReloadUI."], button1 = ACCEPT, button2 = CANCEL, OnAccept = ReloadUI, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["GLOBAL_RL"] = { text = L["One or more of the changes you have made will effect all characters using this addon. You will have to reload the user interface to see the changes you have made."], button1 = ACCEPT, button2 = CANCEL, OnAccept = ReloadUI, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["PRIVATE_RL"] = { text = L["A setting you have changed will change an option for this character only. This setting that you have changed will be uneffected by changing user profiles. Changing this setting requires that you reload your User Interface."], button1 = ACCEPT, button2 = CANCEL, OnAccept = ReloadUI, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["RESET_UF_UNIT"] = { text = L["Accepting this will reset the UnitFrame settings for %s. Are you sure?"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function(self) if self.data and self.data.unit then local UF = E:GetModule('UnitFrames'); UF:ResetUnitSettings(self.data.unit); if self.data.mover then E:ResetMovers(self.data.mover); end if self.data.unit == 'raidpet' then UF:CreateAndUpdateHeaderGroup(self.data.unit, nil, nil, true); end if IsAddOnLoaded("ElvUI_Config") then local ACD = LibStub and LibStub("AceConfigDialog-3.0-ElvUI"); if ACD and ACD.OpenFrames and ACD.OpenFrames.ElvUI then ACD:SelectGroup("ElvUI", "unitframe", self.data.unit); end end else E:Print(L["Error resetting UnitFrame."]); end end, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["RESET_UF_AF"] = { text = L["Accepting this will reset your Filter Priority lists for all auras on UnitFrames. Are you sure?"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() for unitName, content in pairs(E.db.unitframe.units) do if content.buffs then content.buffs.priority = P.unitframe.units[unitName].buffs.priority end if content.debuffs then content.debuffs.priority = P.unitframe.units[unitName].debuffs.priority end if content.aurabar then content.aurabar.priority = P.unitframe.units[unitName].aurabar.priority end end end, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["RESET_NP_AF"] = { text = L["Accepting this will reset your Filter Priority lists for all auras on NamePlates. Are you sure?"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() for unitType, content in pairs(E.db.nameplates.units) do if content.buffs and content.buffs.filters then content.buffs.filters.priority = P.nameplates.units[unitType].buffs.filters.priority end if content.debuffs and content.debuffs.filters then content.debuffs.filters.priority = P.nameplates.units[unitType].debuffs.filters.priority end end end, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["KEYBIND_MODE"] = { text = L["Hover your mouse over any actionbutton or spellbook button to bind it. Press the escape key or right click to clear the current actionbutton's keybinding."], button1 = L["Save"], button2 = L["Discard"], OnAccept = function() E:GetModule('ActionBars'):DeactivateBindMode(true) end, OnCancel = function() E:GetModule('ActionBars'):DeactivateBindMode(false) end, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["DELETE_GRAYS"] = { text = format("|cffff0000%s|r", L["Delete gray items?"]), button1 = YES, button2 = NO, OnAccept = function() E:GetModule('Bags'):VendorGrays(true) end, OnShow = function(self) MoneyFrame_Update(self.moneyFrame, E.PopupDialogs["DELETE_GRAYS"].Money); end, timeout = 4, whileDead = 1, hideOnEscape = false, hasMoneyFrame = 1, } E.PopupDialogs["BUY_BANK_SLOT"] = { text = CONFIRM_BUY_BANK_SLOT, button1 = YES, button2 = NO, OnAccept = PurchaseSlot, OnShow = function(self) MoneyFrame_Update(self.moneyFrame, GetBankSlotCost()) end, hasMoneyFrame = 1, timeout = 0, hideOnEscape = 1, } E.PopupDialogs["CANNOT_BUY_BANK_SLOT"] = { text = L["Can't buy anymore slots!"], button1 = ACCEPT, timeout = 0, whileDead = 1, } E.PopupDialogs["NO_BANK_BAGS"] = { text = L["You must purchase a bank slot first!"], button1 = ACCEPT, timeout = 0, whileDead = 1, } E.PopupDialogs["RESETUI_CHECK"] = { text = L["Are you sure you want to reset every mover back to it's default position?"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() E:ResetAllUI() end, timeout = 0, whileDead = 1, } E.PopupDialogs["HARLEM_SHAKE"] = { text = L["ElvUI needs to perform database optimizations please be patient."], button1 = OKAY, OnAccept = function() if E.isMassiveShaking then E:StopHarlemShake() else E:BeginHarlemShake() return true end end, timeout = 0, whileDead = 1, } E.PopupDialogs["HELLO_KITTY"] = { text = L["ElvUI needs to perform database optimizations please be patient."], button1 = OKAY, OnAccept = function() E:SetupHelloKitty() end, timeout = 0, whileDead = 1, } E.PopupDialogs["HELLO_KITTY_END"] = { text = L["Do you enjoy the new ElvUI?"], button1 = L["Yes, Keep Changes!"], button2 = L["No, Revert Changes!"], OnAccept = function() E:Print(L["Type /hellokitty to revert to old settings."]) StopMusic() SetCVar("Sound_EnableAllSound", E.oldEnableAllSound) SetCVar("Sound_EnableMusic", E.oldEnableMusic) end, OnCancel = function() E:RestoreHelloKitty() StopMusic() SetCVar("Sound_EnableAllSound", E.oldEnableAllSound) SetCVar("Sound_EnableMusic", E.oldEnableMusic) end, timeout = 0, whileDead = 1, } E.PopupDialogs["DISBAND_RAID"] = { text = L["Are you sure you want to disband the group?"], button1 = ACCEPT, button2 = CANCEL, OnAccept = function() E:GetModule('Misc'):DisbandRaidGroup() end, timeout = 0, whileDead = 1, } E.PopupDialogs["CONFIRM_LOOT_DISTRIBUTION"] = { text = CONFIRM_LOOT_DISTRIBUTION, button1 = YES, button2 = NO, timeout = 0, hideOnEscape = 1, } E.PopupDialogs["RESET_PROFILE_PROMPT"] = { text = L["Are you sure you want to reset all the settings on this profile?"], button1 = YES, button2 = NO, timeout = 0, hideOnEscape = 1, OnAccept = function() E:ResetProfile() end, } E.PopupDialogs["WARNING_BLIZZARD_ADDONS"] = { text = L["It appears one of your AddOns have disabled the AddOn Blizzard_CompactRaidFrames. This can cause errors and other issues. The AddOn will now be re-enabled."], button1 = OKAY, timeout = 0, hideOnEscape = false, OnAccept = function() EnableAddOn("Blizzard_CompactRaidFrames"); ReloadUI(); end, } E.PopupDialogs['APPLY_FONT_WARNING'] = { text = L["Are you sure you want to apply this font to all ElvUI elements?"], OnAccept = function() local font = E.db.general.font local fontSize = E.db.general.fontSize E.db.bags.itemLevelFont = font E.db.bags.itemLevelFontSize = fontSize E.db.bags.countFont = font E.db.bags.countFontSize = fontSize E.db.nameplates.font = font --E.db.nameplate.fontSize = fontSize --Dont use this because nameplate font it somewhat smaller than the rest of the font sizes --E.db.nameplate.buffs.font = font --E.db.nameplate.buffs.fontSize = fontSize --Dont use this because nameplate font it somewhat smaller than the rest of the font sizes --E.db.nameplate.debuffs.font = font --E.db.nameplate.debuffs.fontSize = fontSize --Dont use this because nameplate font it somewhat smaller than the rest of the font sizes E.db.actionbar.font = font --E.db.actionbar.fontSize = fontSize --This may not look good if a big font size is chosen E.db.auras.font = font E.db.auras.fontSize = fontSize E.db.chat.font = font E.db.chat.fontSize = fontSize E.db.chat.tabFont = font E.db.chat.tapFontSize = fontSize E.db.datatexts.font = font E.db.datatexts.fontSize = fontSize E.db.general.minimap.locationFont = font E.db.tooltip.font = font E.db.tooltip.fontSize = fontSize E.db.tooltip.headerFontSize = fontSize E.db.tooltip.textFontSize = fontSize E.db.tooltip.smallTextFontSize = fontSize E.db.tooltip.healthBar.font = font --E.db.tooltip.healthbar.fontSize = fontSize -- Size is smaller than default E.db.unitframe.font = font --E.db.unitframe.fontSize = fontSize -- Size is smaller than default E.db.unitframe.units.party.rdebuffs.font = font E.db.unitframe.units.raid.rdebuffs.font = font E.db.unitframe.units.raid40.rdebuffs.font = font E:UpdateAll(true) end, OnCancel = function() E:StaticPopup_Hide('APPLY_FONT_WARNING'); end, button1 = YES, button2 = CANCEL, timeout = 0, whileDead = 1, hideOnEscape = false, } E.PopupDialogs["ELVUI_INFORM_NEW_CHANGES"] = { text = "There have been some major changes in this version of ElvUI. Style Filters have been introduced to NamePlates, and the Aura Filtering system for NamePlates and UnitFrames has been reworked. We recommend you read the following forum post for more information.", OnShow = function(self) self.editBox:SetAutoFocus(false) self.editBox.width = self.editBox:GetWidth() self.editBox:Width(300) self.editBox:SetText("https://www.tukui.org/forum/viewtopic.php?f=8&t=286") self.editBox:HighlightText() self.button1:Disable() self.HideOrig = self.Hide self.Hide = E.noop ChatEdit_FocusActiveWindow(); end, OnHide = function(self) self.editBox:Width(self.editBox.width or 50) self.editBox.width = nil end, EditBoxOnTextChanged = function(self) if(self:GetText() ~= "https://www.tukui.org/forum/viewtopic.php?f=8&t=286") then self:SetText("https://www.tukui.org/forum/viewtopic.php?f=8&t=286") end self:HighlightText() self:ClearFocus() ChatEdit_FocusActiveWindow(); end, OnEditFocusGained = function(self) self:HighlightText() end, OnCancel = function(self, _, reason) if ( reason == "timeout" ) then self.button1:Enable(); end end, OnAccept = function(self) self.Hide = self.HideOrig self.HideOrig = nil E:StaticPopup_Hide('ELVUI_INFORM_NEW_CHANGES') end, button1 = OKAY, showAlert = 1, timeout = 15, hideOnEscape = 0, hasEditBox = 1, } E.PopupDialogs["MODULE_COPY_CONFIRM"] = { button1 = ACCEPT, button2 = CANCEL, timeout = 0, whileDead = 1, hideOnEscape = false, } local MAX_STATIC_POPUPS = 4 function E:StaticPopup_OnShow() PlaySound(850); --IG_MAINMENU_OPEN local dialog = E.PopupDialogs[self.which]; local OnShow = dialog.OnShow; if ( OnShow ) then OnShow(self, self.data); end if ( dialog.hasMoneyInputFrame ) then _G[self:GetName().."MoneyInputFrameGold"]:SetFocus(); end if ( dialog.enterClicksFirstButton ) then self:SetScript("OnKeyDown", E.StaticPopup_OnKeyDown); end -- boost static popups over ace gui if IsAddOnLoaded("ElvUI_Config") then local ACD = LibStub and LibStub("AceConfigDialog-3.0-ElvUI"); if ACD and ACD.OpenFrames and ACD.OpenFrames.ElvUI then self.frameStrataIncreased = true self:SetFrameStrata("FULLSCREEN_DIALOG") local popupFrameLevel = self:GetFrameLevel() if popupFrameLevel < 100 then self:SetFrameLevel(popupFrameLevel+100) end end end end function E:StaticPopup_EscapePressed() local closed = nil; for _, frame in pairs(E.StaticPopup_DisplayedFrames) do if( frame:IsShown() and frame.hideOnEscape ) then local standardDialog = E.PopupDialogs[frame.which]; if ( standardDialog ) then local OnCancel = standardDialog.OnCancel; local noCancelOnEscape = standardDialog.noCancelOnEscape; if ( OnCancel and not noCancelOnEscape) then OnCancel(frame, frame.data, "clicked"); end frame:Hide(); else E:StaticPopupSpecial_Hide(frame); end closed = 1; end end return closed; end function E:StaticPopupSpecial_Hide(frame) frame:Hide(); E:StaticPopup_CollapseTable(); end function E:StaticPopup_CollapseTable() local displayedFrames = E.StaticPopup_DisplayedFrames; local index = #displayedFrames; while ( ( index >= 1 ) and ( not displayedFrames[index]:IsShown() ) ) do tremove(displayedFrames, index); index = index - 1; end end function E:StaticPopup_SetUpPosition(dialog) if ( not tContains(E.StaticPopup_DisplayedFrames, dialog) ) then local lastFrame = E.StaticPopup_DisplayedFrames[#E.StaticPopup_DisplayedFrames]; if ( lastFrame ) then dialog:Point("TOP", lastFrame, "BOTTOM", 0, -4); else dialog:Point("TOP", E.UIParent, "TOP", 0, -100); end tinsert(E.StaticPopup_DisplayedFrames, dialog); end end function E:StaticPopupSpecial_Show(frame) if ( frame.exclusive ) then E:StaticPopup_HideExclusive(); end E:StaticPopup_SetUpPosition(frame); frame:Show(); end function E:StaticPopupSpecial_Hide(frame) frame:Hide(); E:StaticPopup_CollapseTable(); end --Used to figure out if we can resize a frame function E:StaticPopup_IsLastDisplayedFrame(frame) for i=#E.StaticPopup_DisplayedFrames, 1, -1 do local popup = E.StaticPopup_DisplayedFrames[i]; if ( popup:IsShown() ) then return frame == popup end end return false; end function E:StaticPopup_OnKeyDown(key) if ( GetBindingFromClick(key) == "TOGGLEGAMEMENU" ) then return E:StaticPopup_EscapePressed(); elseif ( GetBindingFromClick(key) == "SCREENSHOT" ) then RunBinding("SCREENSHOT"); return; end local dialog = E.PopupDialogs[self.which]; if ( dialog ) then if ( key == "ENTER" and dialog.enterClicksFirstButton ) then local frameName = self:GetName(); local button; local i = 1; while ( true ) do button = _G[frameName.."Button"..i]; if ( button ) then if ( button:IsShown() ) then E:StaticPopup_OnClick(self, i); return; end i = i + 1; else break; end end end end end function E:StaticPopup_OnHide() PlaySound(851); --IG_MAINMENU_CLOSE E:StaticPopup_CollapseTable(); local dialog = E.PopupDialogs[self.which]; local OnHide = dialog.OnHide; if ( OnHide ) then OnHide(self, self.data); end self.extraFrame:Hide(); if ( dialog.enterClicksFirstButton ) then self:SetScript("OnKeyDown", nil); end -- static popup was boosted over ace gui, set it back to normal if self.frameStrataIncreased then self.frameStrataIncreased = nil self:SetFrameStrata("DIALOG") local popupFrameLevel = self:GetFrameLevel() if popupFrameLevel > 100 then self:SetFrameLevel(popupFrameLevel-100) end end end function E:StaticPopup_OnUpdate(elapsed) if ( self.timeleft and self.timeleft > 0 ) then local which = self.which; local timeleft = self.timeleft - elapsed; if ( timeleft <= 0 ) then if ( not E.PopupDialogs[which].timeoutInformationalOnly ) then self.timeleft = 0; local OnCancel = E.PopupDialogs[which].OnCancel; if ( OnCancel ) then OnCancel(self, self.data, "timeout"); end self:Hide(); end return; end self.timeleft = timeleft; end if ( self.startDelay ) then local which = self.which; local timeleft = self.startDelay - elapsed; if ( timeleft <= 0 ) then self.startDelay = nil; local text = _G[self:GetName().."Text"]; text:SetFormattedText(E.PopupDialogs[which].text, text.text_arg1, text.text_arg2); local button1 = _G[self:GetName().."Button1"]; button1:Enable(); StaticPopup_Resize(self, which); return; end self.startDelay = timeleft; end local onUpdate = E.PopupDialogs[self.which].OnUpdate; if ( onUpdate ) then onUpdate(self, elapsed); end end function E:StaticPopup_OnClick(index) if ( not self:IsShown() ) then return; end local which = self.which; local info = E.PopupDialogs[which]; if ( not info ) then return nil; end local hide = true; if ( index == 1 ) then local OnAccept = info.OnAccept; if ( OnAccept ) then hide = not OnAccept(self, self.data, self.data2); end elseif ( index == 3 ) then local OnAlt = info.OnAlt; if ( OnAlt ) then OnAlt(self, self.data, "clicked"); end else local OnCancel = info.OnCancel; if ( OnCancel ) then hide = not OnCancel(self, self.data, "clicked"); end end if ( hide and (which == self.which) ) then -- can self.which change inside one of the On* functions??? self:Hide(); end end function E:StaticPopup_EditBoxOnEnterPressed() local EditBoxOnEnterPressed, which, dialog; local parent = self:GetParent(); if ( parent.which ) then which = parent.which; dialog = parent; elseif ( parent:GetParent().which ) then -- This is needed if this is a money input frame since it's nested deeper than a normal edit box which = parent:GetParent().which; dialog = parent:GetParent(); end if ( not self.autoCompleteParams or not AutoCompleteEditBox_OnEnterPressed(self) ) then EditBoxOnEnterPressed = E.PopupDialogs[which].EditBoxOnEnterPressed; if ( EditBoxOnEnterPressed ) then EditBoxOnEnterPressed(self, dialog.data); end end end function E:StaticPopup_EditBoxOnEscapePressed() local EditBoxOnEscapePressed = E.PopupDialogs[self:GetParent().which].EditBoxOnEscapePressed; if ( EditBoxOnEscapePressed ) then EditBoxOnEscapePressed(self, self:GetParent().data); end end function E:StaticPopup_EditBoxOnTextChanged(userInput) if ( not self.autoCompleteParams or not AutoCompleteEditBox_OnTextChanged(self, userInput) ) then local EditBoxOnTextChanged = E.PopupDialogs[self:GetParent().which].EditBoxOnTextChanged; if ( EditBoxOnTextChanged ) then EditBoxOnTextChanged(self, self:GetParent().data); end end end function E:StaticPopup_FindVisible(which, data) local info = E.PopupDialogs[which]; if ( not info ) then return nil; end for index = 1, MAX_STATIC_POPUPS, 1 do local frame = _G["ElvUI_StaticPopup"..index]; if ( frame:IsShown() and (frame.which == which) and (not info.multiple or (frame.data == data)) ) then return frame; end end return nil; end function E:StaticPopup_Resize(dialog, which) local info = E.PopupDialogs[which]; if ( not info ) then return nil; end local text = _G[dialog:GetName().."Text"]; local editBox = _G[dialog:GetName().."EditBox"]; local button1 = _G[dialog:GetName().."Button1"]; local maxHeightSoFar, maxWidthSoFar = (dialog.maxHeightSoFar or 0), (dialog.maxWidthSoFar or 0); local width = 320; if ( dialog.numButtons == 3 ) then width = 440; elseif (info.showAlert or info.showAlertGear or info.closeButton) then -- Widen width = 420; elseif ( info.editBoxWidth and info.editBoxWidth > 260 ) then width = width + (info.editBoxWidth - 260); end if ( width > maxWidthSoFar ) then dialog:Width(width); dialog.maxWidthSoFar = width; end local height = 32 + text:GetHeight() + 8 + button1:GetHeight(); if ( info.hasEditBox ) then height = height + 8 + editBox:GetHeight(); elseif ( info.hasMoneyFrame ) then height = height + 16; elseif ( info.hasMoneyInputFrame ) then height = height + 22; end if ( info.hasItemFrame ) then height = height + 64; end if ( height > maxHeightSoFar ) then dialog:Height(height); dialog.maxHeightSoFar = height; end end function E:StaticPopup_OnEvent() self.maxHeightSoFar = 0; E:StaticPopup_Resize(self, self.which); end local tempButtonLocs = {}; --So we don't make a new table each time. function E:StaticPopup_Show(which, text_arg1, text_arg2, data) local info = E.PopupDialogs[which]; if ( not info ) then return nil; end if ( UnitIsDeadOrGhost("player") and not info.whileDead ) then if ( info.OnCancel ) then info.OnCancel(); end return nil; end if ( InCinematic() and not info.interruptCinematic ) then if ( info.OnCancel ) then info.OnCancel(); end return nil; end if ( info.cancels ) then for index = 1, MAX_STATIC_POPUPS, 1 do local frame = _G["ElvUI_StaticPopup"..index]; if ( frame:IsShown() and (frame.which == info.cancels) ) then frame:Hide(); local OnCancel = E.PopupDialogs[frame.which].OnCancel; if ( OnCancel ) then OnCancel(frame, frame.data, "override"); end end end end -- Pick a free dialog to use, find an open dialog of the requested type local dialog = E:StaticPopup_FindVisible(which, data); if ( dialog ) then if ( not info.noCancelOnReuse ) then local OnCancel = info.OnCancel; if ( OnCancel ) then OnCancel(dialog, dialog.data, "override"); end end dialog:Hide(); end if ( not dialog ) then -- Find a free dialog local index = 1; if ( info.preferredIndex ) then index = info.preferredIndex; end for i = index, MAX_STATIC_POPUPS do local frame = _G["ElvUI_StaticPopup"..i]; if ( not frame:IsShown() ) then dialog = frame; break; end end --If dialog not found and there's a preferredIndex then try to find an available frame before the preferredIndex if ( not dialog and info.preferredIndex ) then for i = 1, info.preferredIndex do local frame = _G["ElvUI_StaticPopup"..i]; if ( not frame:IsShown() ) then dialog = frame; break; end end end end if ( not dialog ) then if ( info.OnCancel ) then info.OnCancel(); end return nil; end dialog.maxHeightSoFar, dialog.maxWidthSoFar = 0, 0; -- Set the text of the dialog local text = _G[dialog:GetName().."Text"]; text:SetFormattedText(info.text, text_arg1, text_arg2); -- Show or hide the close button if ( info.closeButton ) then local closeButton = _G[dialog:GetName().."CloseButton"]; if ( info.closeButtonIsHide ) then closeButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-HideButton-Up"); closeButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-HideButton-Down"); else closeButton:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up"); closeButton:SetPushedTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Down"); end closeButton:Show(); else _G[dialog:GetName().."CloseButton"]:Hide(); end -- Set the editbox of the dialog local editBox = _G[dialog:GetName().."EditBox"]; if ( info.hasEditBox ) then editBox:Show(); if ( info.maxLetters ) then editBox:SetMaxLetters(info.maxLetters); editBox:SetCountInvisibleLetters(info.countInvisibleLetters); end if ( info.maxBytes ) then editBox:SetMaxBytes(info.maxBytes); end editBox:SetText(""); if ( info.editBoxWidth ) then editBox:Width(info.editBoxWidth); else editBox:Width(130); end else editBox:Hide(); end -- Show or hide money frame if ( info.hasMoneyFrame ) then _G[dialog:GetName().."MoneyFrame"]:Show(); _G[dialog:GetName().."MoneyInputFrame"]:Hide(); elseif ( info.hasMoneyInputFrame ) then local moneyInputFrame = _G[dialog:GetName().."MoneyInputFrame"]; moneyInputFrame:Show(); _G[dialog:GetName().."MoneyFrame"]:Hide(); -- Set OnEnterPress for money input frames if ( info.EditBoxOnEnterPressed ) then moneyInputFrame.gold:SetScript("OnEnterPressed", E.StaticPopup_EditBoxOnEnterPressed); moneyInputFrame.silver:SetScript("OnEnterPressed", E.StaticPopup_EditBoxOnEnterPressed); moneyInputFrame.copper:SetScript("OnEnterPressed", E.StaticPopup_EditBoxOnEnterPressed); else moneyInputFrame.gold:SetScript("OnEnterPressed", nil); moneyInputFrame.silver:SetScript("OnEnterPressed", nil); moneyInputFrame.copper:SetScript("OnEnterPressed", nil); end else _G[dialog:GetName().."MoneyFrame"]:Hide(); _G[dialog:GetName().."MoneyInputFrame"]:Hide(); end -- Show or hide item button if ( info.hasItemFrame ) then _G[dialog:GetName().."ItemFrame"]:Show(); if ( data and type(data) == "table" ) then _G[dialog:GetName().."ItemFrame"].link = data.link _G[dialog:GetName().."ItemFrameIconTexture"]:SetTexture(data.texture); local nameText = _G[dialog:GetName().."ItemFrameText"]; nameText:SetTextColor(unpack(data.color or {1, 1, 1, 1})); nameText:SetText(data.name); if ( data.count and data.count > 1 ) then _G[dialog:GetName().."ItemFrameCount"]:SetText(data.count); _G[dialog:GetName().."ItemFrameCount"]:Show(); else _G[dialog:GetName().."ItemFrameCount"]:Hide(); end end else _G[dialog:GetName().."ItemFrame"]:Hide(); end -- Set the miscellaneous variables for the dialog dialog.which = which; dialog.timeleft = info.timeout; dialog.hideOnEscape = info.hideOnEscape; dialog.exclusive = info.exclusive; dialog.enterClicksFirstButton = info.enterClicksFirstButton; -- Clear out data dialog.data = data; -- Set the buttons of the dialog local button1 = _G[dialog:GetName().."Button1"]; local button2 = _G[dialog:GetName().."Button2"]; local button3 = _G[dialog:GetName().."Button3"]; do --If there is any recursion in this block, we may get errors (tempButtonLocs is static). If you have to recurse, we'll have to create a new table each time. assert(#tempButtonLocs == 0); --If this fails, we're recursing. (See the table.wipe at the end of the block) tinsert(tempButtonLocs, button1); tinsert(tempButtonLocs, button2); tinsert(tempButtonLocs, button3); for i=#tempButtonLocs, 1, -1 do --Do this stuff before we move it. (This is why we go back-to-front) tempButtonLocs[i]:SetText(info["button"..i]); tempButtonLocs[i]:Hide(); tempButtonLocs[i]:ClearAllPoints(); --Now we possibly remove it. if ( not (info["button"..i] and ( not info["DisplayButton"..i] or info["DisplayButton"..i](dialog))) ) then tremove(tempButtonLocs, i); end end local numButtons = #tempButtonLocs; --Save off the number of buttons. dialog.numButtons = numButtons; if ( numButtons == 3 ) then tempButtonLocs[1]:Point("BOTTOMRIGHT", dialog, "BOTTOM", -72, 16); elseif ( numButtons == 2 ) then tempButtonLocs[1]:Point("BOTTOMRIGHT", dialog, "BOTTOM", -6, 16); elseif ( numButtons == 1 ) then tempButtonLocs[1]:Point("BOTTOM", dialog, "BOTTOM", 0, 16); end for i=1, numButtons do if ( i > 1 ) then tempButtonLocs[i]:Point("LEFT", tempButtonLocs[i-1], "RIGHT", 13, 0); end local width = tempButtonLocs[i]:GetTextWidth(); if ( width > 110 ) then tempButtonLocs[i]:Width(width + 20); else tempButtonLocs[i]:Width(120); end tempButtonLocs[i]:Enable(); tempButtonLocs[i]:Show(); end wipe(tempButtonLocs); end -- Show or hide the alert icon local alertIcon = _G[dialog:GetName().."AlertIcon"]; if ( info.showAlert ) then alertIcon:SetTexture(STATICPOPUP_TEXTURE_ALERT); if ( button3:IsShown() )then alertIcon:Point("LEFT", 24, 10); else alertIcon:Point("LEFT", 24, 0); end alertIcon:Show(); elseif ( info.showAlertGear ) then alertIcon:SetTexture(STATICPOPUP_TEXTURE_ALERTGEAR); if ( button3:IsShown() )then alertIcon:Point("LEFT", 24, 0); else alertIcon:Point("LEFT", 24, 0); end alertIcon:Show(); else alertIcon:SetTexture(); alertIcon:Hide(); end if ( info.StartDelay ) then dialog.startDelay = info.StartDelay(); button1:Disable(); else dialog.startDelay = nil; button1:Enable(); end editBox.autoCompleteParams = info.autoCompleteParams; editBox.autoCompleteRegex = info.autoCompleteRegex; editBox.autoCompleteFormatRegex = info.autoCompleteFormatRegex; editBox.addHighlightedText = true; -- Finally size and show the dialog E:StaticPopup_SetUpPosition(dialog); dialog:Show(); E:StaticPopup_Resize(dialog, which); if ( info.sound ) then PlaySound(info.sound); end return dialog; end function E:StaticPopup_Hide(which, data) for index = 1, MAX_STATIC_POPUPS, 1 do local dialog = _G["ElvUI_StaticPopup"..index]; if ( (dialog.which == which) and (not data or (data == dialog.data)) ) then dialog:Hide(); end end end function E:Contruct_StaticPopups() E.StaticPopupFrames = {} local S = self:GetModule('Skins') for index = 1, MAX_STATIC_POPUPS do E.StaticPopupFrames[index] = CreateFrame('Frame', 'ElvUI_StaticPopup'..index, E.UIParent, 'StaticPopupTemplate') E.StaticPopupFrames[index]:SetID(index) --Fix Scripts E.StaticPopupFrames[index]:SetScript('OnShow', E.StaticPopup_OnShow) E.StaticPopupFrames[index]:SetScript('OnHide', E.StaticPopup_OnHide) E.StaticPopupFrames[index]:SetScript('OnUpdate', E.StaticPopup_OnUpdate) E.StaticPopupFrames[index]:SetScript('OnEvent', E.StaticPopup_OnEvent) for i = 1, 3 do _G['ElvUI_StaticPopup'..index..'Button'..i]:SetScript('OnClick', function(button) E.StaticPopup_OnClick(button:GetParent(), button:GetID()) end) end _G['ElvUI_StaticPopup'..index..'EditBox']:SetScript('OnEnterPressed', E.StaticPopup_EditBoxOnEnterPressed) _G['ElvUI_StaticPopup'..index..'EditBox']:SetScript('OnEscapePressed', E.StaticPopup_EditBoxOnEscapePressed) _G['ElvUI_StaticPopup'..index..'EditBox']:SetScript('OnTextChanged', E.StaticPopup_EditBoxOnTextChanged) --Skin E.StaticPopupFrames[index]:SetTemplate('Transparent') for i = 1, 3 do S:HandleButton(_G["ElvUI_StaticPopup"..index.."Button"..i]) end _G["ElvUI_StaticPopup"..index.."EditBox"]:SetFrameLevel(_G["ElvUI_StaticPopup"..index.."EditBox"]:GetFrameLevel()+1) S:HandleEditBox(_G["ElvUI_StaticPopup"..index.."EditBox"]) S:HandleEditBox(_G["ElvUI_StaticPopup"..index.."MoneyInputFrameGold"]) S:HandleEditBox(_G["ElvUI_StaticPopup"..index.."MoneyInputFrameSilver"]) S:HandleEditBox(_G["ElvUI_StaticPopup"..index.."MoneyInputFrameCopper"]) _G["ElvUI_StaticPopup"..index.."EditBox"].backdrop:Point("TOPLEFT", -2, -4) _G["ElvUI_StaticPopup"..index.."EditBox"].backdrop:Point("BOTTOMRIGHT", 2, 4) _G["ElvUI_StaticPopup"..index.."ItemFrameNameFrame"]:Kill() _G["ElvUI_StaticPopup"..index.."ItemFrame"]:GetNormalTexture():Kill() _G["ElvUI_StaticPopup"..index.."ItemFrame"]:SetTemplate("Default") _G["ElvUI_StaticPopup"..index.."ItemFrame"]:StyleButton() _G["ElvUI_StaticPopup"..index.."ItemFrameIconTexture"]:SetTexCoord(unpack(E.TexCoords)) _G["ElvUI_StaticPopup"..index.."ItemFrameIconTexture"]:SetInside() end E:SecureHook('StaticPopup_SetUpPosition') E:SecureHook('StaticPopup_CollapseTable') end
local key = ModPath .. ' ' .. RequiredScript if _G[key] then return else _G[key] = true end local table_insert = table.insert local table_remove = table.remove local WGT_OCCLUDED = 40000000000000 local WGT_UNKNOWN = 39000000000000 local max_tasks = FullSpeedSwarm.settings.max_tasks function FullSpeedSwarmUpdateMaxTasks(new_value) max_tasks = new_value end function EnemyManager:_update_queued_tasks(t) local qt = self._queued_tasks local n = max_tasks == 0 and #qt or max_tasks local i_task = 1 local task_data = qt[1] while task_data do if task_data.t == nil or t > task_data.t then self:_execute_queued_task(i_task) n = n - 1 if n <= 0 then break end else i_task = i_task + 1 end task_data = qt[i_task] end local all_clbks = self._delayed_clbks if all_clbks[1] and t > all_clbks[1][2] then local clbk = table_remove(all_clbks, 1)[3] clbk() end end local fs_original_enemymanager_initenemydata = EnemyManager._init_enemy_data function EnemyManager:_init_enemy_data() fs_original_enemymanager_initenemydata(self) self._enemy_data.announcer_data = {} self.iter_lod = 1 self.lowest_occluded_rank = 1 self._gfx_lod_data.entries.last_check_t = {} end local mvec3_dir = mvector3.direction local mvec3_dot = mvector3.dot local tmp_vec1 = Vector3() local frm = 1 local lod_step = tonumber(FullSpeedSwarm.settings.lod_updater) if lod_step < 3 then function EnemyManager:_update_gfx_lod() local managers = managers if self._gfx_lod_data.enabled and managers.navigation:is_data_ready() then local camera_rot = managers.viewport:get_current_camera_rotation() if camera_rot then local cam_pos local pl_fwd = camera_rot:y() local player = managers.player:player_unit() if player then cam_pos = player:movement():m_head_pos() else cam_pos = managers.viewport:get_current_camera_position() end local entries = self._gfx_lod_data.entries local states = entries.states local nr = #states local anim_lod = managers.user:get_setting('video_animation_lod') local nr_lod_1 = self._nr_i_lod[anim_lod][1] local nr_lod_2 = self._nr_i_lod[anim_lod][2] local nr_lod_total = nr_lod_1 + nr_lod_2 local units = entries.units local trackers = entries.trackers local com = entries.com local last_check_t = entries.last_check_t local unit_occluded = Unit.occluded local occ_skip_units = managers.occlusion._skip_occlusion local World = World local world_in_view_with_options = World.in_view_with_options local sorted_index = self._gfx_lod_data.prio_i local weights = self._gfx_lod_data.prio_weights local lowest_occluded_rank = self.lowest_occluded_rank frm = (frm + 1) % lod_step for s = lowest_occluded_rank + frm, nr, lod_step do local i = sorted_index[s] local unit = units[i] if not unit_occluded(unit) and world_in_view_with_options(World, com[i], 0, 110, 18000) then sorted_index[s], sorted_index[lowest_occluded_rank] = sorted_index[lowest_occluded_rank], sorted_index[s] lowest_occluded_rank = lowest_occluded_rank + 1 weights[i] = WGT_UNKNOWN states[i] = 2 unit:base():set_visibility_state(2) end end local max_iter = nr / 25 local threshold_t = max_iter * 0.02 local s = self.iter_lod local looping = false repeat local i max_iter = max_iter - 1 while true do if s >= lowest_occluded_rank or s > nr then s = 1 looping = true break end i = sorted_index[s] if self._t - last_check_t[i] > threshold_t then break end s = s + 1 end if looping then break end last_check_t[i] = self._t local my_wgt local unit = units[i] if not (occ_skip_units[unit:key()] or not unit_occluded(unit) and world_in_view_with_options(World, com[i], 0, 120, 18000)) then my_wgt = WGT_OCCLUDED else my_wgt = mvec3_dir(tmp_vec1, cam_pos, com[i]) local dot = mvec3_dot(tmp_vec1, pl_fwd) my_wgt = my_wgt * my_wgt * (1 - dot) end local new_rank local weight_i = weights[i] if my_wgt == weight_i then new_rank = s elseif my_wgt > weight_i then new_rank = nr for s2 = s, nr - 1 do local si2 = sorted_index[s2 + 1] if weights[si2] >= my_wgt then new_rank = s2 break else sorted_index[s2] = si2 end end if s <= nr_lod_total and lowest_occluded_rank > nr_lod_total then states[nr_lod_total] = 2 units[nr_lod_total]:base():set_visibility_state(2) if s <= nr_lod_1 and lowest_occluded_rank > nr_lod_1 then states[nr_lod_1] = 1 units[nr_lod_1]:base():set_visibility_state(1) end end sorted_index[new_rank] = i else new_rank = 1 for s2 = s, 2, -1 do local si2 = sorted_index[s2 - 1] if weights[si2] <= my_wgt then new_rank = s2 break else sorted_index[s2] = si2 end end if s > nr_lod_1 then local nr_lod_1_p_1 = nr_lod_1 + 1 if lowest_occluded_rank > nr_lod_1_p_1 then states[nr_lod_1_p_1] = 2 units[nr_lod_1_p_1]:base():set_visibility_state(2) if s > nr_lod_total then local nr_lod_total_p_1 = nr_lod_total + 1 if lowest_occluded_rank > nr_lod_total_p_1 then states[nr_lod_total_p_1] = 3 units[nr_lod_total_p_1]:base():set_visibility_state(3) end end end end sorted_index[new_rank] = i end if new_rank <= s then s = s + 1 end local new_state if my_wgt == WGT_OCCLUDED then new_state = false elseif new_rank <= nr_lod_total then new_state = new_rank <= nr_lod_1 and 1 or 2 else new_state = 3 end if new_state ~= states[i] then states[i] = new_state unit:base():set_visibility_state(new_state) if not new_state then lowest_occluded_rank = lowest_occluded_rank - 1 end end weights[i] = my_wgt until max_iter <= 0 self.iter_lod = s self.lowest_occluded_rank = lowest_occluded_rank end end end function EnemyManager:_create_unit_gfx_lod_data(unit) if not unit:alive() then return end local gfx_lod_data = self._gfx_lod_data local lod_entries = gfx_lod_data.entries table_insert(lod_entries.units, unit) table_insert(lod_entries.states, 42) table_insert(lod_entries.move_ext, unit:movement()) table_insert(lod_entries.trackers, unit:movement():nav_tracker()) table_insert(lod_entries.com, unit:movement():m_com()) table_insert(lod_entries.last_check_t, 0) local weights = gfx_lod_data.prio_weights table_insert(weights, WGT_UNKNOWN) local sorted_index = gfx_lod_data.prio_i table_insert(sorted_index, self.lowest_occluded_rank, #weights) self.lowest_occluded_rank = self.lowest_occluded_rank + 1 end function EnemyManager:_destroy_unit_gfx_lod_data(u_key) local gfx_lod_data = self._gfx_lod_data local lod_entries = gfx_lod_data.entries local units = lod_entries.units local nr_entries = #units for i = 1, nr_entries do local unit = units[i] if u_key == unit:key() then local ub = unit:base() if ub._tweak_table == 'sniper' then ub:set_visibility_state(1) end local sorted_index = gfx_lod_data.prio_i for j = nr_entries, 1, -1 do local s = sorted_index[j] if s == nr_entries then for k = j, 1, -1 do if sorted_index[k] == i then sorted_index[j] = i table_remove(sorted_index, k) break end end break end if s == i then table_remove(sorted_index, j) for k = j - 1, 1, -1 do if sorted_index[k] == nr_entries then sorted_index[k] = i break end end break end end units[i] = units[nr_entries] table_remove(units) lod_entries.states[i] = lod_entries.states[nr_entries] table_remove(lod_entries.states) lod_entries.move_ext[i] = lod_entries.move_ext[nr_entries] table_remove(lod_entries.move_ext) lod_entries.trackers[i] = lod_entries.trackers[nr_entries] table_remove(lod_entries.trackers) lod_entries.com[i] = lod_entries.com[nr_entries] table_remove(lod_entries.com) if gfx_lod_data.prio_weights[i] ~= WGT_OCCLUDED and self.lowest_occluded_rank > 1 then self.lowest_occluded_rank = self.lowest_occluded_rank - 1 end gfx_lod_data.prio_weights[i] = gfx_lod_data.prio_weights[nr_entries] table_remove(gfx_lod_data.prio_weights) lod_entries.last_check_t[i] = lod_entries.last_check_t[nr_entries] table_remove(lod_entries.last_check_t) break end end end function EnemyManager:set_gfx_lod_enabled(state) if state then self._gfx_lod_data.enabled = state elseif self._gfx_lod_data.enabled then self._gfx_lod_data.enabled = state local entries = self._gfx_lod_data.entries local units = entries.units local states = entries.states local weights = self._gfx_lod_data.prio_weights for i, state in ipairs(states) do states[i] = 1 weights[i] = WGT_UNKNOWN units[i]:base():set_visibility_state(1) end end end end local fs_announcables = {} for ctype, tdc in pairs(tweak_data.character) do if type(tdc) == 'table' and tdc.announce_incomming then fs_announcables[ctype] = tdc.announce_incomming end end local fs_announcers = {} for ctype, tdc in pairs(tweak_data.character) do if type(tdc) == 'table' and tdc.chatter then for _, a in pairs(fs_announcables) do if tdc.chatter[a] then fs_announcers[ctype] = true break end end end end local fs_original_enemymanager_registerenemy = EnemyManager.register_enemy function EnemyManager:register_enemy(enemy) fs_original_enemymanager_registerenemy(self, enemy) local e_key = enemy:key() local u_data = self._enemy_data.unit_data[e_key] local _tweak_table = enemy:base()._tweak_table u_data.tweak_table = _tweak_table if fs_announcers[_tweak_table] then self._enemy_data.announcer_data[e_key] = u_data end enemy:movement().fs_do_track = u_data end local fs_original_enemymanager_onenemyunregistered = EnemyManager.on_enemy_unregistered function EnemyManager:on_enemy_unregistered(unit) fs_original_enemymanager_onenemyunregistered(self, unit) local u_key = unit:key() self._enemy_data.announcer_data[u_key] = nil local u_mov = unit:movement() u_mov.fs_do_track = nil if u_mov._cur_seg then FullSpeedSwarm.units_per_navseg[u_mov._cur_seg][u_key] = nil u_mov._cur_seg = nil end end function EnemyManager:all_enemy_announcers() return self._enemy_data.announcer_data end
-- Create a proxy on _G __index/__newindex to get direct access to registers without having -- to use registers lib directly. So instead of having registers.write("rax", 1) we can say rax = 1 local register_names = { ["rflags"] = true, ["eflags"] = true, ["rax"] = true, ["eax"] = true, ["ax"] = true, ["ah"] = true, ["al"] = true, ["rbx"] = true, ["ebx"] = true, ["bx"] = true, ["bh"] = true, ["bl"] = true, ["rcx"] = true, ["ecx"] = true, ["cx"] = true, ["ch"] = true, ["cl"] = true, ["rdx"] = true, ["edx"] = true, ["dx"] = true, ["dh"] = true, ["dl"] = true, ["rdi"] = true, ["edi"] = true, ["di"] = true, ["dil"] = true, ["rsi"] = true, ["esi"] = true, ["si"] = true, ["sil"] = true, ["rbp"] = true, ["ebp"] = true, ["bp"] = true, ["bpl"] = true, ["rsp"] = true, ["esp"] = true, ["sp"] = true, ["spl"] = true, ["rip"] = true, ["eip"] = true, ["r8"] = true, ["r8d"] = true, ["r8w"] = true, ["r8b"] = true, } local function IS_REGISTER(k) return register_names[string.lower(k)] == true end proxies.install({ __index = function(t, k) if IS_DEBUGGING and IS_REGISTER(k) then return registers.read(k) end return nil end, __newindex = function(t, k, v) if IS_DEBUGGING and IS_REGISTER(k) then registers.write(k, v) return true end return nil end, })
if not Utils:IsInGameState() then do return end end if not Utils:IsInHeist() then do return end end if not Network:is_server() then UT.showMessage("host only", UT.colors.error) do return end end local crosshairRay = Utils:GetCrosshairRay() if not crosshairRay then UT.showMessage("nothing to copy", UT.colors.warning) do return end end local unit = crosshairRay.unit if unit:base() or UT.Tables.bagsKeys[unit:name():key()] or UT.Tables.vehicles[unit:name():key()] then UT.showMessage("cannot copy this", UT.colors.error) do return end end if unit:network_sync() == "spawn" then UT.Construction.clipboard.synchronized = true else UT.Construction.clipboard.synchronized = false end UT.Construction.clipboard.unit = unit UT.Construction.clipboard.name = unit:name() UT.Construction.clipboard.key = unit:name():key() managers.hud:on_crit_confirmed() UT.playSound("box_tick")
-- -- Autogenerated by Thrift -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated -- local Thrift = require 'Thrift' local TType = Thrift.TType local TMessageType = Thrift.TMessageType local __TObject = Thrift.__TObject local TApplicationException = Thrift.TApplicationException local __TClient = Thrift.__TClient local __TProcessor = Thrift.__TProcessor local ttype = Thrift.ttype local ttable_size = Thrift.ttable_size local social_network_ttypes = require 'social_network_ttypes' local ServiceException = social_network_ttypes.ServiceException local Post = social_network_ttypes.Post -- HELPER FUNCTIONS AND STRUCTURES local WriteUserTimeline_args = __TObject:new{ req_id, post_id, user_id, timestamp, carrier } function WriteUserTimeline_args:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.req_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.I64 then self.post_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 3 then if ftype == TType.I64 then self.user_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 4 then if ftype == TType.I64 then self.timestamp = iprot:readI64() else iprot:skip(ftype) end elseif fid == 5 then if ftype == TType.MAP then self.carrier = {} local _ktype171, _vtype172, _size170 = iprot:readMapBegin() for _i=1,_size170 do local _key174 = iprot:readString() local _val175 = iprot:readString() self.carrier[_key174] = _val175 end iprot:readMapEnd() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function WriteUserTimeline_args:write(oprot) oprot:writeStructBegin('WriteUserTimeline_args') if self.req_id ~= nil then oprot:writeFieldBegin('req_id', TType.I64, 1) oprot:writeI64(self.req_id) oprot:writeFieldEnd() end if self.post_id ~= nil then oprot:writeFieldBegin('post_id', TType.I64, 2) oprot:writeI64(self.post_id) oprot:writeFieldEnd() end if self.user_id ~= nil then oprot:writeFieldBegin('user_id', TType.I64, 3) oprot:writeI64(self.user_id) oprot:writeFieldEnd() end if self.timestamp ~= nil then oprot:writeFieldBegin('timestamp', TType.I64, 4) oprot:writeI64(self.timestamp) oprot:writeFieldEnd() end if self.carrier ~= nil then oprot:writeFieldBegin('carrier', TType.MAP, 5) oprot:writeMapBegin(TType.STRING, TType.STRING, ttable_size(self.carrier)) for kiter176,viter177 in pairs(self.carrier) do oprot:writeString(kiter176) oprot:writeString(viter177) end oprot:writeMapEnd() oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local WriteUserTimeline_result = __TObject:new{ se } function WriteUserTimeline_result:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.STRUCT then self.se = ServiceException:new{} self.se:read(iprot) else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function WriteUserTimeline_result:write(oprot) oprot:writeStructBegin('WriteUserTimeline_result') if self.se ~= nil then oprot:writeFieldBegin('se', TType.STRUCT, 1) self.se:write(oprot) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local ReadUserTimeline_args = __TObject:new{ req_id, user_id, start, stop, carrier } function ReadUserTimeline_args:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.req_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.I64 then self.user_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 3 then if ftype == TType.I32 then self.start = iprot:readI32() else iprot:skip(ftype) end elseif fid == 4 then if ftype == TType.I32 then self.stop = iprot:readI32() else iprot:skip(ftype) end elseif fid == 5 then if ftype == TType.MAP then self.carrier = {} local _ktype179, _vtype180, _size178 = iprot:readMapBegin() for _i=1,_size178 do local _key182 = iprot:readString() local _val183 = iprot:readString() self.carrier[_key182] = _val183 end iprot:readMapEnd() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function ReadUserTimeline_args:write(oprot) oprot:writeStructBegin('ReadUserTimeline_args') if self.req_id ~= nil then oprot:writeFieldBegin('req_id', TType.I64, 1) oprot:writeI64(self.req_id) oprot:writeFieldEnd() end if self.user_id ~= nil then oprot:writeFieldBegin('user_id', TType.I64, 2) oprot:writeI64(self.user_id) oprot:writeFieldEnd() end if self.start ~= nil then oprot:writeFieldBegin('start', TType.I32, 3) oprot:writeI32(self.start) oprot:writeFieldEnd() end if self.stop ~= nil then oprot:writeFieldBegin('stop', TType.I32, 4) oprot:writeI32(self.stop) oprot:writeFieldEnd() end if self.carrier ~= nil then oprot:writeFieldBegin('carrier', TType.MAP, 5) oprot:writeMapBegin(TType.STRING, TType.STRING, ttable_size(self.carrier)) for kiter184,viter185 in pairs(self.carrier) do oprot:writeString(kiter184) oprot:writeString(viter185) end oprot:writeMapEnd() oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local ReadUserTimeline_result = __TObject:new{ success, se } function ReadUserTimeline_result:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 0 then if ftype == TType.LIST then self.success = {} local _etype189, _size186 = iprot:readListBegin() for _i=1,_size186 do local _elem190 = Post:new{} _elem190:read(iprot) table.insert(self.success, _elem190) end iprot:readListEnd() else iprot:skip(ftype) end elseif fid == 1 then if ftype == TType.STRUCT then self.se = ServiceException:new{} self.se:read(iprot) else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function ReadUserTimeline_result:write(oprot) oprot:writeStructBegin('ReadUserTimeline_result') if self.success ~= nil then oprot:writeFieldBegin('success', TType.LIST, 0) oprot:writeListBegin(TType.STRUCT, #self.success) for _,iter191 in ipairs(self.success) do iter191:write(oprot) end oprot:writeListEnd() oprot:writeFieldEnd() end if self.se ~= nil then oprot:writeFieldBegin('se', TType.STRUCT, 1) self.se:write(oprot) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local UserTimelineServiceClient = __TObject.new(__TClient, { __type = 'UserTimelineServiceClient' }) function UserTimelineServiceClient:WriteUserTimeline(req_id, post_id, user_id, timestamp, carrier) self:send_WriteUserTimeline(req_id, post_id, user_id, timestamp, carrier) self:recv_WriteUserTimeline(req_id, post_id, user_id, timestamp, carrier) end function UserTimelineServiceClient:send_WriteUserTimeline(req_id, post_id, user_id, timestamp, carrier) self.oprot:writeMessageBegin('WriteUserTimeline', TMessageType.CALL, self._seqid) local args = WriteUserTimeline_args:new{} args.req_id = req_id args.post_id = post_id args.user_id = user_id args.timestamp = timestamp args.carrier = carrier args:write(self.oprot) self.oprot:writeMessageEnd() self.oprot.trans:flush() end function UserTimelineServiceClient:recv_WriteUserTimeline(req_id, post_id, user_id, timestamp, carrier) local fname, mtype, rseqid = self.iprot:readMessageBegin() if mtype == TMessageType.EXCEPTION then local x = TApplicationException:new{} x:read(self.iprot) self.iprot:readMessageEnd() error(x) end local result = WriteUserTimeline_result:new{} result:read(self.iprot) self.iprot:readMessageEnd() if result.se then error(result.se) end end function UserTimelineServiceClient:ReadUserTimeline(req_id, user_id, start, stop, carrier) self:send_ReadUserTimeline(req_id, user_id, start, stop, carrier) return self:recv_ReadUserTimeline(req_id, user_id, start, stop, carrier) end function UserTimelineServiceClient:send_ReadUserTimeline(req_id, user_id, start, stop, carrier) self.oprot:writeMessageBegin('ReadUserTimeline', TMessageType.CALL, self._seqid) local args = ReadUserTimeline_args:new{} args.req_id = req_id args.user_id = user_id args.start = start args.stop = stop args.carrier = carrier args:write(self.oprot) self.oprot:writeMessageEnd() self.oprot.trans:flush() end function UserTimelineServiceClient:recv_ReadUserTimeline(req_id, user_id, start, stop, carrier) local fname, mtype, rseqid = self.iprot:readMessageBegin() if mtype == TMessageType.EXCEPTION then local x = TApplicationException:new{} x:read(self.iprot) self.iprot:readMessageEnd() error(x) end local result = ReadUserTimeline_result:new{} result:read(self.iprot) self.iprot:readMessageEnd() if result.success ~= nil then return result.success elseif result.se then error(result.se) end error(TApplicationException:new{errorCode = TApplicationException.MISSING_RESULT}) end local UserTimelineServiceIface = __TObject:new{ __type = 'UserTimelineServiceIface' } local UserTimelineServiceProcessor = __TObject.new(__TProcessor , { __type = 'UserTimelineServiceProcessor' }) function UserTimelineServiceProcessor:process(iprot, oprot, server_ctx) local name, mtype, seqid = iprot:readMessageBegin() local func_name = 'process_' .. name if not self[func_name] or ttype(self[func_name]) ~= 'function' then iprot:skip(TType.STRUCT) iprot:readMessageEnd() x = TApplicationException:new{ errorCode = TApplicationException.UNKNOWN_METHOD } oprot:writeMessageBegin(name, TMessageType.EXCEPTION, seqid) x:write(oprot) oprot:writeMessageEnd() oprot.trans:flush() else self[func_name](self, seqid, iprot, oprot, server_ctx) end end function UserTimelineServiceProcessor:process_WriteUserTimeline(seqid, iprot, oprot, server_ctx) local args = WriteUserTimeline_args:new{} local reply_type = TMessageType.REPLY args:read(iprot) iprot:readMessageEnd() local result = WriteUserTimeline_result:new{} local status, res = pcall(self.handler.WriteUserTimeline, self.handler, args.req_id, args.post_id, args.user_id, args.timestamp, args.carrier) if not status then reply_type = TMessageType.EXCEPTION result = TApplicationException:new{message = res} elseif ttype(res) == 'ServiceException' then result.se = res else result.success = res end oprot:writeMessageBegin('WriteUserTimeline', reply_type, seqid) result:write(oprot) oprot:writeMessageEnd() oprot.trans:flush() end function UserTimelineServiceProcessor:process_ReadUserTimeline(seqid, iprot, oprot, server_ctx) local args = ReadUserTimeline_args:new{} local reply_type = TMessageType.REPLY args:read(iprot) iprot:readMessageEnd() local result = ReadUserTimeline_result:new{} local status, res = pcall(self.handler.ReadUserTimeline, self.handler, args.req_id, args.user_id, args.start, args.stop, args.carrier) if not status then reply_type = TMessageType.EXCEPTION result = TApplicationException:new{message = res} elseif ttype(res) == 'ServiceException' then result.se = res else result.success = res end oprot:writeMessageBegin('ReadUserTimeline', reply_type, seqid) result:write(oprot) oprot:writeMessageEnd() oprot.trans:flush() end return { UserTimelineServiceClient = UserTimelineServiceClient }
--[[ LuiExtended License: The MIT License (MIT) --]] -- Effects namespace LUIE.Data.CrowdControl = {} local CrowdControl = LUIE.Data.CrowdControl -- CrowdControl.aoePlayerUltimate -- CrowdControl.aoePlayerNormal -- CrowdControl.aoePlayerSet -- CrowdControl.aoeTrap -- cc.aoeBoss -- CrowdControl.aoeElite -- CrowdControl.aoeNormal -- Increment by 1 here if we want to change priority. Best way to do this is +1 for a new ability, and shared morphs or other damage sources from a shared attack don't increment. -- Priority system doesn't support gaps so NEVER more than +1 here, also the FIRST ability in each tier needs to be +0 to prevent skips if a category is disabled in the options. CrowdControl.aoePlayerUltimate = { -- Dragonknight [28995] = 0, -- Dragonknight Standard [32960] = 0, -- Shifting Standard [32964] = 0, -- Shifting Standard [32948] = 0, -- Standard of Might -- Warden [86247] = 1, -- Sleet Storm (Sleet Storm) [88860] = 0, -- Northern Storm (Northern Storm) [88863] = 0, -- Permafrost (Permafrost) -- Templar [21753] = 1, -- Nova [21756] = 0, -- Solar Prison [21759] = 0, -- Solar Disturbance -- Nightblade [36490] = 1, -- Veil of Blades (Veil of Blades) -- Necromancer [122178] = 1, -- Frozen Colossus (Frozen Colossus) [122399] = 0, -- Pestilent Colossus (Pestilent Colossus) [122400] = 0, -- Pestilent Colossus (Pestilent Colossus) [122401] = 0, -- Pestilent Colossus (Pestilent Colossus) [122392] = 0, -- Glacial Colossus (Glacial Colossus) [118289] = 1, -- Ravenous Goliath (Ravenous Goliath) -- Sorcerer [80435] = 1, -- Suppression Field (Suppression Field) -- Destruction Staff [85127] = 1, --Fiery Rage [85131] = 0, --Thunderous Rage [85129] = 0, --Icy Rage [83683] = 1, --Eye of Flame [83687] = 0, --Eye of Lightning [83685] = 0, --Eye of Frost [83626] = 1, --Fire Storm [83631] = 0, --Thunder Storm [83629] = 0, --Ice Storm -- Mages Guild [63429] = 1, -- Meteor [63454] = 0, -- Ice Comet [63471] = 0, -- Shooting Star -- Vampire [38935] = 1, -- Swarming Scion -- Volendrung [116669] = 1, -- Ebony Cyclone (Ruinous Cyclone) } CrowdControl.aoePlayerNormal = { -- Psijic Order [104007] = 0, -- Time Stop [104072] = 0, -- Borrowed Time [104082] = 0, -- Time Freeze -- Dragonknight [32711] = 1, -- Eruption (Eruption) -- Warden --[130400] = 1, -- Arctic Wind (Arctic Wind) --[130402] = 0, -- Polar Wind (Polar Wind) --[130406] = 0, -- Arctic Blast (Arctic Blast) [88783] = 1, -- Impaling Shards (Impaling Shards) [88791] = 0, -- Gripping Shards (Gripping Shards) [88802] = 0, -- Winter's Revenge (Winter's Revenge) -- Templar [26192] = 1, -- Spear Shards [95931] = 0, -- Spear Shards [26859] = 0, -- Luminous Shards [95955] = 0, -- Luminous Shards [26871] = 0, -- Blazing Spear [26879] = 0, -- Blazing Spear [80172] = 1, -- Ritual of Retribution (Ritual of Retribution) -- Sorcerer [23189] = 1, -- Lightning Splash (Lightning Splash) [23202] = 0, -- Liquid Lightning (Liquid Lightning) [23208] = 0, -- Lightning Flood (Lightning Flood) -- Nightblade [36052] = 1, -- Twisting Path (Twisting Path) -- Necromancer [115254] = 1, -- Boneyard (Boneyard) [117809] = 0, -- Unnerving Boneyard (Unnerving Boneyard) [117854] = 0, -- Avid Boneyard (Avid Boneyard) --[116410] = 1, -- Shocking Siphon (Shocking Siphon) --[118766] = 0, -- Detonating Siphon (Detonating Siphon) --[118011] = 0, -- Mystic Siphon (Mystic Siphon) -- Destruction Staff [62896] = 1, -- Wall of Fire [62971] = 0, -- Wall of Storms [62931] = 0, -- Wall of Frost [39054] = 1, -- Unstable Wall of Fire [39079] = 0, -- Unstable Wall of Storms [39071] = 0, -- Unstable Wall of Frost [62912] = 1, -- Blockade of Fire [62990] = 0, -- Blockade of Storms [62951] = 0, -- Blockade of Frost -- Two-Handed [126474] = 1, -- Stampede -- Bow [28877] = 1, -- Volley [38690] = 0, -- Endless Hail [38696] = 0, -- Arrow Barrage -- Undaunted [39299] = 1, -- Necrotic Orb [42029] = 1, -- Mystic Orb -- Assault [38561] = 1, -- Caltrops (Caltrops) [40267] = 0, -- Anti-Cavalry Caltrops (Anti-Cavalry Caltrops) [40252] = 0, -- Razor Caltrops (Razor Caltrops) } CrowdControl.aoePlayerSet = { -- Sets [102136] = 0, -- Zaan [59568] = 1, -- Malubeth [80522] = 1, -- Stormfist [59498] = 1, -- Mephala's Web (Spawm of Mephala) [60972] = 1, -- Fiery Breath (Maw of the Infernal) [80525] = 1, -- Ilambris [80526] = 0, -- Ilambris [84502] = 1, -- Grothdarr [80561] = 1, -- Iceheart [97883] = 1, -- Domihaus [97899] = 0, -- Domihaus [80565] = 1, -- Kra'gh [75692] = 1, -- Bahraha's Curse (of Bahraha's Curse) [57209] = 1, -- Storm Knight's Plate (of the Storm Knight) [67136] = 1, -- Overwhelming Surge (Overwhelming) [59696] = 1, -- Embershield (Embershield) [67204] = 1, -- Leeching Plate (of Leeching) [102094] = 1, -- Thurvokun (Thurvokun) [116920] = 1, -- Auroran's Thunder (Auroran's Thunder) [133494] = 1, -- Aegis Caller (Aegis Caller's) [137526] = 1, -- Hunter's Venom (Venomous) [143077] = 1, -- Stone Husk (Stone Husk) -- Siege [104693] = 1, -- Meatbag Catapult [104695] = 1, -- Scattershot Catapult [138556] = 1, -- Shock Lancer [138434] = 1, -- Fire Lancer [138552] = 1, -- Frost Lancer } CrowdControl.aoeTraps = { [87949] = 0, -- Lava (Foyada Quarry) [44034] = 0, -- Slaughterfish Attack (Stirk) [113082] = 0, -- Slaughterfish Attack (Cyrodiil) [19224] = 0, -- In Lava (Halls of Torment) [11338] = 0, -- In Lava (The Earth Forge) [56277] = 0, -- Lava (City of Ash II) [5140] = 0, -- Lava (Dragonstar Arena) [62770] = 0, -- Coldharbour Flames (Flame Trap) - Soul Shriven in Coldharbour [21943] = 0, -- Spike Trap (Spike Trap) [53169] = 0, -- Spike Trap (Spike Trap) - Dragonstar Arena [26531] = 0, -- Bear Trap (Bear Trap) [31086] = 0, -- Trap (Trap) - Selene's Web [20260] = 0, -- Rune Burst (Sigil of Frost) [33594] = 0, -- Fire (Fire) -- Greenshade - Throne of the Wilderking [17314] = 0, -- Fire Trap (Player) [72888] = 0, -- Fire Attack 1 (Fire) -- Banished Cells II [72889] = 0, -- Fire Attack 2 (Fire) -- Banished Cells II [27940] = 0, -- Laser Damage (Generic Flame Wave Shooter) -- Stros M'Kai [32245] = 0, -- Searing Steam (Steam Trap) -- Stros M'Kai [26040] = 0, -- Steam Blast (Steam Vent) -- Volenfell [26089] = 0, -- Steam Blast (Steam Vent) -- Volenfell [26077] = 1, -- Steam Blast (Steam Vent) -- Volenfell [26091] = 1, -- Steam Blast (Steam Vent) -- Volenfell [110416] = 1, -- Putrid Cloud (Gas Blossom) -- Housing [110542] = 1, -- Stunted Current (Static Pitcher) -- Housing [111258] = 1, -- Surprise Attack (Lantern Mantis) -- Housing [111261] = 1, -- Surprise Attack (Lantern Mantis) -- Housing [92757] = 0, -- Spinning Blade (Ald Carac) [117508] = 0, -- Shock Wall (Lightning Trap - Elinhir Private Arena) [117622] = 0, -- Shock Wall (Lightning Trap - Elinhir Private Arena) [117598] = 0, -- Shock Wall (Lightning Trap - Elinhir Private Arena) [117139] = 0, -- Spinning Blade (Blade Trap - Elinhir Private Arena) [92150] = 0, -- Fire Trap (Vvardenfell -- Divine Delusions) [87102] = 0, -- Spinning Blade (Vvardenfell -- Divine Restoration) [92284] = 0, -- Planar Shear (Vvardenfell -- Divine Restoration) [86743] = 0, -- Accelerated Transposition (Vvardenfell -- Like Blood from a Stone) [84527] = 0, -- Searing Steam (Vvardenfell - Nchuleftingth) [90271] = 0, -- Charge-Wire Shock (Vvardenfell - Nchuleftingth) [92138] = 0, -- Laser Damage (Vvardenfell - Nchuleftingth) -- Quests [31970] = 1, -- Wrath (Tears of the Two Moons) [33404] = 0, -- Wrath (Tears of the Two Moons) [38499] = 1, -- Wrath (The Grips of Madness) [33577] = 1, -- Maormer Fire (Pelidil's End) -- Dragonstar Arena [53341] = 0, -- Biting Cold (Player) [60421] = 0, -- Biting Cold (Player) [83498] = 0, -- Poisonous Cloud (Poison Cloud) [83468] = 0, -- Restoring Nature (Nature's Blessing) -- Maelstrom Arena [69101] = 0, -- Shock (Generator) [66797] = 0, -- Spinning Blade (Blade Trap) [67871] = 0, -- Shock (Water) [72525] = 0, -- Frigid Waters (Player) [67808] = 0, -- Frigid Waters (Player) -- City of Ash II [56068] = 0, -- Slag Geyser (Lava Pool) } CrowdControl.aoeNPCBoss = { -- Vvardenfell [94936] = 0, -- Tremor (Nchuleftingth - Mud-Tusk) [86566] = 1, -- Fire Runes (Nchuleftingth - Friar Hadelar) [89754] = 1, -- Shocking Rake (Old Rust-Eye - Khartag Point) [90148] = 1, -- Sunder's Echo (Vvardenfell -- Divine Intervention) [90146] = 0, -- Sunder's Echo (Vvardenfell -- Divine Intervention) [69284] = 1, -- Whirlwind Function (Guardian of Bthark -- Nchuleftingth) [86607] = 1, -- Steam Breath (Guardian of Bthark -- Nchuleftingth) -- Elsweyr [124352] = 1, -- Flame Aura (Bahlokdaan) -- World Bosses [84045] = 1, -- Seal of Defilement (Quenyas) - World Boss - Seaside Scarp Camp [84206] = 1, -- Stinging Sputum (Gathongor the Mauler) - World Boss - Gathongor's Mine [83668] = 1, -- Feral Impact (Skullbreaker) - World Boss - Windshriek Strand [83671] = 1, -- Feral Impact (Skullbreaker) - World Boss - Windshriek Strand [84160] = 1, -- Spit Poison (Old Widow Silk) - World Boss - Spider Nest [84549] = 1, -- Venom Spray (Old Widow Silk) - World Boss - Spider Nest [83000] = 1, -- Crabuchet (Titanclaw) - World Boss - Mudcrab Beach [83021] = 1, -- Crabuchet (Titanclaw) - World Boss - Mudcrab Beach -- Quests [36860] = 1, -- Swordstorm Damage (MSQ - Halls of Torment) [87959] = 1, -- Ash Storm (Vvardenfell -- Divine Delusions) -- Dragonstar Arena [53660] = 1, -- Power Overload Heavy Attack (Nak'tah) [54084] = 1, -- Corrosive Armor (Earthen Heart Knight) [52903] = 1, -- Standard of Might (Anal'a Tu'wha0) [52933] = 1, -- Solar Disturbance (Shadow Knight) [55086] = 1, -- Poison Mist (Vampire Lord Thisa) [55092] = 1, -- Devouring Swarm (Vampire Lord Thisa) [55104] = 1, -- Marked for Death (Hiath the Battlemaster) [55182] = 0, -- Marked for Death (Hiath the Battlemaster) -- Maelstrom Arena [68197] = 1, -- Necrotic Essence (Necrotic Orb) [70901] = 1, -- Defiled Grave (Maxus the Many) -- NORMAL [72149] = 0, -- Defiled Grave (Maxus the Many) -- VETERAN [69366] = 1, -- Barrage Function (Centurion Champion) [69316] = 1, -- Electric Shield (Centurion Champion) [73880] = 1, -- Call Lightning (Lamia Queen) [67758] = 1, -- Queen's Poison (Lamia Queen) [68537] = 1, -- Overcharged Bolt (The Control Guardian) [70860] = 1, -- Overheated Flame (The Control Guardian) [68543] = 1, -- Overheated Volley (The Control Guardian) -- Banished Cells I [19027] = 1, -- Dead Zone (Skeletal Destroyer) [33188] = 1, -- Daedric Tempest (High Kinlord Rilis) -- Banished Cells II [28904] = 1, -- Immolating Bite (Maw of the Infernal) [49149] = 1, -- Breath of Flame (Maw of the Infernal) [29020] = 1, -- Berserker Frenzy (Keeper Voranil) [31727] = 1, -- Corruption (Keeper Imiril) [48800] = 1, -- Daedric Tempest (High Kinlord Rilis) [48815] = 0, -- Daedric Tempest (High Kinlord Rilis) -- Elden Hollow I [16017] = 1, -- Berserker Frenzy (Akasha gra-Mal) [25300] = 0, -- Berserker Frenzy (Akasha gra-Mal) [25301] = 0, -- Berserker Frenzy (Akasha gra-Mal) [25302] = 0, -- Berserker Frenzy (Akasha gra-Mal) [42601] = 1, -- Necrotic Circle (Canonreeve Oraneth) -- Elden Hollow II --[34377] = 1, -- Flame Geyser (Dubroze the Infestor) [32972] = 1, -- Consuming Shadow (Murklight) [33050] = 1, -- Eclipse (Murklight) [33103] = 1, -- Spout Shadow (The Shadow Guard) [33434] = 1, -- Daedric Flame (Bogdan the Nightflame) -- City of Ash I [34960] = 1, -- Blazing Fire (Warden of the Shrine) [35145] = 1, -- Consuming Fire (Infernal Guardian) [34204] = 1, -- Burning Field (Rothariel Flameheart) -- City of Ash II [56415] = 1, -- Fire Runes (Urata the Legion) [55314] = 1, -- Slag Breath (Horvantud the Fire Maw) [55334] = 0, -- Fiery Breath (Horvantud the Fire Maw) [55321] = 0, -- Fiery Breath (Horvantud the Fire Maw) [55336] = 0, -- Fiery Breath (Horvantud the Fire Maw) [55327] = 0, -- Fiery Breath (Horvantud the Fire Maw) [55338] = 0, -- Fiery Breath (Horvantud the Fire Maw) [56010] = 1, -- Ground Quake (Horvantud the Fire Maw) [56151] = 1, -- Ethereal Flame (Ash Titan) [55175] = 1, -- Molten Rain (Ash Titan) [54637] = 1, -- Flame Tornado (Air Atronach) [55756] = 1, -- Burning (Valkyn Skoria) -- Tempest Island [26619] = 1, -- Shock (Sudden Storm) [6108] = 1, -- Lightning Storm (Yalorasse the Speaker) [26752] = 1, -- Enervating Stone (Stormfist) [26517] = 1, -- Electrical Shock (Twister) -- Selene's Web [30908] = 1, -- Summon Primal Swarm (Treethane Kerninn) [30773] = 1, -- Arrow Rain (Longclaw) [31150] = 1, -- Poison Burst (Longclaw) [31203] = 1, -- Venomous Burst (Queen Aklayah) -- Spindleclutch II [28006] = 1, -- Cave In (Blood Spawn) [47332] = 0, -- Cave-In (Blood Spawn) [27603] = 1, -- Blood Pool (Urvan Veleth) [27906] = 1, -- Blood Pool (Vorenor Winterbourne) -- Wayrest Sewers I [25591] = 1, -- Necrotic Essence (Investigator Garron) -- Wayrest Sewers II [36625] = 1, -- Scourging Spark (Malubeth the Scourger) [36869] = 1, -- Scorching Flames (Uulgarg the Risen) [36944] = 1, -- Necrotic Barrage (Garron the Returned) -- Crypt of Hearts I [22716] = 1, -- Necrotic Ritual (Archmaster Siniel) [46950] = 1, -- Fire Trail (Death's Leviathan) [22432] = 1, -- Electric Prison (Lightning Rod) [22388] = 1, -- Rain Fire (Ilambris-Zaven) [22398] = 1, -- Call Lightning (Ilambris-Athor) [22401] = 0, -- Call Lightning (Ilambris-Athor) [22403] = 0, -- Call Lightning (Ilambris-Athor) -- Crypt of Hearts II [51883] = 1, -- Creeping Storm (Creeping Storm) [52286] = 1, -- Rain Fire (Ilambris Amalgam) [52335] = 0, -- Rain Fire (Ilambris Amalgam) [52279] = 1, -- Call Lightning (Ilambris Amalgam) [52339] = 0, -- Call Lightning (Ilambris Amalgam) [52082] = 1, -- Cursed Ground (Nerien'eth) [53157] = 0, -- Cursed Ground (Nerien'eth) [53134] = 1, -- Tortured Souls (Soul Cage) -- Volenfell [25030] = 1, -- Twisted Steel (Quintus Verres) [25143] = 1, -- Burning Ground (Quintus Verres) [25223] = 1, -- Heaving Quake (Quintus Verres) [25674] = 1, -- Flame Burst (Boilbite) [25675] = 1, -- Flame Burst (Boilbite) [25676] = 1, -- Flame Burst (Boilbite) [25677] = 1, -- Flame Burst (Boilbite) [44113] = 1, -- Barrage Function (The Guardian's Spark) [25213] = 1, -- Whirlwind Function (The Guardian's Strength) } CrowdControl.aoeNPCElite = { -- Overland / Standard NPC's [44228] = 0, -- Dragonknight Standard (Dragonknight - Elite) [81197] = 1, -- Agonizing Fury (Thundermaul - Boss) [21952] = 1, -- Repulsion Shock (Wamasu) [55867] = 0, -- Repulsion Shock (Wamasu - Boss) [72794] = 1, -- Toxic Pool (Haj Mota) [53233] = 1, -- Miasma Pool (Flesh Colossus) [52866] = 1, -- Volley (Cyrodiil Archer) [54258] = 1, -- Upgraded Volley (Cyrodiil Archer) [10271] = 1, -- Quake (Gargoyle) [9011] = 1, -- Tremor (Troll) [48297] = 1, -- Consuming Omen (Troll - Ranged) [19061] = 1, -- Rain of Wisps (Wispmother) [75928] = 1, -- Elemental Pool (Minotaur) [75953] = 1, -- Brimstone Hailfire (Minotaur Shaman) [75976] = 1, -- Pillar of Nirn (Minotaur Shaman) [75980] = 1, -- Pillar Eruption (Minotaur Shaman) [11282] = 1, -- Steam Breath (Dwemer Centurion) -- World [95841] = 1, -- Static Charge (Dark Anchor) -- Quests [50765] = 1, -- CON_AOE_Template1 (Pelidil's End) -- Summerset [105889] = 1, -- Pustulant Eruption (Yaghra Nightmare) -- Dragonstar Arena [53314] = 1, -- Flame Volley (Sovngarde Ranger) [53280] = 1, -- Unstable Wall of Frost (Sovngarde Icemage) [53614] = 1, -- Thundering Presence (Nak'tah) [53625] = 1, -- Lightning Flood (Nak'tah) [56824] = 1, -- Puncturing Sweep (House Dres Templar) [54161] = 1, -- Berserker Frenzy (House Dres Slaver) [54080] = 1, -- Cinder Storm (Earthen Heart Knight) [52892] = 1, -- Flames of Oblivion (Anal'a Tu'wha) [55981] = 1, -- Ice Charge (Dwarven Ice Centurion) -- Maelstrom Arena [72159] = 1, -- Static Field (Dwarven Spider) [72203] = 1, -- Overcharge (Scavenger Thunder-Smith) } CrowdControl.aoeNPCNormal = { [37131] = 0, -- Ice Cage (Battlemage) [10813] = 1, -- Ignite (Synergy - Fire Mage) [38260] = 0, -- Ignite (Synergy - Fire Mage) [28629] = 1, -- Volley (Archer) [47102] = 1, -- Fire Rune (Fire Mage) [14068] = 1, -- Ignite (Synergy - Archer) [70414] = 0, -- Ignite (Synergy - Cyrodiil Archer) [38125] = 1, -- Caltrops (Faction NPCs) [76730] = 1, -- Pool of Shadow (Voidbringer) [76624] = 0, -- Pool of Shadow (Voidbringer) [76729] = 0, -- Pool of Shadow (Voidbringer) [76728] = 0, -- Pool of Shadow (Voidbringer) [88336] = 0, -- Pool of Shadow (Skaafin Masquer) [88330] = 0, -- Pool of Shadow (Skaafin Masquer) [88335] = 0, -- Pool of Shadow (Skaafin Masquer) [88334] = 0, -- Pool of Shadow (Skaafin Masquer) [84837] = 1, -- Broken Pact (Skaafin Witchling) [87902] = 1, -- Bombard (Arbalest) [62502] = 1, -- Fiery Wind (Justice Mage) [46819] = 1, -- Storm Damage (Cyrodiil Mage) [7883] = 1, -- Guardian Storm (Cyrodiil Mage) [8604] = 1, -- Vigorous Swipe (Mammoth) [27100] = 1, -- Shocking Rake (Dreugh) [16698] = 1, -- Poisonbloom (Netch) [90778] = 1, -- Acid Pool (Nix-Ox) [90815] = 0, -- Acid Pool (Nix-Ox) [85421] = 1, -- Retch (Cliff Strider) [85391] = 1, -- Slash (Cliff Strider) [13680] = 1, -- Acid Blood (Assassin Beetle) [61374] = 1, -- Infectious Swarm (Necrotic Hoarvor) [10947] = 1, -- Fiery Breath (Shalk) [5265] = 1, -- Burning Ground (Shalk) [8088] = 1, -- Poison Spray (Giant Spider) [87126] = 1, -- Heat Vents (Fetcherfly Nest) [51282] = 1, -- Flame Tornado (Air Atronach - Flame) [9749] = 1, -- Envelop (Banekin) [73437] = 1, -- Soul Flame (Daedric Titan) [4772] = 1, -- Fiery Breath (Daedroth) [91938] = 1, -- Burst of Embers (Daedroth) [51645] = 1, -- Frozen Ground (Frost Atronach) [6162] = 1, -- Rain of Fire (Scamp) [88323] = 1, -- Blast Furnace (Iron Atronach) [69950] = 1, -- Desecrated Ground (Undead Synergy) [73937] = 1, -- Soul Cage (Lich) [73929] = 0, -- Soul Cage (Lich) [20812] = 1, -- Defiled Ground (Lich) [72996] = 1, -- Symphony of Blades (Defiled Aegis) [8628] = 1, -- Charged Ground (Harpy) [4769] = 1, -- Choking Pollen (Lurcher) [16040] = 1, -- Hurricane (Nereid) [19997] = 1, -- Static Field (Dwemer Spider - Synergy) [91094] = 1, -- Split Bolt (Dwemer Arquebus) [91095] = 0, -- Split Bolt (Dwemer Arquebus) [91096] = 0, -- Split Bolt (Dwemer Arquebus) [103862] = 1, -- Deluge (Yaghra Spewer) [103992] = 1, -- Luminescent Burn (Yaghra Spewer) [121644] = 1, -- Defiled Ground (Euraxian Necromancer) } -- List of effects sourced by the player that damage self that should be shown CrowdControl.LavaAlerts = { -- Player [115607] = true, -- Dismount Stun (Mount) [141004] = true, -- Dismount Stun (Passenger Mount) -- Consumables [68565] = true, -- Stun (Potion of Stun) -- World [95841] = true, -- Static Charge (Dark Anchor) -- Battlegrounds [87949] = true, -- Lava (Foyada Quarry) -- Traps & World [44034] = true, -- Slaughterfish Attack (Stirk) [113082] = true, -- Slaughterfish Attack (Cyrodiil) [19224] = true, -- In Lava (Halls of Torment) [11338] = true, -- In Lava (The Earth Forge) [56277] = true, -- Lava (City of Ash II) [5140] = true, -- Lava (Dragonstar Arena) [17314] = true, -- Fire Trap (Player) -- Quests [31502] = true, -- MGQ2 Asakala Sahdina Barrier (Simply Misplaced) [31503] = true, -- MGQ2 Asakala Rashomta Barrier (Simply Misplaced) [21876] = true, -- Q4260 West Barrier Teleport (Breaking the Barrier) [21878] = true, -- Q4260 East Barrier Teleport (Breaking the Barrier) [22395] = true, -- Q4261 ROD Barrier Teleport (Sever All Ties) [23606] = true, -- Q4326 Crystal Backfire (Preventative Measure) [37438] = true, -- Shocked (The Grips of Madness) [36766] = true, -- Q4842 Stun Headgrab Knockback (The Unquiet Dead) -------------- -- Arenas ---- -------------- -- Dragonstar Arena [53341] = true, -- Biting Cold (Player) [60421] = true, -- Biting Cold (Player) [54405] = true, -- Celestial Blast (Player) -- Maelstrom Arena [72525] = true, -- Frigid Waters (Player) [67808] = true, -- Frigid Waters (Player) -------------- -- Dungeons -- -------------- -- Elden Hollow II [30455] = true, -- Arachnophobia (The Opus of Torment) -- City of Ash I [70113] = true, -- Soul Scream (Scroll of Glorious Battle) -- City of Ash II [56563] = true, -- Book (Frigid Tome) -- Selene's Web [58521] = true, -- Web (Selene) -- Wayrest Sewers II [49052] = true, -- Pellingare Prison (Allene Pellingare) } CrowdControl.IgnoreList ={ [54363] = true, -- Halt (Guard) [4197] = true, -- Recovering (NPC Duel) -- Quests [34499] = true, -- Corruption Beam (The Blight of the Bosmer) -- Vampire [44670] = true, -- Vamp Theater Head Grab Stun (Scion of the Blood Matron) -- MSQ [64072] = true, -- Eye of the Sentinel (Tutorial) [61646] = true, -- Incapacitating Terror (Tutorial) [28737] = true, -- Recovery (Manifestation of Terror) [48077] = true, -- Q4971 Shali Cast (Saved) [32060] = true, -- Shocked (Tears of the Two Moons) [38108] = true, -- Q4868 Sheo Teleports Player (The Grips of Madness) [35645] = true, -- Q4768 PC Tribunal Layer 2 Stun (Scars Never Fade) -- Elsweyr [121032] = true, -- Bash (Grand Adept Ma'hja-dro) (Bright Moons, Warm Sands) [121035] = true, -- Staggered (Grand Adept Ma'hja-dro) (Bright Moons, Warm Sands) ---------------- -- Arenas ---------------- -- Dragonstar Arena [55221] = true, -- Sucked Under (Player) [55641] = true, -- Stun (Light of Boethia) ---------------- -- Dungeons ---------------- -- Banished Cells II [46433] = true, -- DUN_BCH_Knockback&Knockdown (High Kinlord Rilis) -- Elden Hollow I [25723] = true, -- CON_Knockback&Knockdown (Bakkhara) -- City of Ash II [55429] = true, -- Magma Prison (Valkyn Skoria) -- Tempest Island [26938] = true, -- Enervating Stone (Stormfist) -- Frostvault [109838] = true, -- End Stun (Icestalker) -- Frostvault [119461] = true, -- Teleport Failsafe (Border Chk) -- Frostvault } -- Not implemented - list of abilities that ACTION_RESULT_GAINED_DURATION fires in the opposite order of normal CrowdControl.ReversedLogic = { -- Quests [21876] = true, -- Q4260 West Barrier Teleport [21878] = true, -- Q4260 East Barrier Teleport [39260] = true, -- Q4917 Push Player Back (Grahtwood - The Blacksap's Hold) -- World Bosses [83124] = true, -- Ferocious Bellow (Greenshade - World Boss - Thodundor's View) -- Dungeons [26716] = true, -- Skyward Slam (Stormfist) -- Tempest Island [34848] = true, -- Primal Sweep -- Wayrest Sewers } -- Use on ACTION_RESULT_EFFECT_GAINED CrowdControl.SpecialCC = { [55756] = true, -- Burning (Valkyn Skoria) }
-- -- Recharges a battery cart -- if not yatm_cluster_energy then return end
local system = require "coutil.system" local stateco = require "coutil.coroutine" newtest "coroutine" ------------------------------------------------------------ do case "compilation errors" for v in ipairs(types) do local ltype = type(v) if ltype ~= "string" and ltype ~= "number" then asserterr("string or memory expected", pcall(stateco.load, v)) asserterr("string expected", pcall(stateco.load, "", v)) asserterr("string expected", pcall(stateco.load, "", "", v)) end end local bytecodes = string.dump(function () a = a+1 end) asserterr("attempt to load a binary chunk (mode is 't')", stateco.load(bytecodes, nil, "t")) asserterr("attempt to load a text chunk (mode is 'b')", stateco.load("a = a+1", "bytecodes", "b")) asserterr("syntax error", stateco.load("invalid chunk")) done() end do case "runtime errors" local co = stateco.load[[ return 1, 2, 3 ]] asserterr("unable to yield", pcall(system.resume, co)) assert(co:status() == "suspended") local co = stateco.load([[ require "_G" error "Oops!" ]], "@bytecodes") local a spawn(function () a = 1 asserterr("bytecodes:2: Oops!", system.resume(co)) assert(co:status() == "dead") asserterr("cannot resume dead coroutine", system.resume(co)) a = 2 end) assert(a == 1) local b spawn(function () asserterr("cannot resume running coroutine", system.resume(co)) b = 1 local res, errval = system.resume(stateco.load[[ require "_G" error(true) ]]) assert(res == false) assert(errval == true) b = 2 end) assert(b == 1) assert(system.run() == false) assert(a == 2 or b == 2) done() end do case "type errors" local stage = 0 spawn(function () local co = stateco.load(string.dump(function () require "_G" error{} end)) assert(co:status() == "suspended") asserterr("unable to transfer argument #2 (got table)", system.resume(co, table)) assert(co:status() == "suspended") asserterr("unable to transfer argument #3 (got function)", system.resume(co, 1, print)) assert(co:status() == "suspended") asserterr("unable to transfer argument #4 (got thread)", system.resume(co, 1, 2, coroutine.running())) assert(co:status() == "suspended") asserterr("unable to transfer argument #5 (got userdata)", system.resume(co, 1, 2, 3, co)) assert(co:status() == "suspended") stage = 1 asserterr("unable to transfer error (got table)", system.resume(co)) assert(co:status() == "dead") co = stateco.load[[ return 1, {2}, 3 ]] asserterr("unable to transfer return value #2 (got table)", system.resume(co)) assert(co:status() == "dead") co = stateco.load[[ return 1, 2, 3, require ]] asserterr("unable to transfer return value #4 (got function)", system.resume(co)) assert(co:status() == "dead") stage = 2 end) assert(stage == 1) assert(system.run() == false) assert(stage == 2) done() end do case "preemptive execution" local path = os.tmpname() os.remove(path) assert(not io.open(path)) local co = assert(stateco.load(string.format([[ local io = require "io" local os = require "os" local path = %q while true do local file = io.open(path) if file ~= nil then local contents = file:read("a") file:close() if contents == "deleteme" then os.remove(path) break end end end ]], path))) assert(co:status() == "suspended") local stage = 0 spawn(function () assert(system.resume(co)) stage = 1 end) assert(co:status() == "running") local file = assert(io.open(path, "w")) file:write("deleteme") file:close() local removed = false for i=1, 1e5 do if not pcall(system.fileinfo, path, "~b") then removed = true break end system.suspend(.1, "~") end assert(removed) assert(co:status() == "running") assert(stage == 0) system.run() assert(stage == 1) assert(co:status() == "dead") done() end do case "transfer values" local co = stateco.load[[ require "_G" local coroutine = require "coroutine" assert(select("#", ...) == 5) local a,b,c,d,e = ... assert(a == nil) assert(b == false) assert(c == 123) assert(d == 0xfacep-8) assert(e == "\001") assert(select("#", coroutine.yield()) == 0) assert(coroutine.yield(nil) == nil) assert(coroutine.yield(false) == false) assert(coroutine.yield(true) == true) assert(coroutine.yield(0) == 0) assert(coroutine.yield(1) == 1) assert(coroutine.yield(-1) == -1) assert(coroutine.yield(0xadap-16) == 0xadap-16) assert(coroutine.yield('') == '') assert(coroutine.yield('Lua 5.4') == 'Lua 5.4') assert(coroutine.yield('\\0') == '\\0') return ... ]] assert(co:status() == "suspended") spawn(function () local function assertreturn(count, ...) assert(co:status() == (count == 5 and "dead" or "suspended")) assert(select("#", ...) == 2*count+1) assert(select(count+1, ...) == true) for i = 1, count do assert(select(i, ...) == select(count+1+i, ...)) end end assertreturn(0, system.resume(co, nil, false, 123, 0xfacep-8, "\001")) assertreturn(1, nil, system.resume(co)) assertreturn(1, false, system.resume(co, nil)) assertreturn(1, true, system.resume(co, false)) assertreturn(1, 0, system.resume(co, true)) assertreturn(1, 1, system.resume(co, 0)) assertreturn(1, -1, system.resume(co, 1)) assertreturn(1, 0xadap-16, system.resume(co, -1)) assertreturn(1, '', system.resume(co, 0xadap-16)) assertreturn(1, 'Lua 5.4', system.resume(co, '')) assertreturn(1, '\\0', system.resume(co, 'Lua 5.4')) assertreturn(5, nil, false, 123, 0xfacep-8, "\001", system.resume(co, '\\0')) end) assert(system.run() == false) done() end do case "resume closed" local stage spawn(function () local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] stage = 0 local ok, res = system.resume(co) assert(ok == true) assert(res == "hello") assert(co:close() == true) assert(co:status() == "dead") asserterr("cannot resume dead coroutine", system.resume(co)) stage = 1 end) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "collect suspended" local stage spawn(function () garbage.co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] stage = 0 local ok, res = system.resume(garbage.co) assert(ok == true) assert(res == "hello") stage = 1 end) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "collect canceled" local stage spawn(function () garbage.coro = coroutine.running() garbage.co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] stage = 0 local ok, res = system.resume(garbage.co) assert(ok == nil) assert(res == "cancel") stage = 1 assert(stateco.status(garbage.co) == "running") end) assert(stage == 0) coroutine.resume(garbage.coro, nil, "cancel") assert(stage == 1) assert(system.run() == false) gc() assert(garbage.co == nil) done() end do case "running unreferenced" local stage spawn(function () stage = 0 local ok, res = system.resume(stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]]) assert(ok == true) assert(res == "hello") stage = 1 end) gc() assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "close running" local stage local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] spawn(function () stage = 0 local ok, res = system.resume(co) assert(ok == true) assert(res == "hello") assert(stateco.close(co) == true) asserterr("cannot resume dead coroutine", system.resume(co)) assert(stateco.close(co) == true) stage = 1 end) assert(co:status() == "running") asserterr("cannot close a running coroutine", pcall(stateco.close, co)) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "close on error" local stage local co = stateco.load[[ require "_G" error("oops!") ]] spawn(function () stage = 0 asserterr("oops!", system.resume(co)) asserterr("oops!", stateco.close(co)) asserterr("cannot resume dead coroutine", system.resume(co)) assert(stateco.close(co) == true) stage = 1 end) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "close on non-transferable error" local stage local co = stateco.load[[ require "_G" error(error) ]] spawn(function () stage = 0 asserterr("unable to transfer error (got function)", system.resume(co)) asserterr("unable to transfer error (got function)", stateco.close(co)) asserterr("cannot resume dead coroutine", system.resume(co)) assert(stateco.close(co) == true) stage = 1 end) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "yield values" local stage = 0 local a,b,c = spawn(function () local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] local res, extra = system.resume(co, "testing", 1, 2, 3) assert(res == true) assert(extra == "hello") stage = 1 end) assert(a == nil) assert(b == nil) assert(c == nil) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "scheduled yield" local stage = 0 spawn(function () local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] system.resume(co) stage = 1 coroutine.yield() stage = 2 end) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "resume same coroutine" local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] local stage = 0 spawn(function () system.resume(co) assert(co:status() == "suspended") stage = 1 system.resume(co) assert(co:status() == "dead") stage = 2 end) assert(stage == 0) assert(co:status() == "running") if standard == "posix" then assert(system.run("step") == true) assert(co:status() == "running") assert(stage == 1) end assert(system.run() == false) assert(stage == 2) assert(co:status() == "dead") done() end do case "resume different coroutines" local co1 = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello once") ]] local co2 = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello twice") ]] local stage = 0 spawn(function () system.resume(co1) assert(co1:status() == "suspended") assert(co2:status() == "suspended") stage = 1 system.resume(co2) assert(co1:status() == "suspended") assert(co2:status() == "suspended") stage = 2 end) assert(stage == 0) assert(co1:status() == "running") assert(co2:status() == "suspended") if standard == "posix" then assert(system.run("step") == true) assert(co1:status() == "suspended") assert(co2:status() == "running") assert(stage == 1) end assert(system.run() == false) assert(stage == 2) assert(co1:status() == "suspended") assert(co2:status() == "suspended") done() end do case "resume transfer" local thread local a spawn(function () local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") return "bye" ]] a = 1 local res, extra = system.resume(co) assert(res == true) assert(extra == "hello") assert(co:status() == "suspended") coroutine.resume(thread, co) a = 2 end) assert(a == 1) spawn(function () thread = coroutine.running() b = 1 local co = coroutine.yield() thread = nil b = 2 local res, extra = system.resume(co) assert(res == true) assert(extra == "bye") assert(co:status() == "dead") b = 3 end) assert(b == 1) if standard == "posix" then assert(system.run("step") == true) assert(a == 2) assert(b == 2) end gc() assert(system.run() == false) assert(b == 3) done() end do case "cancel resume" local stage = 0 spawn(function () garbage.coro = coroutine.running() local co = stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]] local a,b,c = system.resume(co) assert(a == true) assert(b == nil) assert(c == 3) stage = 1 coroutine.yield() stage = 2 end) assert(stage == 0) coroutine.resume(garbage.coro, true,nil,3) assert(stage == 1) assert(system.run() == false) assert(stage == 1) done() end do case "cancel and resume again" local stage = 0 spawn(function () garbage.coro = coroutine.running() local co = stateco.load[[ require "_G" local coroutine = require "coroutine" coroutine.yield("hello") return "bye" ]] local res, extra = system.resume(co) assert(res == nil) assert(extra == "cancel") assert(co:status() == "running") asserterr("cannot resume running coroutine", system.resume(co)) stage = 1 repeat system.suspend() until co:status() == "suspended" local res, extra = system.resume(co) assert(res == true) if extra == "hello" then assert(co:status() == "suspended") else assert(extra == "bye") assert(co:status() == "dead") end stage = 2 end) assert(stage == 0) coroutine.resume(garbage.coro, nil, "cancel") assert(stage == 1) assert(system.run() == false) assert(stage == 2) done() end do case "cancel and resume by other" local thread local stage spawn(function () garbage.coro = coroutine.running() local co = stateco.load[[ require "_G" local coroutine = require "coroutine" coroutine.yield("hello") return "bye" ]] stage = 0 local res, extra = system.resume(co) assert(res == nil) assert(extra == "cancel") assert(co:status() == "running") coroutine.resume(thread, co) end) assert(stage == 0) spawn(function () thread = coroutine.running() stage = 1 local co = coroutine.yield() thread = nil asserterr("cannot resume running coroutine", system.resume(co)) stage = 2 repeat system.suspend() until co:status() == "suspended" local res, extra = system.resume(co) assert(res == true) if extra == "hello" then assert(co:status() == "suspended") else assert(extra == "bye") assert(co:status() == "dead") end stage = 3 end) assert(stage == 1) coroutine.resume(garbage.coro, nil, "cancel") assert(stage == 2) assert(system.run() == false) assert(stage == 3) done() end do case "ignore errors" local stage = 0 pspawn(function () assert(system.resume(stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]])) stage = 1 error("oops!") end) assert(stage == 0) assert(system.run() == false) assert(stage == 1) done() end do case "ignore errors after cancel" local stage = 0 pspawn(function () garbage.coro = coroutine.running() assert(system.resume(stateco.load[[ local coroutine = require "coroutine" coroutine.yield("hello") ]])) stage = 1 error("oops!") end) assert(stage == 0) coroutine.resume(garbage.coro, true) assert(stage == 1) assert(system.run() == false) assert(stage == 1) done() end do case "chunk from file" local path = os.tmpname() local file = io.open(path, "w") file:write[[ local coroutine = require "coroutine" coroutine.yield("hello") return "bye" ]] file:close() local co = stateco.loadfile(path) os.remove(path) local stage spawn(function () stage = 0 local res, extra = system.resume(co) assert(res == true) assert(extra == "hello") assert(co:status() == "suspended") stage = 1 local res, extra = system.resume(co) assert(res == true) assert(extra == "bye") assert(co:status() == "dead") stage = 2 end) assert(co:status() == "running") assert(stage == 0) if standard == "posix" then assert(system.run("step") == true) assert(stage == 1) end assert(system.run() == false) assert(stage == 2) done() end do case "inherit preload" spawn(function () package.preload["coutil.spawn"] = assert(package.searchers[2]("coutil.spawn")) package.preload["coutil.system"] = assert(package.searchers[4]("coutil.system")) local co = stateco.load[[ local package = require "package" package.path = "" package.cpath = "" require "coutil.spawn" require "coutil.system" return true ]] package.preload["coutil.spawn"] = nil package.preload["coutil.system"] = nil local ok, res = system.resume(co) assert(ok == true and res == true) end) assert(system.run() == false) done() end
--- A simple colour class. -- Is converted to a [JUCE Colour](http://www.juce.com/api/classColour.html) -- @classmod juce.Colour --- Constuctor with classical arguments. -- @param r red -- @param g green -- @param b blue -- @param[opt] a alpha -- @within Constructors -- @constructor -- @function Colour --- Constuctor with named arguments. -- Every field is optional. -- @tparam table args -- @param args.r red -- @param args.g green -- @param args.b blue, -- @param args.a alpha -- @within Constructors -- @constructor -- @function Colour local Colour = setmetatable({}, { __call = function (self, ...) local c = {} c.r, c.g, c.b, c.a = ... if type(c.r)=="table" then c = c.r end c.a = c.a or 0xff return ffi.new("Colour",c) end }) local Colour_mt = { -- operator '==' __eq = function(self, rhs) return self.argb == rhs.argb end; } ffi.metatype("Colour", Colour_mt); Colour.black = Colour() Colour.white = Colour(255,255,255) Colour.red = Colour(255,0,0) Colour.green = Colour(0,255,0) Colour.blue = Colour(0,0,255) --- Red (0-255) -- @simplefield r --- Green (0-255) -- @simplefield g --- Blue (0-255) -- @simplefield b --- Alpha (0-255) -- @simplefield a --- @predefined black --- @predefined white --- @predefined red --- @predefined green --- @predefined blue return Colour
ClassType = require('ClassType.init') Utils = require('Utils.init') local Object = { _type = ClassType.OBJECT } function Object:new(class) if string.lower(class._type) == 'class' then local o = {} Utils:clone(o, class) setmetatable(o, { __index = Object, __newindex = function(t, k, v) if (t._type == 'object') then local getName = Utils:getGetName(k) local setName = Utils:getSetName(k) if type(t[setName]) == 'function' then print('Assigning ', k, v, getName, setName) t[setName](t, v) else error(string.format('Unknown property `%s`', k)) end end end }) return o else error('Invalid class to create the object') end end function Object:typeof(typeName) assert((type(typeName) == 'string'), 'typeof() argument should be string') if string.lower(self._type) == string.lower(typeName) then return true end return false end return Object
local udtype = require("udtype") local typex = udtype.type print ("Commencing module test for 'udtype'") --io.read() assert(typex("hello") == "string", "expected string") assert(typex(nil) == "nil", "expected nil") assert(typex(13) == "number", "expected number") assert(typex(true) == "boolean", "expected boolean") assert(typex( {} ) == "table", "expected table") local socket = require("socket") local sock = socket.tcp() local sock2 = socket.tcp() assert(typex(sock) == typex(sock2), "expected both sockets to have same metatable") print ("Module udtype test succeeded!") --io.read()
-- http://query.yahooapis.com/v1/public/yql?q=select%20item.forecast%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22munic%2C%20de%22)%20and%20u%3D%27c%27%20limit%203&format=json yaw = { url1 = "GET /v1/public/yql?q=select%20item.forecast%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22", url2 = "%2C%20", url3 = "%22)%20and%20u%3D%27c%27%20limit%203&format=json", city = "munic", country = "de", server = "query.yahooapis.com", port = 80, timerId = 2, syncPeriodSec = 3600, -- sync weather every hour -- weather tabel contains forecast for x days -- K: day number starting from 1, where 1 is today, 2 tomorrow, and so on. -- V: table containing following keys: -- low - min temp in celclus -- high - max temp in celclus -- day - 3 letter day code, like: Tue or Mon -- code - https://developer.yahoo.com/weather/documentation.html#codes -- date - date in form: 31 Aug 2016 -- text - description, like: Partly Cloudy, Thunderstorms or Sunny -- examples: -- - yaw.weather[1].low -- - yaw.weather[2].date weather = nil, responseCallback = nil } local con local stats = { yahooReqTime = -1,-- time in sec of last response from DNS server and request to yahoo yahooRespTime = -1, -- time in sec of last response from yahoo dnsReqTime = -1, -- time in sec of last request to DNS server, ip = 0 -- ip of yahoo server } local function parseWeather(jsonStr) local json = cjson.decode(jsonStr) local weather = {} local day = 1 for k,v in pairs(json.query.results.channel) do for _,forecast in pairs(v.item) do weather[day] = forecast; day = day + 1 end end return weather; end local function findJsonEnd(body) local len = string.len(body) for idx = len, 1, -1 do local char = body:sub(idx, idx) if char == '}' then return idx end end return len end local function extraactJson(body) local bodyStart = string.find(body, "\n\r", 1) local jsonStart = string.find(body, "{", bodyStart) local jsonEnd = findJsonEnd(body); local jsonStr = string.sub(body, jsonStart, jsonEnd) return jsonStr end local function onReceive(cn, body) stats.yahooRespTime = tmr.time() cn:close() con = nil local jsonStr = extraactJson(body) yaw.weather = parseWeather(jsonStr) if yaw.responseCallback ~= nil then yaw.responseCallback() end end local function onConnection(sck, c) local get = yaw.url1..yaw.city..yaw.url2..yaw.country..yaw.url3.. " HTTP/1.1\r\nHost: "..yaw.server.."\r\nAccept: */*\r\n\r\n" sck:send(get) end local function onDNSResponse(con, ip) if ip == nil then stats.ip = 0; return end stats.ip = ip; stats.yahooReqTime = tmr.time() con:connect(yaw.port, ip) end local function requestWeather() if con ~= nil then con:close() end con = net.createConnection(net.TCP, 0) con:on("receive", onReceive) con:on("connection", onConnection) stats.dnsReqTime = tmr.time() con:dns(yaw.server, onDNSResponse) end local function onTimer() wlan.execute(requestWeather) end function yaw.start() onTimer() tmr.alarm(yaw.timerId, yaw.syncPeriodSec * 1000, tmr.ALARM_AUTO, onTimer) end local mt = {} function yaw.lastSyncSec() local lastSyncSec = -1 if stats.yahooRespTime ~= -1 then lastSyncSec = tmr.time() - stats.yahooRespTime end return lastSyncSec; end mt.__tostring = function(yaw) return string.format("YAW->%d,%s,DNS_RQ:%d,Y_RQ:%d,Y_RS:%d", yaw.lastSyncSec(), stats.ip, stats.dnsReqTime, stats.yahooReqTime, stats.yahooRespTime) end setmetatable(yaw, mt)
-- ~/.config/nvim/lua/bootstrap.lua: -- automatically install `chiyadev/dep` on startup local path = vim.fn.stdpath "data" .. "/site/pack/deps/opt/dep" if vim.fn.empty(vim.fn.glob(path)) > 0 then vim.fn.system { "git", "clone", "--depth=1", "https://github.com/chiyadev/dep", path, } end vim.cmd "packadd dep"
local K, C = unpack(select(2, ...)) if C["Unitframe"].Enable ~= true then return end local Module = K:GetModule("Unitframes") local oUF = oUF or K.oUF if not oUF then K.Print("Could not find a vaild instance of oUF. Stopping FocusTarget.lua code!") return end local _G = _G local CreateFrame = _G.CreateFrame local UnitFrame_OnEnter = _G.UnitFrame_OnEnter local UnitFrame_OnLeave = _G.UnitFrame_OnLeave function Module:CreateFocusTarget() local UnitframeFont = K.GetFont(C["UIFonts"].UnitframeFonts) local UnitframeTexture = K.GetTexture(C["UITextures"].UnitframeTextures) self:RegisterForClicks("AnyUp") self:SetScript("OnEnter", function(self) UnitFrame_OnEnter(self) if (self.Highlight and not self.Highlight:IsShown()) then self.Highlight:Show() end end) self:SetScript("OnLeave", function(self) UnitFrame_OnLeave(self) if (self.Highlight and self.Highlight:IsShown()) then self.Highlight:Hide() end end) self.Health = CreateFrame("StatusBar", "$parent.Healthbar", self) self.Health:SetSize(74, 12) self.Health:SetPoint("CENTER", self, "CENTER", 15, 7) self.Health:SetStatusBarTexture(UnitframeTexture) self.Health:CreateBorder() self.Health.colorTapping = true self.Health.colorDisconnected = true self.Health.colorSmooth = false self.Health.colorClass = true self.Health.colorReaction = true self.Health.frequentUpdates = false self.Health.Value = self.Health:CreateFontString(nil, "OVERLAY") self.Health.Value:SetPoint("CENTER", self.Health, "CENTER", 0, 0) self.Health.Value:SetFontObject(UnitframeFont) self.Health.Value:SetFont(select(1, self.Health.Value:GetFont()), 10, select(3, self.Health.Value:GetFont())) self:Tag(self.Health.Value, "[KkthnxUI:HealthPercent]") self.Power = CreateFrame("StatusBar", nil, self) self.Power:SetSize(74, 8) self.Power:SetPoint("TOP", self.Health, "BOTTOM", 0, -6) self.Power:SetStatusBarTexture(UnitframeTexture) self.Power:CreateBorder() self.Power.colorPower = true self.Power.frequentUpdates = true if C["Unitframe"].ShowPortrait then if (C["Unitframe"].PortraitStyle.Value == "ThreeDPortraits") then self.Portrait = CreateFrame("PlayerModel", nil, self) self.Portrait:SetSize(26, 26) self.Portrait:SetPoint("LEFT", self, 4, 0) self.Portrait:SetAlpha(0.9) self.Portrait.Borders = CreateFrame("Frame", nil, self) self.Portrait.Borders:SetPoint("LEFT", self, 4, 0) self.Portrait.Borders:SetSize(26, 26) self.Portrait.Borders:CreateBorder() self.Portrait.Borders:CreateInnerShadow() elseif (C["Unitframe"].PortraitStyle.Value ~= "ThreeDPortraits") then self.Portrait = self.Health:CreateTexture("$parentPortrait", "BACKGROUND", nil, 1) self.Portrait:SetTexCoord(0.15, 0.85, 0.15, 0.85) self.Portrait:SetSize(26, 26) self.Portrait:SetPoint("LEFT", self, 4, 0) self.Portrait.Borders = CreateFrame("Frame", nil, self) self.Portrait.Borders:SetPoint("LEFT", self, 4, 0) self.Portrait.Borders:SetSize(26, 26) self.Portrait.Borders:CreateBorder() if (C["Unitframe"].PortraitStyle.Value == "ClassPortraits" or C["Unitframe"].PortraitStyle.Value == "NewClassPortraits") then self.Portrait.PostUpdate = Module.UpdateClassPortraits end end end self.Name = self:CreateFontString(nil, "OVERLAY") self.Name:SetPoint("BOTTOM", self.Power, "BOTTOM", 0, -16) self.Name:SetSize(74, 14) self.Name:SetJustifyV("BOTTOM") self.Name:SetJustifyH("CENTER") self.Name:SetFontObject(UnitframeFont) self.Name:SetWordWrap(false) self:Tag(self.Name, "[KkthnxUI:GetNameColor][KkthnxUI:NameShort]") if C["Unitframe"].MouseoverHighlight then Module.MouseoverHealth(self, "focustarget") end self.Threat = { Hide = K.Noop, IsObjectType = K.Noop, Override = Module.CreateThreatIndicator, } self.Range = Module.CreateRangeIndicator(self) end
---protobuf模块 --@script gg.codec.protobuf --@author sundream --@release 2018/12/25 10:30:00 --@usage --一个完整的protobuf包格式如下 -- ----------------- -- |len|header|body| -- ----------------- -- len为2字节大端,表示header的长度 -- header是消息头,是一个protobuf消息,一般包含消息ID,会话ID等数据 -- body是消息体,是一个protobuf消息(消息ID在header中指定) local pb = require "pb" local protobuf = setmetatable({},{__index=pb}) function protobuf.new(conf) local pbfile = assert(conf.pbfile) local idfile = assert(conf.idfile) local self = { pbfile = pbfile, idfile = idfile, message_define = {} } self.MessageHeader = conf.MessageHeader or "MessageHeader" setmetatable(self,{__index=protobuf}) self:reload() return self end function protobuf:reload() protobuf.clear() protobuf.loadfile(self.pbfile) self.message_define = {} local fd = io.open(self.idfile,"rb") for line in fd:lines() do local message_id,message_name = string.match(line,'%[(%d+)%]%s+=%s+"([%w_.]+)"') if message_id and message_name then message_id = assert(tonumber(message_id)) assert(self.message_define[message_name] == nil) assert(self.message_define[message_id] == nil) self.message_define[message_name] = message_id self.message_define[message_id] = message_name end end fd:close() end local header_tmp = {} function protobuf:unpack_message(msg) local MessageHeader = self.MessageHeader local header_bin,size = string.unpack(">s2",msg) local header,err = protobuf.decode(MessageHeader,header_bin) assert(err == nil,err) local message_id = header.type local message_name = assert(self.message_define[message_id],"unknow message_id:" .. message_id) local args if #msg >= size then local args_bin = string.sub(msg,size,#msg) args,err = protobuf.decode(message_name,args_bin) assert(err == nil,err) end if header.request then -- request return { type = 1, cmd = message_name, args = args, --tag = message_id, session = header.session, ud = header.ud, } else -- response assert(header.session,"session not found") return { type = 2, cmd = message_name, args = args, --tag = message_id, session = header.session, ud = header.ud, } end end function protobuf:pack_message(message) local is_request = message.type == 1 local message_name = message.cmd local session = message.session local ud = message.ud local args = message.args if is_request then return self:pack_request(message_name,args,session,ud) else return self:pack_response(message_name,args,session,ud) end end function protobuf:pack_request(message_name,request,session,ud) if session == 0 then session = nil end local message_id = assert(self.message_define[message_name],"unknow message_name: " .. message_name) header_tmp.type = message_id header_tmp.session = session header_tmp.ud = ud header_tmp.request = true local MessageHeader = self.MessageHeader local header = protobuf.encode(MessageHeader,header_tmp) if request then local body = protobuf.encode(message_name,request) return string.pack(">s2",header) .. body else return string.pack(">s2",header) end end function protobuf:pack_response(message_name,response,session,ud) local message_id = assert(self.message_define[message_name],"unknow message_name: " .. message_name) header_tmp.type = message_id header_tmp.session = session header_tmp.ud = ud header_tmp.request = false local MessageHeader = self.MessageHeader local header = protobuf.encode(MessageHeader,header_tmp) if response then local body = protobuf.encode(message_name,response) return string.pack(">s2",header) .. body else return string.pack(">s2",header) end end return protobuf
u_execScript("common.lua") -- pAltBarrage: spawns a series of cAltBarrage function pAltBarrage(mTimes, mStep) local delay = getPerfectDelayDM(THICKNESS) * 5.6 for i = 0, mTimes do cAltBarrage(i, mStep) t_wait(delay) end t_wait(delay) end -- pSpiralDir: spawns a spiral of cWallEx function pSpiralDir(mLoopDir, mTimes, mExtra) local oldThickness = THICKNESS THICKNESS = getPerfectThickness(THICKNESS) * l_getDelayMult() local delay = getPerfectDelay(THICKNESS) / l_getDelayMult() * 0.9 -- overlap a bit to avoid going through gaps local startSide = getRandomSide() local loopDir = mLoopDir local j = 0 for i = 0, mTimes do cWallEx(startSide + j, mExtra) j = j + loopDir t_wait(delay) end THICKNESS = oldThickness t_wait(getPerfectDelayDM(THICKNESS) * 6.5) end -- pSpiral: spawns a spiral of cWallEx function pSpiral(mTimes, mExtra) pSpiralDir(getRandomDir(), mTimes, mExtra) end -- pMirrorSpiral: spawns a spiral of rWallEx function pMirrorSpiral(mTimes, mExtra) local oldThickness = THICKNESS THICKNESS = getPerfectThickness(THICKNESS) * l_getDelayMult() local delay = getPerfectDelay(THICKNESS) / l_getDelayMult() * 0.9 -- overlap a bit to avoid going through gaps local startSide = getRandomSide() local loopDir = getRandomDir() j = 0 for i = 0, mTimes do rWallEx(startSide + j, mExtra) j = j + loopDir t_wait(delay) end THICKNESS = oldThickness t_wait(getPerfectDelayDM(THICKNESS) * 6.5) end -- pMirrorSpiralDouble: spawns a spiral of rWallEx where you need to change direction function pMirrorSpiralDouble(mTimes, mExtra) local oldThickness = THICKNESS THICKNESS = getPerfectThickness(THICKNESS) * l_getDelayMult() local delay = getPerfectDelayDM(THICKNESS) / l_getDelayMult() * 0.9 -- overlap a bit to avoid going through gaps local startSide = getRandomSide() local loopDir = getRandomDir() local j = 0 for i = 0, mTimes do rWallEx(startSide + j, mExtra) j = j + loopDir t_wait(delay) end rWallEx(startSide + j, mExtra) t_wait(delay * 0.9) for i = 0, mTimes + 1 do rWallEx(startSide + j, mExtra) j = j - loopDir t_wait(delay) end THICKNESS = oldThickness t_wait(getPerfectDelayDM(THICKNESS) * 7.5) end -- pBarrageSpiral: spawns a spiral of cBarrage function pBarrageSpiral(mTimes, mDelayMult, mStep) local delay = getPerfectDelayDM(THICKNESS) * 5.6 * mDelayMult local startSide = getRandomSide() local loopDir = mStep * getRandomDir() local j = 0 for i = 0, mTimes do cBarrage(startSide + j) j = j + loopDir t_wait(delay) if(l_getSides() < 6) then t_wait(delay * 0.6) end end t_wait(getPerfectDelayDM(THICKNESS) * 6.1) end -- pDMBarrageSpiral: spawns a spiral of cBarrage, with static delay function pDMBarrageSpiral(mTimes, mDelayMult, mStep) local delay = (getPerfectDelayDM(THICKNESS) * 5.42) * (mDelayMult / (u_getDifficultyMult() ^ 0.4)) * (u_getSpeedMultDM() ^ 0.35) local startSide = getRandomSide() local loopDir = mStep * getRandomDir() local j = 0 for i = 0, mTimes do cBarrage(startSide + j) j = j + loopDir t_wait(delay) if(l_getSides() < 6) then t_wait(delay * 0.49) end end t_wait(getPerfectDelayDM(THICKNESS) * (6.7 * (u_getDifficultyMult() ^ 0.7))) end -- pWallExVortex: spawns left-left right-right spiral patters function pWallExVortex(mTimes, mStep, mExtraMult) local delay = getPerfectDelayDM(THICKNESS) * 5.0 local startSide = getRandomSide() local loopDir = getRandomDir() local currentSide = startSide for j = 0, mTimes do for i = 0, mStep do currentSide = currentSide + loopDir rWallEx(currentSide, loopDir * mExtraMult) t_wait(delay) end loopDir = loopDir * -1 for i = 0, mStep + 1 do currentSide = currentSide + loopDir rWallEx(currentSide, loopDir * mExtraMult) t_wait(delay) end end t_wait(getPerfectDelayDM(THICKNESS) * 5.5) end -- pInverseBarrage: spawns two barrages who force you to turn 180 degrees function pInverseBarrage(mTimes) local delay = getPerfectDelayDM(THICKNESS) * 9.9 local startSide = getRandomSide() for i = 0, mTimes do cBarrage(startSide) t_wait(delay) if(l_getSides() < 6) then t_wait(delay * 0.8) end cBarrage(startSide + getHalfSides()) t_wait(delay) end t_wait(getPerfectDelayDM(THICKNESS) * 2.5) end -- pRandomBarrage: spawns barrages with random side, and waits humanly-possible times depending on the sides distance function pRandomBarrage(mTimes, mDelayMult) local side = getRandomSide() local oldSide = 0 for i = 0, mTimes do cBarrage(side) oldSide = side side = getRandomSide() t_wait(getPerfectDelayDM(THICKNESS) * (2 + (getSideDistance(side, oldSide)*mDelayMult))) end t_wait(getPerfectDelayDM(THICKNESS) * 5.6) end -- pMirrorWallStrip: spawns rWalls close to one another on the same side function pMirrorWallStrip(mTimes, mExtra) local delay = getPerfectDelayDM(THICKNESS) * 3.65 local startSide = getRandomSide() for i = 0, mTimes do rWallEx(startSide, mExtra) t_wait(delay) end t_wait(getPerfectDelayDM(THICKNESS) * 5.00) end -- pTunnel: forces you to circle around a very thick wall function pTunnel(mTimes) local oldThickness = THICKNESS local myThickness = getPerfectThickness(THICKNESS) local delay = getPerfectDelay(myThickness) * 5 local startSide = getRandomSide() local loopDir = getRandomDir() THICKNESS = myThickness for i = 0, mTimes do if i < mTimes then w_wall(startSide, myThickness + 5 * u_getSpeedMultDM() * delay) end cBarrage(startSide + loopDir) t_wait(delay) loopDir = loopDir * -1 end THICKNESS = oldThickness end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end nyagos.alias.lua_e=function(args) if #args >= 1 then local f,err =loadstring(args[1]) if f then f() else io.stderr:write(err,"\n") end end end nyagos.alias.lua_f=function(args) local save=_G["arg"] local script = args[1] local param = {} for i=1,#args do param[i-1] = args[i] end local f, err = loadfile(script) _G["arg"] = param if f then f() else io.stderr:write(err,"\n") end _G["arg"] = save end -- on chcp, font-width is changed. nyagos.alias.chcp = function(args) nyagos.resetcharwidth() nyagos.rawexec(args[0],(table.unpack or unpack)(args)) end -- wildcard expand for external commands nyagos.alias.wildcard = function(args) local newargs = {} for i=1,#args do local tmp = nyagos.glob(args[i]) for j=1,#tmp do newargs[ #newargs+1] = tmp[j] end end -- for i=1,#newargs do print(newargs[i]) end nyagos.exec( newargs ) end -- print the absolute path function nyagos.alias.abspath(args) local cwd = nyagos.getwd() for i = 1,#args do local path1 = nyagos.pathjoin(cwd,args[i]) nyagos.write(path1) nyagos.write("\n") end end -- chompf - cut last CRLF of the files and output them to STDOUT function nyagos.alias.chompf(args) local lf="" if #args <= 0 then for line in nyagos.lines() do nyagos.write(lf) nyagos.write(line) lf = "\n" end else for i=1,#args do for line in nyagos.lines(args[i]) do nyagos.write(lf) nyagos.write(line) lf = "\n" end end end end
local render = { sx = love.graphics.getWidth(), sy = love.graphics.getHeight(), x = 0, y = 0, zoom = 1, zoomTarget = 1, } render.update = function(dt) render.dt = dt render.sx = love.graphics.getWidth() render.sy = love.graphics.getHeight() render.zoom = render.zoom + (render.zoomTarget - render.zoom)*dt*10 end render.wheelmoved = function(x, y) if search.open then return end render.zoomTarget = math.max(math.min(render.zoomTarget + y/5, 3), 0.2) end render.getScreenFromWorldPosition = function(x, y) return render.sx/2 + x*render.zoom + render.x*render.zoom, render.sy/2 + y*render.zoom + render.y*render.zoom end render.getWorldFromScreenPosition = function(x, y) return (x - render.sx/2)/render.zoom - render.x, (y - render.sy/2)/render.zoom - render.y end render.drawBackground = function() local sx, sy = render.sx, render.sy dxDrawImageSection(sx/2, sy/2, sx/2, -sy/2, -render.x*0.8+1, render.y*0.8+1, sx/2/render.zoom, sy/2/render.zoom, "data/themes/" .. themes.current .. "/bg.png") dxDrawImageSection(sx/2, sy/2, -sx/2, -sy/2, render.x*0.8+1, render.y*0.8+1, sx/2/render.zoom, sy/2/render.zoom, "data/themes/" .. themes.current .. "/bg.png") dxDrawImageSection(sx/2, sy/2, -sx/2, sy/2, render.x*0.8+1, -render.y*0.8+1, sx/2/render.zoom, sy/2/render.zoom, "data/themes/" .. themes.current .. "/bg.png") dxDrawImageSection(sx/2, sy/2, sx/2, sy/2, -render.x*0.8+1, -render.y*0.8+1, sx/2/render.zoom, sy/2/render.zoom, "data/themes/" .. themes.current .. "/bg.png") end render.quadLine = function(from, to, approx, color) setColor(color) local prevx, prevy local sx, sy = love.graphics.getDimensions() if from.x >= 0 and from.y >= 0 and from.x <= sx and from.y <= sy and to.x >= 0 and to.y >= 0 and to.x <= sx and to.y <= sy then for t = 0, 1, 0.01 do local x = (1-t)^2*from[1] + 2*(1-t)*t*approx[1] + t^2*to[1] local y = (1-t)^2*from[2] + 2*(1-t)*t*approx[2] + t^2*to[2] if prevx then love.graphics.line(prevx,prevy,x,y) end prevx, prevy = x, y end end end render.cubicLine = function(from, to, approx, approx2, color, size) local prevx, prevy setColor(color) for t = 0, 1, 0.02 do local x = (1-t)^3*from[1] + 3*(1-t)^2*t*approx[1] + 3*(1-t)*t^2*approx2[1] + t^3*to[1] local y = (1-t)^3*from[2] + 3*(1-t)^2*t*approx[2] + 3*(1-t)*t^2*approx2[2] + t^3*to[2] if prevx then love.graphics.line(prevx,prevy,x,y) end prevx, prevy = x, y end end render.grabScene = function() if render.holdScene then if love.mouse.isDown(1) then local cx, cy = love.mouse.getPosition() render.x = render.x + (cx - render.holdScene[1])/render.zoom render.y = render.y + (cy - render.holdScene[2])/render.zoom render.holdScene = {cx, cy} else render.holdScene = false end else if love.mouse.isDown(1) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open and not saving.open and not blocks.changingPickerColor then local cx, cy = love.mouse.getPosition() render.holdScene = {cx, cy} end end local touches = love.touch.getTouches() if #touches == 2 then local lx, ly = love.touch.getPosition(touches[1]) local rx, ry = love.touch.getPosition(touches[2]) if lx < rx then local _lx = lx lx = rx rx = _lx end if render.mobileGrab then local ldiff = lx - render.mobileGrab[1] local rdiff = render.mobileGrab[2] - rx render.zoomTarget = math.max(math.min(render.zoomTarget + (ldiff + rdiff)/100, 3), 0.2) end render.mobileGrab = {lx, rx} else render.mobileGrab = false end end render.drawUI = function() local sx, sy = love.graphics.getDimensions() dxDrawImage(20, sy - 80, 60, 60, "data/themes/" .. themes.current .. "/add.png") dxDrawImage(80, sy - 80, 60, 60, "data/themes/" .. themes.current .. "/new.png") dxDrawImage(140, sy - 80, 60, 60, "data/themes/" .. themes.current .. "/save.png") dxDrawImage(200, sy - 80, 60, 60, "data/themes/" .. themes.current .. "/load.png") dxDrawImage(260, sy - 80, 60, 60, "data/themes/" .. themes.current .. "/code.png") dxDrawImage(320, sy - 80, 60, 60, "data/themes/" .. themes.current .. "/settings.png") end render.clickUI = function(btn) local sx, sy = love.graphics.getDimensions() if isMouseInPosition(20, sy - 80, 60, 60) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open and not saving.open then search.open = true search.x = sx/2 - 100 search.y = sy/2 - 100 search.text = "" elseif isMouseInPosition(80, sy - 80, 60, 60) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open then if (lastnew or 0) > tickCount - 500 then blocks.blocks = {} end lastnew = tickCount elseif isMouseInPosition(140, sy - 80, 60, 60) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open then saving.loadSaves() saving.open = true saving.type = "save" elseif isMouseInPosition(200, sy - 80, 60, 60) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open then saving.loadSaves() saving.open = true saving.type = "load" elseif isMouseInPosition(260, sy - 80, 60, 60) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open and not saving.open then code.showCode() elseif isMouseInPosition(320, sy - 80, 60, 60) and not blocks.grabBlock and not blocks.holdConnection and not search.open and not code.open and not saving.open then settings.showSettings() end end local runs = http.request("http://jitter.mtasa.eu/runs.php") render.drawScene = function() love.graphics.setDefaultFilter("nearest", "nearest", 1) render.drawBackground() local sx, sy = love.graphics.getDimensions() if not render.selectedLanguage then fonts.drawText("bold", 30, "Select language", 0, -sy/2+200, sx, sy, white, false, "center", "center") dxDrawImage(sx/2 - 350, 50, 200, 120, "data/en.png", {255, 255, 255, isMouseInPosition(sx/2 - 350, 50, 200, 120) and 200 or 100}) dxDrawImage(sx/2 + 150, 50, 200, 120, "data/pl.png", {255, 255, 255, isMouseInPosition(sx/2 + 150, 50, 200, 120) and 200 or 100}) fonts.drawText("bold", 18, "American English", sx/2 - 350, 130, 200, 120, white, false, "center", "center") fonts.drawText("bold", 16, "Polish (Temp not working)", sx/2 + 150, 130, 200, 120, white, false, "center", "center") fonts.drawText("bold", 40, "BETA TESTY 0.45", 10, sy/2, sx, sy) fonts.drawText("regular", 25, "Ostatnie aktualizacje", 10, sy/2+35, sx, sy) fonts.drawText("regular", 15, "• Błędy logiczne generatora\n\n\n\n\n• Tworzenie GUI w następnej aktualizacji", 10, sy/2+70, sx, sy) if isMouseInPosition(sx/2 - 350, 50, 200, 120) and love.mouse.isDown(1) then render.selectedLanguage = true languages.current = "EN" discordrpc.topText = "Working on Untitled Project" elseif isMouseInPosition(sx/2 + 150, 50, 200, 120) and love.mouse.isDown(1) then render.selectedLanguage = true languages.current = "PL" discordrpc.topText = "Pracuje nad Bez Nazwy" end return end love.graphics.setDefaultFilter(themes.getFilterMode(), themes.getFilterMode(), 1) blocks.drawBlocks() search.drawSearch() render.grabScene() render.drawUI() saving.renderSaving() code.renderCode() dxDrawImage(sx - 120, sy - 45, 110, 40, "data/logo.png") --fonts.richText("regular", 15, "{ff0000}te{00ff00}st", 50, 50) local text = "x: " .. math.floor(render.x) .. "\ny: " .. math.floor(render.y) .. "\nfps: " .. love.timer.getFPS() .. "\ntheme: " .. themes.current .. "\nzoom: " .. ("%.2f"):format(render.zoom) .. "\nsession: " .. math.floor(tickCount/1000) .. "s" --fonts.drawText("regular", 13, "Total program runs: " .. tonumber(runs or 0), 0, render.sy - 35, render.sx, 50, white, false, "center", "center") --fonts.drawText("regular", 15, text, render.sx - fonts.getWidth("regular", 15, text) - 5, render.sy - fonts.getHeight("regular", 15)*6, render.sx, render.sy) end return render
client_async = require "websocket.client_async" connected=false function init(self) self.ws = client_async({ connect_timeout = 5, -- optional timeout (in seconds) when connecting }) self.ws:on_connected(function(ok, err) if ok then print("Connected") connected = true else print("Unable to connect", err, msg) end end) self.ws:on_disconnected(function() print("Disconnected") end) self.ws:on_message(function(message) print("Received message", message) end) local sslparams = { mode = "client", protocol = "tlsv1_2", verify = "none", options = "all", } self.ws:connect("wss://echo.websocket.org", "wss", sslparams) --self.ws:connect("ws://121.40.165.18:8800") end function update(self, dt) self.ws:step() end copas=require'copas' copas.addthread(function() ctx={} init(ctx) cnt=0 while true do update(ctx) cnt=cnt+1 if cnt==1 then if connected then print('send') ctx.ws:send('test') end end if cnt>200000 then cnt=0 end end end)
vim.cmd [[ let dirvish_mode = ':sort ,^.*/,' command! -nargs=? -complete=dir Explore Dirvish <args> command! -nargs=? -complete=dir Sexplore belowright split | silent Dirvish <args> command! -nargs=? -complete=dir Vexplore leftabove vsplit | silent Dirvish <args> "augroup dirvish_config " autocmd! " autocmd FileType dirvish " \ nnoremap <silent><buffer> <C-v> :call dirvish#open('vsplit', 0)<CR> " \ xnoremap <silent><buffer> <C-v> :call dirvish#open('vsplit', 0)<CR> " \ nnoremap <silent><buffer> <C-x> :call dirvish#open('split', 0)<CR> " \ xnoremap <silent><buffer> <C-x> :call dirvish#open('split', 0)<CR> "augroup END ]]
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:26' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_GiftInventoryReturned_Gamepad = ZO_GiftInventoryCategory_Gamepad:Subclass() function ZO_GiftInventoryReturned_Gamepad:New(...) return ZO_GiftInventoryCategory_Gamepad.New(self, ...) end function ZO_GiftInventoryReturned_Gamepad:Initialize(control) ZO_GiftInventoryCategory_Gamepad.Initialize(self, control) self:SetNoItemText(GetString(SI_GIFT_INVENTORY_NO_RETURNED_GIFTS)) self:AddSupportedGiftState(GIFT_STATE_RETURNED, "ZO_GamepadGiftWithNoteEntryTemplate", ZO_GiftInventoryCategory_Gamepad.GiftWithNoteSetupFunction) table.insert(self.keybindStripDescriptor, { -- Send name = GetString(SI_GIFT_INVENTORY_SEND_KEYBIND), keybind = "UI_SHORTCUT_PRIMARY", visible = function() local targetData = self:GetTargetData() return targetData ~= nil end, callback = function() local targetData = self:GetTargetData() targetData.gift:View() targetData.gift:RequestResendGift() GIFT_INVENTORY_GAMEPAD:OnRequestResendGift() end, }) end -- begin ZO_GiftInventoryCategory_Gamepad overrides function ZO_GiftInventoryReturned_Gamepad:CreateGiftEntryData(gift) local formattedGiftName = gift:GetFormattedName() local icon = gift:GetIcon() local entryData = ZO_GamepadEntryData:New(formattedGiftName, icon) entryData:SetModifyTextType(MODIFY_TEXT_TYPE_NONE) entryData:SetIconTintOnSelection(true) entryData:SetStackCount(gift:GetStackCount()) local formattedPlayerName = zo_strformat(SI_GAMEPAD_GIFT_INVENTORY_FROM_FORMATTER, gift:GetUserFacingPlayerName()) entryData:AddSubLabel(formattedPlayerName) entryData.gift = gift return entryData end function ZO_GiftInventoryReturned_Gamepad:UpdateTooltip() local selectedData = self:GetSelectedData() if selectedData and self.shouldShowTooltip then local gift = selectedData.gift GAMEPAD_TOOLTIPS:LayoutReturnedGift(GAMEPAD_LEFT_TOOLTIP, gift:GetName(), gift:GetUserFacingPlayerName(), gift:GetNote()) else GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_LEFT_TOOLTIP) end end -- end ZO_GiftInventoryCategory_Gamepad overrides
Number_Properties_Priority = 1.0 -- Default - on conflict higher is used... Number_Properties = { } String_Properties_Priority = 1.0 String_Properties = { }
--- -- Represent numbers at compile time (to avoid loss of precision). --- do local function __eq(a, b) return (lemma.type(a) == lemma.type(b)) and (tostring(a) == tostring(b)) end local function __tostring(e) return ':'..e.str end local t = {} local mt = { class = 'Number', implements = nil, __index = t, __tostring = __tostring, __eq = __eq } Number = function(n) if lemma.type(n) ~= 'string' then return error('Number objects serve to wrap numbers (as strings) at'.. 'compile time. (Got '..lemma.type(n)..')') end local o = { str = n } setmetatable(o, mt) return o end function t:string() return self.str end end
_VERSION = 'v5 2021-12-10' --[[-- ---------------------------------------------------------------------------- Kartaverse - OpenUSD Scene Exporter - v5 2021-12-10 04.42 PM by Andrew Hazelden www.andrewhazelden.com andrew@andrewhazelden.com Overview --------- The "OpenUSD Scene Exporter" script allows you to export PIXAR USD ASCII (.usda) data, along with Maya ASCII 2019 (.ma), Maya MOVE ASCII (.mov), XYZ ASCII (.xyz), and PLY ASCII (.ply) format data. Scenegraph Export Options -------------------------- AlembicMesh3D nodes can be exported to the PIXAR USD ASCII (.usda), Maya ASCII 2019 (.ma), and Maya MOVE ASCII (.mov) format. Camera3D nodes with per-frame Keyframe animated XYZ translation/rotation keys can be exported to the PIXAR USD ASCII (.usda), and Maya MOVE ASCII (.mov) format. PointCloud3D node based points or FBXMesh3D node OBJ mesh vertices can be exported to XYZ ASCII (.xyz), and PLY ASCII (.ply) formats. Static (non-animated) Camera3D nodes can be exported to the Maya ASCII 2019 (.ma) format. Keyframe animated FBXMesh3D nodes with per-frame XYZ translation/rotation keys can be exported to the Maya MOVE ASCII (.mov) format. The "OpenUSD Scene Exporter.lua" comp/tool script works in Fusion v9-17.4.2+ and Resolve v15-17.4.2+. Easy Installation: ------------------- The "OpenUSD Scene Exporter.lua" script is typically installed in a single click using the "Reactor" Package Manager by adding the AtomTestLab add-on repository, and then selecting the "Kartaverse/CompX/Scripts | Virtual Production" atom package. https://gitlab.com/AndrewHazelden/AtomTestLab Manual Installation: Step 1. If you are unable to use Reactor to download and install the "Kartaverse/CompX/Scripts | Virtual Production" atom package, you can always download the most recent version of the "OpenUSD Scene Exporter.lua" script directly from the CompX GitHub Repository at: https://github.com/AndrewHazelden/CompX/ Step 2. Copy the downloaded "OpenUSD Scene Exporter.lua" script to your Fusion/Resolve Fusion page user preferences' "Tool" and "Comp" based "Scripts:/" PathMap locations at: Scripts:/Tool/Kartaverse/CompX/ Scripts:/Comp/Kartaverse/CompX/ *Note: You will need to create these sub-folders by hand since they won't pre-exist on a manual install. Fusion Standalone Manual Script Install: On Windows this works out to: %AppData%\Blackmagic Design\Fusion\Scripts\Comp\Kartaverse\CompX\ %AppData%\Blackmagic Design\Fusion\Scripts\Tool\Kartaverse\CompX\ On Linux this works out to: $HOME/.fusion/BlackmagicDesign/Fusion/Scripts/Comp/Kartaverse/CompX/ $HOME/.fusion/BlackmagicDesign/Fusion/Scripts/Tool/Kartaverse/CompX/ On MacOS this works out to: $HOME/Library/Application Support/Blackmagic Design/Fusion/Scripts/Comp/Kartaverse/CompX/ $HOME/Library/Application Support/Blackmagic Design/Fusion/Scripts/Tool/Kartaverse/CompX/ Resolve Fusion Page Manual Script Install: On Windows this works out to: %AppData%\Blackmagic Design\DaVinci Resolve\Fusion\Scripts\Comp\Kartaverse\CompX\ %AppData%\Blackmagic Design\DaVinci Resolve\Fusion\Scripts\Tool\Kartaverse\CompX\ On Linux this works out to: $HOME/.fusion/BlackmagicDesign/DaVinci Resolve/Fusion/Scripts/Comp/Kartaverse/CompX/ $HOME/.fusion/BlackmagicDesign/DaVinci Resolve/Fusion/Scripts/Tool/Kartaverse/CompX/ On MacOS this works out to: $HOME/Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts/Comp/Kartaverse/CompX/ $HOME/Library/Application Support/Blackmagic Design/DaVinci Resolve/Fusion/Scripts/Tool/Kartaverse/CompX/ Usage: Step 1. Save your Fusion composite to disk. Step 2. Select a single PointCloud3D, FBXMesh3D (OBJ mesh), AlembicMesh3D, or Camera3D node in the Flow/Nodes view. Step 3. Run the "Script > Kartaverse > CompX > OpenUSD Scene Exporter" menu item. The point cloud, mesh, or camera data will be saved to disk. Notes: - If you are exporting a Maya ASCII (.ma) point cloud you may way to adjust the Maya Locator Size "SpinBox" control to change the visible locator scale in the Maya scene file. Common values you might explore are "0.1" or "0.05" if you are working with centimetre/decimetre units as your scene size in Maya. - The Maya ASCII (.ma) exported AlembicMesh3D data is loaded in the .ma file as an "Alembic Reference Import" which works well if the ABC meshes have not been moved from their initial XYZ position in the Fusion comp. - The "Maya MOVE ASCII (.mov)" export format saves out an ASCII file that records 1 set of XYZ Translation and Rotation keyframe animation data per line of the text file. The Maya MOVE format is a very minimal data format that can be viewed in a spreadsheet. It is simply a space or tab delimited file with the raw keyframe export of an object's transform data. - Fusion v9 appears to only support the Alembic HDF5 "legacy" (pre-Maya 2014 Extension 1) era .abc mesh format. Newer Ogawa formatted abc files fail to load in my tests. This means you need to have compiled PIXAR's open source "usdview" or your USD for Maya/Katana/Houdini/etc... plugins with HDF5 support enabled if you want to interact with Fusion compatible Alembic files in an exported USD ASCII "Reference Assembly". Todo: - Save/Attempt to restore an extra "comp" scope preference for the 'CompX.OpenUSDSceneExporter.ExportDirectory' setting so each comp can restore the last output folder used for that individual project. If this comp scope setting doesn't exist then use the last global scope preference. - For Maya ASCII 2019 (.ma) "Alembic Reference Import" mode .ma settings check if Maya's relative workspace option can be used with the exported filepath for the Alembic references, then look at adding an control to define the current Maya Workspace/"File > Set Project" value in the OpenUSD Scene Exporter script UI so Maya exported relative .abc filepaths to stay relative. ---------------------------------------------------------------------------- --]]-- ------------------------------------------------------------------------ ------------------------------------------------------------------------ -- Maya ASCII Export Settings: -- Size of a Maya ASCII (.ma) locator (0.05, 0.1, and 0.2 are common values) local mayaLocatorSize = 0.2 -- Are the Maya camera attributes animated (true/false) local mayaAnimatedCamera = false ------------------------------------------------------------------------ -- Pixar USD ASCII Export Settings: -- USD ASCII scene scale = CM local metersPerUnit = 0.01 -- Maya default style Y-axis Up-coordinate system local upAxis = 'Y' -- Are the PIAR USD ASCII camera attributes animated (true/false) local usdAnimatedCamera = true ------------------------------------------------------------------------ -- Find out the current operating system platform. -- The platform local variable should be set to either "Windows", "Mac", or "Linux". local platform = (FuPLATFORM_WINDOWS and 'Windows') or (FuPLATFORM_MAC and 'Mac') or (FuPLATFORM_LINUX and 'Linux') ------------------------------------------------------------------------ -- Add the platform specific folder slash character osSeparator = package.config:sub(1,1) ------------------------------------------------------------------------ -- Home Folder -- Add the user folder path - Example: C:\Users\Administrator\ if platform == 'Windows' then homeFolder = tostring(os.getenv('USERPROFILE')) .. osSeparator else -- Mac and Linux homeFolder = tostring(os.getenv('HOME')) .. osSeparator end ------------------------------------------------------------------------ -- Set a fusion specific preference value -- Example: SetPreferenceData('Kartaverse.Version', '1.0', true) function SetPreferenceData(pref, value, status) -- comp:SetData(pref, value) fusion:SetData(pref, value) -- List the preference value if status == 1 or status == true then if value == nil then print('[Setting ' .. pref .. ' Preference Data] ' .. 'nil') else print('[Setting ' .. pref .. ' Preference Data] ' .. value) end end end ------------------------------------------------------------------------ -- Read a fusion specific preference value. If nothing exists set and return a default value -- Example: GetPreferenceData('Kartaverse.Version', 1.0, true) function GetPreferenceData(pref, defaultValue, status) -- local newPreference = comp:GetData(pref) local newPreference = fusion:GetData(pref) if newPreference then -- List the existing preference value if status == 1 or status == true then if newPreference == nil then print('[Reading ' .. pref .. ' Preference Data] ' .. 'nil') else print('[Reading ' .. pref .. ' Preference Data] ' .. newPreference) end end else -- Force a default value into the preference & then list it newPreference = defaultValue -- comp:SetData(pref, defaultValue) fusion:SetData(pref, defaultValue) if status == 1 or status == true then if newPreference == nil then print('[Creating ' .. pref .. ' Preference Data] ' .. 'nil') else print('[Creating '.. pref .. ' Preference Entry] ' .. newPreference) end end end return newPreference end ------------------------------------------------------------------------ -- Add a slash to the end of folder paths function ValidateDirectoryPath(path) if string.sub(path, -1, -1) ~= osSeparator then path = path .. osSeparator end return path end ------------------------------------------------------------------------ -- Find out the current directory from a file path -- Example: print(Dirname('/Volumes/Media/pointcloud.xyz')) function Dirname(mediaDirName) return mediaDirName:match('(.*' .. osSeparator .. ')') end ------------------------------------------------------------------------ -- Open a folder window up using your desktop file browser -- Example: openDirectory('/Volumes/Media/') function openDirectory(mediaDirName) command = nil dir = Dirname(mediaDirName) if platform == 'Windows' then -- Running on Windows command = 'explorer "' .. dir .. '"' print('[Launch Command] ', command) os.execute(command) elseif platform == 'Mac' then -- Running on Mac command = 'open "' .. dir .. '" &' print('[Launch Command] ', command) os.execute(command) elseif platform == 'Linux' then -- Running on Linux command = 'nautilus "' .. dir .. '" &' print('[Launch Command] ', command) os.execute(command) else print('[Platform] ', platform) print('There is an invalid platform defined in the local platform variable at the top of the code.') end end -- Add duplicate slashes for Windows Filepaths in a Maya ASCII file function DupSlashes(path) path = string.gsub(path, [[\]], [[\\]]) return path end ------------------------------------------------------------------------ -- Show the UI manager GUI function OpenUSDSceneExporterWin() -- Load UI Manager ui = app.UIManager disp = bmd.UIDispatcher(ui) -- Read the open Fusion composite's name (In the Resolve Fusion page this is an empty string...) local compFile = tostring(comp:GetAttrs().COMPS_FileName) print('[Fusion Comp Source File] ' .. tostring(compFile)) -- Read the last folder accessed from a ExportDirectory preference -- The default value for the first time the RequestDir is shown in the "$HOME/Documents/" folder. local exportDirectory = GetPreferenceData('CompX.OpenUSDSceneExporter.ExportDirectory', homeFolder, false) -- Maya Locator Size local mayaLocatorSize = GetPreferenceData('CompX.OpenUSDSceneExporter.MayaLocatorSize', mayaLocatorSize, false) -- Load the Reactor icon resources PathMap local iconsDir = fusion:MapPath('Reactor:/System/UI/Images') .. 'icons.zip/' -- print('[Icons Folder] ' .. tostring(iconsDir)) -- Create a list of the standard PNG format ui:Icon/ui:Button Sizes/MinimumSizes in px local tiny = 14 local small = 16 local medium = 24 local large = 32 local long = 110 local big = 150 -- Create Lua tables with X/Y defined Icon Sizes local iconsMedium = {large,large} local iconsMediumLong = {big,large} -- Track the current node selection local selectedNode = comp.ActiveTool local selectedNodeName = '' if selectedNode then selectedNodeName = selectedNode.Name end ------------------------------------------------------------------------ -- Create the new window local epcwin = disp:AddWindow({ ID = 'OpenUSDSceneExporter', TargetID = 'OpenUSDSceneExporter', WindowTitle = 'OpenUSD Scene Exporter', Geometry = {200,100,600,155}, MinimumSize = {600, 140}, -- Spacing = 10, -- Margin = 20, ui:VGroup{ ID = 'root', ui:HGroup{ Weight = 0.01, ui:Label{ ID = 'FormatLabel', Weight = 0.1, Text = 'Export Format', }, ui:ComboBox{ ID = 'FormatCombo', }, ui:Label{ ID = 'NodeLabel', Weight = 0.2, Text = 'Selected Node', }, ui:LineEdit{ ID = 'NodeNameText', PlaceholderText = '[Select a Fusion 3D Node]', Text = selectedNodeName, ReadOnly = true, }, }, -- pointcloud Working Directory ui:HGroup{ Weight = 0.01, ui:Label{ ID = 'ExportDirectoryLabel', Weight = 0.2, Text = 'Export Directory', }, ui:HGroup{ ui:LineEdit{ ID = 'ExportDirectoryText', PlaceholderText = '', Text = exportDirectory, }, ui:Button{ ID = 'SelectFolderButton', Weight = 0.01, Text = 'Select Folder', IconSize = iconsMedium, Icon = ui:Icon{ File = iconsDir .. 'folder.png' }, MinimumSize = iconsMediumLong, Flat = true, }, }, }, ui:VGap(5), ui:HGroup{ Weight = 0, ui:Label{ ID = 'MayaLocatorSizeLabel', Weight = 0.2, Text = 'Maya Locator Size', }, ui:DoubleSpinBox{ ID = 'MayaLocatorSizeSpinner', Value = mayaLocatorSize, -- Value = 0.05, Maximum = 1000, Minimum = 0.001, StepBy = 0.1, SingleStep = 0.1, }, ui:HGap(150), }, ui:HGroup{ Weight = 0.01, ui:Button{ ID = 'CancelButton', Text = 'Cancel', IconSize = iconsMedium, Icon = ui:Icon{ File = iconsDir .. 'close.png' }, MinimumSize = iconsMedium, Flat = true, }, -- ui:HGap(20), ui:HGap(150), ui:Button{ ID = 'ContinueButton', Text = 'Continue', IconSize = iconsMedium, Icon = ui:Icon{ File = iconsDir .. 'create.png' }, MinimumSize = iconsMedium, Flat = true, }, }, } }) -- Add your GUI element based event functions here: local epcitm = epcwin:GetItems() -- The window was closed function epcwin.On.OpenUSDSceneExporter.Close(ev) epcwin:Hide() pointcloudFile = nil pointcloudData = nil disp:ExitLoop() end -- The Continue Button was clicked function epcwin.On.ContinueButton.Clicked(ev) -- Maya Locator size: mayaLocatorSize = epcitm.MayaLocatorSizeSpinner.Value -- Read the render time frame ranges startFrameGlobal = comp:GetAttrs().COMPN_GlobalStart endFrameGlobal = comp:GetAttrs().COMPN_GlobalEnd startFrame = comp:GetAttrs().COMPN_RenderStart endFrame = comp:GetAttrs().COMPN_RenderEnd renderStep = comp:GetAttrs().COMPI_RenderStep -- Read the Working Directory textfield workingDir = ValidateDirectoryPath(epcitm.ExportDirectoryText.Text) if workingDir == nil then -- Check if the working directory is empty print('[Working Directory] The textfield is empty!') else if bmd.fileexists(workingDir) == false then -- Create the working directory if it doesn't exist yet print('[Working Directory] Creating the folder: "' .. workingDir .. '"') bmd.createdir(workingDir) end -- Build the point cloud folder path pointcloudFolder = fusion:MapPath(workingDir .. osSeparator) -- Remove double slashes from the path pointcloudFolder = string.gsub(pointcloudFolder, '//', '/') pointcloudFolder = string.gsub(pointcloudFolder, '\\\\', '\\') -- Create the point cloud output folder bmd.createdir(pointcloudFolder) if bmd.fileexists(pointcloudFolder) == false then -- See if there was an error creating the pointcloud folder print('[pointcloud Folder] Error creating the folder: "' .. pointcloudFolder .. '".\nPlease select an export directory with write permissions.') disp:ExitLoop() else -- Success epcwin:Hide() -- Save a default ExportDirectory preference SetPreferenceData('CompX.OpenUSDSceneExporter.ExportDirectory', workingDir, false) -- Save the point cloud format SetPreferenceData('CompX.OpenUSDSceneExporter.PointCloudFormat', epcitm.FormatCombo.CurrentIndex, false) -- Save the Maya Locator Size Gui setting SetPreferenceData('CompX.OpenUSDSceneExporter.MayaLocatorSize', mayaLocatorSize, false) -- List the selected Node in Fusion selectedNode = comp.ActiveTool if selectedNode then local nodeName = selectedNode.Name print('[Selected Node] ' .. tostring(nodeName)) toolAttrs = selectedNode:GetAttrs() nodeType = toolAttrs.TOOLS_RegID -- Get the point cloud export format: "xyz", "ply", or "ma" local exportFormat = epcitm.FormatCombo.CurrentText local fileExt = '' if exportFormat == 'XYZ ASCII (.xyz)' then fileExt = 'xyz' elseif exportFormat == 'PLY ASCII (.ply)' then fileExt = 'ply' elseif exportFormat == 'Maya ASCII (.ma)' then fileExt = 'ma' elseif exportFormat == 'Maya MOVE ASCII (.mov)' then fileExt = 'mov' elseif exportFormat == 'PIXAR USDA ASCII (.usda)' then fileExt = 'usda' else fileExt = 'xyz' end -- Use the Export Directory from the UI Manager GUI outputDirectory = pointcloudFolder os.execute('mkdir "' .. outputDirectory ..'"') -- Save a copy of the point cloud to the $TEMP/Kartaverse/ folder pointcloudFile = outputDirectory .. nodeName .. '.' .. fileExt print('[Export Format] "' .. tostring(exportFormat) .. '"') -- Read data from the selected node if nodeType == 'Camera3D' then -- Read the Camera3D node settings -- Lens focal length (in mm) focalLength = selectedNode:GetInput('FLength') -- Lens focus distance (in scene units) focusDistance = selectedNode:GetInput('PlaneOfFocus') -- f-Stop is a fixed (default) value that is not used inside of Fusion's Camera3D node fStop = 5.6 apertureW = selectedNode:GetInput('ApertureW') apertureH = selectedNode:GetInput('ApertureH') lensShiftX = selectedNode:GetInput('LensShiftX') lensShiftY = selectedNode:GetInput('LensShiftY') perspNearClip = selectedNode:GetInput('PerspNearClip') perspFarClip = selectedNode:GetInput('PerspFarClip') -- Translate tx = selectedNode:GetInput('Transform3DOp.Translate.X') ty = selectedNode:GetInput('Transform3DOp.Translate.Y') tz = selectedNode:GetInput('Transform3DOp.Translate.Z') -- Rotate rx = selectedNode:GetInput('Transform3DOp.Rotate.X') ry = selectedNode:GetInput('Transform3DOp.Rotate.Y') rz = selectedNode:GetInput('Transform3DOp.Rotate.Z') -- Scale sx = selectedNode:GetInput('Transform3DOp.Scale.X') sy = selectedNode:GetInput('Transform3DOp.Scale.Y') sz = selectedNode:GetInput('Transform3DOp.Scale.Z') -- Results print('\t[Focal Length (mm)] ' .. tostring(focalLength)) print('\t[Camera Aperture (in)] ' .. tostring(apertureW) .. ' x ' .. tostring(apertureH)) print('\t[Focus Distance (scene units)] ' .. tostring(focusDistance)) print('\t[Lens Shift] ' .. tostring(lensShiftX) .. ' x ' .. tostring(lensShiftY)) print('\t[Near Clip] ' .. tostring(perspNearClip)) print('\t[Far Clip] ' .. tostring(perspFarClip)) print('\t[Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) print('\t[Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) print('\t[Scale] [X] ' .. sx .. ' [Y] ' .. sy .. ' [Z] ' .. sz) if fileExt == 'ma' then -- Maya ASCII (.ma) export -- The system temporary directory path (Example: $TEMP/Kartaverse/) -- outputDirectory = comp:MapPath('Temp:\\Kartaverse\\') -- Open up the file pointer for the output textfile outFile, err = io.open(pointcloudFile,'w') if err then print('[Camera] [Error opening file for writing] ' .. tostring(pointcloudFile)) disp:ExitLoop() end -- Write a Maya ASCII header entry outFile:write('//Maya ASCII scene\n') outFile:write('//Name: ' .. tostring(nodeName) .. '.' .. tostring(fileExt) .. '\n') outFile:write('//Created by Kartaverse/CompX : ' .. _VERSION .. '\n') outFile:write('//Created: ' .. tostring(os.date('%Y-%m-%d %I:%M:%S %p')) .. '\n') outFile:write('requires maya "2019";\n') outFile:write('currentUnit -l centimeter -a degree -t film;\n') outFile:write('fileInfo "application" "maya";\n') outFile:write('createNode transform -s -n "persp";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".v" no;\n') outFile:write('\tsetAttr ".t" -type "double3" 42.542190019936143 11.856220346068302 7.6545481521220538 ;\n') outFile:write('\tsetAttr ".r" -type "double3" -15.338352729601354 79.799999999999187 8.9803183372077805e-15 ;\n') outFile:write('createNode camera -s -n "perspShape" -p "persp";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr -k off ".v" no;\n') outFile:write('\tsetAttr ".fl" 34.999999999999986;\n') outFile:write('\tsetAttr ".coi" 44.82186966202994;\n') outFile:write('\tsetAttr ".imn" -type "string" "persp";\n') outFile:write('\tsetAttr ".den" -type "string" "persp_depth";\n') outFile:write('\tsetAttr ".man" -type "string" "persp_mask";\n') outFile:write('\tsetAttr ".hc" -type "string" "viewSet -p %camera";\n') -- Write out the Camera3D node data outFile:write('createNode transform -n "' .. tostring(nodeName) .. '";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- Visible (Yes) outFile:write('\tsetAttr ".v";\n') -- Translate XYZ outFile:write('\tsetAttr ".t" -type "double3" ' .. tx .. ' ' .. ty .. ' ' .. tz .. ';\n') -- Rotate XYZ outFile:write('\tsetAttr ".r" -type "double3" ' .. rx .. ' ' .. ry .. ' ' .. rz .. ';\n') outFile:write('createNode camera -s -n "' .. tostring(nodeName) .. 'Shape" -p "' .. tostring(nodeName) .. '";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr -k off ".v";\n') -- Lens Focal length (mm) outFile:write('\tsetAttr ".fl" ' .. tostring(focalLength) .. ';\n') -- Camera Aperture (inches) outFile:write('\tsetAttr ".cap" -type "double2" ' .. tostring(apertureW) .. ' ' .. tostring(apertureH) .. ';\n') -- Film Offset outFile:write('\tsetAttr ".fio" -type "double2" ' .. tostring(lensShiftX) .. ' ' .. tostring(lensShiftY) .. ';\n') outFile:write('\tsetAttr ".coi" 44.82186966202994;\n') outFile:write('\tsetAttr ".imn" -type "string" "' .. tostring(nodeName) .. '";\n') outFile:write('\tsetAttr ".den" -type "string" "' .. tostring(nodeName) .. '_depth";\n') outFile:write('\tsetAttr ".man" -type "string" "' .. tostring(nodeName) .. '_mask";\n') outFile:write('\tsetAttr ".hc" -type "string" "viewSet -p %camera";\n') -- Should the Maya camera export be animated if mayaAnimatedCamera == true then local tx_animated = '' local ty_animated = '' local tz_animated = '' local rx_animated = '' local ry_animated = '' local rz_animated = '' local sx_animated = '' local sy_animated = '' local sz_animated = '' total_keyframes = 0 -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do -- Animated camera parameters focalLength = selectedNode:GetInput('FLength', frame) print('\t[Focal Length (mm)] ' .. tostring(focalLength)) apertureW = selectedNode:GetInput('ApertureW', frame) apertureH = selectedNode:GetInput('ApertureH', frame) print('\t[Camera Aperture (in)] ' .. tostring(apertureW) .. ' x ' .. tostring(apertureH)) lensShiftX = selectedNode:GetInput('LensShiftX', frame) lensShiftY = selectedNode:GetInput('LensShiftY', frame) print('\t[Lens Shift] ' .. tostring(lensShiftX) .. ' x ' .. tostring(lensShiftY)) perspNearClip = selectedNode:GetInput('PerspNearClip', frame) print('\t[Near Clip] ' .. tostring(perspNearClip)) perspFarClip = selectedNode:GetInput('PerspFarClip', frame) print('\t[Far Clip] ' .. tostring(perspFarClip)) tx = selectedNode:GetInput('Transform3DOp.Translate.X', frame) ty = selectedNode:GetInput('Transform3DOp.Translate.Y', frame) tz = selectedNode:GetInput('Transform3DOp.Translate.Z', frame) print('\t[Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) rx = selectedNode:GetInput('Transform3DOp.Rotate.X', frame) ry = selectedNode:GetInput('Transform3DOp.Rotate.Y', frame) rz = selectedNode:GetInput('Transform3DOp.Rotate.Z', frame) print('\t[Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) sx = selectedNode:GetInput('Transform3DOp.Scale.X', frame) sy = selectedNode:GetInput('Transform3DOp.Scale.Y', frame) sz = selectedNode:GetInput('Transform3DOp.Scale.Z', frame) print('\t[Scale] [X] ' .. sx .. ' [Y] ' .. sy .. ' [Z] ' .. sz) -- Append the per frame animated keys tx_animated = tx_animated .. tostring(frame) .. ' ' .. tx .. ' ' ty_animated = ty_animated .. tostring(frame) .. ' ' .. ty .. ' ' tz_animated = tz_animated .. tostring(frame) .. ' ' .. tz .. ' ' rx_animated = rx_animated .. tostring(frame) .. ' ' .. rx .. ' ' ry_animated = ry_animated .. tostring(frame) .. ' ' .. ry .. ' ' rz_animated = rz_animated .. tostring(frame) .. ' ' .. rz .. ' ' sx_animated = sx_animated .. tostring(frame) .. ' ' .. sx .. ' ' sy_animated = sy_animated .. tostring(frame) .. ' ' .. sy .. ' ' sz_animated = sz_animated .. tostring(frame) .. ' ' .. sz .. ' ' total_keyframes = total_keyframes + 1 end print('[TX Keys] ' .. tx_animated) print('[TY Keys] ' .. ty_animated) print('[TZ Keys] ' .. tz_animated) print('\n') print('[RX Keys] ' .. rx_animated) print('[RY Keys] ' .. ry_animated) print('[RZ Keys] ' .. rz_animated) print('\n') -- Add the animation curves -- translateX outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_translateX";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".tan" 2;\n') outFile:write('\tsetAttr ".wgt" no;\n') outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. tx_animated .. ';\n') -- translateY outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_translateY";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".tan" 2;\n') outFile:write('\tsetAttr ".wgt" no;\n') outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. ty_animated .. ';\n') -- translateY outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_translateZ";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".tan" 2;\n') outFile:write('\tsetAttr ".wgt" no;\n') outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. tz_animated .. ';\n') -- rotateX outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_rotateX";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".tan" 2;\n') outFile:write('\tsetAttr ".wgt" no;\n') outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. rx_animated .. ';\n') -- rotateY outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_rotateY";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".tan" 2;\n') outFile:write('\tsetAttr ".wgt" no;\n') outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. ry_animated .. ';\n') -- rotateZ outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_rotateZ";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".tan" 2;\n') outFile:write('\tsetAttr ".wgt" no;\n') outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. rz_animated .. ';\n') -- -- -- scaleX -- outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_scaleX";\n') -- outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- outFile:write('\tsetAttr ".tan" 2;\n') -- outFile:write('\tsetAttr ".wgt" no;\n') -- outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. sx_animated .. ';\n') -- -- scaleY -- outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_scaleY";\n') -- outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- outFile:write('\tsetAttr ".tan" 2;\n') -- outFile:write('\tsetAttr ".wgt" no;\n') -- outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. sy_animated .. ';\n') -- -- scaleY -- outFile:write('createNode animCurveTL -n "' .. tostring(nodeName) .. '_scale";\n') -- outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- outFile:write('\tsetAttr ".tan" 2;\n') -- outFile:write('\tsetAttr ".wgt" no;\n') -- outFile:write('\tsetAttr -s ' .. tostring(total_keyframes) .. ' ".ktv[0:' .. tostring(total_keyframes - 1) .. ']" ' .. sz_animated .. ';\n') -- Connect the animation curves outFile:write('connectAttr "' .. tostring(nodeName) .. '_translateX.o" "' .. tostring(nodeName) .. '.tx";\n') outFile:write('connectAttr "' .. tostring(nodeName) .. '_translateY.o" "' .. tostring(nodeName) .. '.ty";\n') outFile:write('connectAttr "' .. tostring(nodeName) .. '_translateZ.o" "' .. tostring(nodeName) .. '.tz";\n') outFile:write('connectAttr "' .. tostring(nodeName) .. '_rotateX.o" "' .. tostring(nodeName) .. '.rx";\n') outFile:write('connectAttr "' .. tostring(nodeName) .. '_rotateY.o" "' .. tostring(nodeName) .. '.ry";\n') outFile:write('connectAttr "' .. tostring(nodeName) .. '_rotateZ.o" "' .. tostring(nodeName) .. '.rz";\n') -- outFile:write('connectAttr "' .. tostring(nodeName) .. '_scaleX.o" "' .. tostring(nodeName) .. '.sx";\n') -- outFile:write('connectAttr "' .. tostring(nodeName) .. '_scaleY.o" "' .. tostring(nodeName) .. '.sy";\n') -- outFile:write('connectAttr "' .. tostring(nodeName) .. '_scaleZ.o" "' .. tostring(nodeName) .. '.sz";\n') end -- Write out the Maya ASCII footer -- Playback frame range outFile:write('createNode script -n "sceneConfigurationScriptNode";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".b" -type "string" "playbackOptions -min ' .. startFrame .. ' -max ' .. endFrame .. ' -ast ' .. startFrameGlobal .. ' -aet ' .. endFrameGlobal .. ' ";\n') outFile:write('\tsetAttr ".st" 6;\n') -- End timeline range outFile:write('select -ne :time1;\n') outFile:write('\tsetAttr ".o" ' .. endFrame .. ';\n') -- Current playhead timeline frame outFile:write('\tsetAttr ".unw" ' .. endFrame .. ';\n') outFile:write('// End of Maya ASCII\n') -- File writing complete outFile:write('\n') -- Close the file pointer on our Camera textfile outFile:close() print('[Export Camera] [File] ' .. tostring(pointcloudFile)) -- Show the output folder using a desktop file browser openDirectory(outputDirectory) elseif fileExt == 'usda' then -- The system temporary directory path (Example: $TEMP/Kartaverse/) -- outputDirectory = comp:MapPath('Temp:\\Kartaverse\\') -- Open up the file pointer for the output textfile outFile, err = io.open(pointcloudFile,'w') if err then print('[Camera] [Error opening file for writing] ' .. tostring(pointcloudFile)) disp:ExitLoop() end -- Write a PIXAR USD ASCII header entry outFile:write('#usda 1.0\n') outFile:write('(\n') outFile:write('\tdefaultPrim = "' .. tostring(nodeName) .. '"\n') if compFile and compFile ~= '' then -- The Fusion comp has a name so reference it in the usd ascii export outFile:write('\tdoc = """Generated from Composed Stage of root layer ' .. tostring(compFile) .. '"""\n') else -- Fallback - The Fusion comp is unsaved so just give this exported usd ascii file as the name outFile:write('\tdoc = """Generated from Composed Stage of root layer ' .. tostring(pointcloudFile) .. '"""\n') end outFile:write('\tmetersPerUnit = ' .. tostring(metersPerUnit) .. '\n') outFile:write('\tupAxis = "' .. tostring(upAxis) .. '"\n') outFile:write(')\n') outFile:write('\n') outFile:write('def Xform "' .. tostring(nodeName) .. '" (\n') outFile:write('\tkind = "assembly"\n') outFile:write(')\n') outFile:write('{\n') -- Should the PIXAR USD ASCII camera export be animated if usdAnimatedCamera == false then -- Static (non-animated) camera export -- Rotate XYZ outFile:write('\tfloat3 xformOp:rotateXYZ = (' .. rx .. ', ' .. ry .. ', ' .. rz .. ')\n') -- Translate XYZ outFile:write('\tdouble3 xformOp:translate = (' .. tx .. ', ' .. ty .. ', ' .. tz .. ')\n') outFile:write('\tuniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]\n') else -- Animated camera export -- Rotate XYZ outFile:write('\tfloat3 xformOp:rotateXYZ.timeSamples = {\n') -- Per frame Rotate XYZ values start -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do rx = selectedNode:GetInput('Transform3DOp.Rotate.X', frame) ry = selectedNode:GetInput('Transform3DOp.Rotate.Y', frame) rz = selectedNode:GetInput('Transform3DOp.Rotate.Z', frame) print('\t[Frame] ' .. tostring(frame) .. ' [Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) -- Example: 1: (1.0, 2.0, 3.0), outFile:write('\t\t' .. frame .. ': (' .. rx .. ', ' .. ry .. ', ' .. rz .. '),\n') end -- Per frame Rotate XYZ values end outFile:write('\t}\n') -- Translate XYZ outFile:write('\tdouble3 xformOp:translate.timeSamples = {\n') -- Per frame Translate XYZ values start -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do tx = selectedNode:GetInput('Transform3DOp.Translate.X', frame) ty = selectedNode:GetInput('Transform3DOp.Translate.Y', frame) tz = selectedNode:GetInput('Transform3DOp.Translate.Z', frame) print('\t[Frame] ' .. tostring(frame) .. ' [Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) -- Example: 1: (1.0, 2.0, 3.0), outFile:write('\t\t' .. frame .. ': (' .. tx .. ', ' .. ty .. ', ' .. tz .. '),\n') end -- Per frame Translate XYZ values end outFile:write('\t}\n') outFile:write('\tuniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]\n') end -- Camera properties outFile:write('\n') outFile:write('\tdef Camera "' .. tostring(nodeName) .. 'Shape"\n') outFile:write('\t{\n') -- Camera visibility -- outFile:write('\t\ttoken visibility = "invisible"\n') -- Camera Near/Far clipping range outFile:write('\t\tfloat2 clippingRange = (' .. tostring(perspNearClip) .. ', ' .. tostring(perspFarClip) .. ')\n') -- Lens Focal length (mm) outFile:write('\t\tfloat focalLength = ' .. tostring(focalLength) ..'\n') -- Lens focus distance (in scene units) outFile:write('\t\tfloat focusDistance = ' .. tostring(focusDistance) .. '\n') -- f-Stop is a fixed (default) value that is not used inside of Fusion's Camera3D node outFile:write('\t\tfloat fStop = ' .. tostring(fStop) .. '\n') -- Camera Aperture (mm) -- Convert 1 inch into millimetres local inchesToMM = 25.4 -- Horizontal Aperture (mm) outFile:write('\t\tfloat horizontalAperture = ' .. tonumber(apertureW * inchesToMM) .. '\n') -- Vertical Aperture (mm) outFile:write('\t\tfloat verticalAperture = ' .. tonumber(apertureH * inchesToMM) .. '\n') -- Write a Camera footer entry outFile:write('\t}\n') -- Write a PIXAR USD ASCII footer entry outFile:write('}\n') -- File writing complete outFile:write('\n') -- Close the file pointer on our Camera textfile outFile:close() print('[Export Camera] [File] ' .. tostring(pointcloudFile)) -- Show the output folder using a desktop file browser openDirectory(outputDirectory) elseif fileExt == 'mov' then -- Maya MOVE ASCII (.mov) export -- The system temporary directory path (Example: $TEMP/Kartaverse/) -- outputDirectory = comp:MapPath('Temp:\\Kartaverse\\') -- Open up the file pointer for the output textfile outFile, err = io.open(pointcloudFile,'w') if err then print('[Camera] [Error opening file for writing] ' .. tostring(pointcloudFile)) disp:ExitLoop() end -- Per frame Translate and Rotate XYZ values start -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do tx = selectedNode:GetInput('Transform3DOp.Translate.X', frame) ty = selectedNode:GetInput('Transform3DOp.Translate.Y', frame) tz = selectedNode:GetInput('Transform3DOp.Translate.Z', frame) rx = selectedNode:GetInput('Transform3DOp.Rotate.X', frame) ry = selectedNode:GetInput('Transform3DOp.Rotate.Y', frame) rz = selectedNode:GetInput('Transform3DOp.Rotate.Z', frame) print('\t[Frame] ' .. tostring(frame) .. ' [Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) print('\t[Frame] ' .. tostring(frame) .. ' [Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) -- Example: 1.0 2.0 3.0 4.0 5.0 6.0 outFile:write(tx .. ' ' .. ty .. ' ' .. tz .. ' ' .. rx .. ' ' .. ry .. ' ' .. rz .. '\n') end -- Per frame Translate and Rotate XYZ values end -- File writing complete outFile:write('\n') -- Close the file pointer on our Camera textfile outFile:close() print('[Export Camera] [File] ' .. tostring(pointcloudFile)) -- Show the output folder using a desktop file browser openDirectory(outputDirectory) end elseif nodeType == 'SurfaceAlembicMesh' then -- Read the SurfaceAlembicMesh node settings -- Filename filename = comp:MapPath(selectedNode:GetInput('Filename')) -- Translate tx = selectedNode:GetInput('Transform3DOp.Translate.X') ty = selectedNode:GetInput('Transform3DOp.Translate.Y') tz = selectedNode:GetInput('Transform3DOp.Translate.Z') -- Rotate rx = selectedNode:GetInput('Transform3DOp.Rotate.X') ry = selectedNode:GetInput('Transform3DOp.Rotate.Y') rz = selectedNode:GetInput('Transform3DOp.Rotate.Z') -- Scale sx = selectedNode:GetInput('Transform3DOp.Scale.X') sy = selectedNode:GetInput('Transform3DOp.Scale.Y') sz = selectedNode:GetInput('Transform3DOp.Scale.Z') -- Results print('\t[Filename] ' .. tostring(filename)) print('\t[Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) print('\t[Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) print('\t[Scale] [X] ' .. sx .. ' [Y] ' .. sy .. ' [Z] ' .. sz) -- The system temporary directory path (Example: $TEMP/Kartaverse/) -- outputDirectory = comp:MapPath('Temp:\\Kartaverse\\') -- Open up the file pointer for the output textfile outFile, err = io.open(pointcloudFile,'w') if err then print('[Alembic Mesh] [Error opening file for writing] ' .. tostring(pointcloudFile)) disp:ExitLoop() end -- Maya ASCII (.ma) export if fileExt == 'ma' then -- Write a Maya ASCII header entry outFile:write('//Maya ASCII scene\n') outFile:write('//Name: ' .. tostring(nodeName) .. '.' .. tostring(fileExt) .. '\n') outFile:write('//Created by Kartaverse: ' .. _VERSION .. '\n') outFile:write('//Created: ' .. tostring(os.date('%Y-%m-%d %I:%M:%S %p')) .. '\n') -- Alembic reference header entry -- Reference Alembic requires line outFile:write('requires "AbcImport" "1.0";;\n') outFile:write('file -rdi 1 -ns "' .. tostring(nodeName) .. '" -rfn "' .. tostring(nodeName) .. 'RN" -typ "Alembic" "' .. DupSlashes(filename) .. '";\n') outFile:write('file -r -ns "' .. tostring(nodeName) .. '" -dr 1 -rfn "' .. tostring(nodeName) .. 'RN" -typ "Alembic" "' .. DupSlashes(filename) .. '";\n') -- Standard Alembic requires line -- outFile:write('requires -nodeType "AlembicNode" "AbcImport" "1.0";\n') -- Rest of the Maya ASCII headers outFile:write('requires maya "2019";\n') outFile:write('currentUnit -l centimeter -a degree -t film;\n') outFile:write('fileInfo "application" "maya";\n') outFile:write('createNode transform -s -n "persp";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".v" no;\n') outFile:write('\tsetAttr ".t" -type "double3" 42.542190019936143 11.856220346068302 7.6545481521220538 ;\n') outFile:write('\tsetAttr ".r" -type "double3" -15.338352729601354 79.799999999999187 8.9803183372077805e-15 ;\n') outFile:write('createNode camera -s -n "perspShape" -p "persp";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr -k off ".v" no;\n') outFile:write('\tsetAttr ".fl" 34.999999999999986;\n') outFile:write('\tsetAttr ".coi" 44.82186966202994;\n') outFile:write('\tsetAttr ".imn" -type "string" "persp";\n') outFile:write('\tsetAttr ".den" -type "string" "persp_depth";\n') outFile:write('\tsetAttr ".man" -type "string" "persp_mask";\n') outFile:write('\tsetAttr ".hc" -type "string" "viewSet -p %camera";\n') -- Write out the SurfaceAlembicMesh node data -- outFile:write('createNode AlembicNode -n "' .. tostring(nodeName) .. '_AlembicNode";\n') -- outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- outFile:write('\tsetAttr ".fn" -type "string" "' .. filename .. '";\n') -- outFile:write('\tsetAttr ".fns" -type "stringArray" 1 "' .. filename .. '" ;\n') -- Write out the Maya Mesh Node + Transform Mode data -- outFile:write('createNode transform -n "' .. tostring(nodeName) .. '";\n') -- outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- outFile:write('\tsetAttr ".t" -type "double3" ' .. tx .. ' ' .. ty .. ' ' .. tz .. ';\n') -- outFile:write('\tsetAttr ".r" -type "double3" ' .. rx .. ' ' .. ry .. ' ' .. rz .. ';\n') -- outFile:write('createNode mesh -n "' .. tostring(nodeName) .. 'Mesh_0" -p "' .. tostring(nodeName) .. '";\n') -- outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') -- outFile:write('\tsetAttr -k off ".v";\n') -- outFile:write('\tsetAttr ".vir" yes;\n') -- outFile:write('\tsetAttr ".vif" yes;\n') -- outFile:write('\tsetAttr ".uvst[0].uvsn" -type "string" "map1";\n') -- outFile:write('\tsetAttr ".cuvs" -type "string" "map1";\n') -- outFile:write('\tsetAttr ".dcol" yes;\n') -- outFile:write('\tsetAttr ".dcc" -type "string" "Ambient+Diffuse";\n') -- outFile:write('\tsetAttr ".ccls" -type "string" "velocity";\n') -- outFile:write('\tsetAttr ".clst[0].clsn" -type "string" "velocity";\n') -- outFile:write('\tsetAttr ".covm[0]" 0 1 1;\n') -- outFile:write('\tsetAttr ".cdvm[0]" 0 1 1;\n') -- Connect the Alembic Node to the Mesh -- outFile:write('connectAttr "' .. tostring(nodeName) .. '_AlembicNode.opoly[0]" "' .. tostring(nodeName) .. 'Mesh_0.i";\n') -- Write out the SurfaceAlembicMesh node as Alembic Reference data outFile:write('createNode reference -n "' .. tostring(nodeName) .. 'RN";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".ed" -type "dataReferenceEdits" \n') outFile:write('\t\t"' .. tostring(nodeName) .. 'RN"\n') outFile:write('\t\t"' .. tostring(nodeName) .. 'RN" 0;\n') -- Write out the Maya ASCII footer -- Playback frame range outFile:write('createNode script -n "sceneConfigurationScriptNode";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".b" -type "string" "playbackOptions -min ' .. startFrame .. ' -max ' .. endFrame .. ' -ast ' .. startFrameGlobal .. ' -aet ' .. endFrameGlobal .. ' ";\n') outFile:write('\tsetAttr ".st" 6;\n') -- End timeline range outFile:write('select -ne :time1;\n') outFile:write('\tsetAttr ".o" ' .. endFrame .. ';\n') -- Current playhead timeline frame outFile:write('\tsetAttr ".unw" ' .. endFrame .. ';\n') outFile:write('// End of Maya ASCII\n') -- File writing complete outFile:write('\n') elseif fileExt == 'usda' then -- Write a PIXAR USD ASCII header entry outFile:write('#usda 1.0\n') outFile:write('(\n') outFile:write('\tdefaultPrim = "' .. tostring(nodeName) .. '"\n') if compFile and compFile ~= '' then -- The Fusion comp has a name so reference it in the usd ascii export outFile:write('\tdoc = """Generated from Composed Stage of root layer ' .. tostring(compFile) .. '"""\n') else -- Fallback - The Fusion comp is unsaved so just give this exported usd ascii file as the name outFile:write('\tdoc = """Generated from Composed Stage of root layer ' .. tostring(pointcloudFile) .. '"""\n') end outFile:write('\tmetersPerUnit = ' .. tostring(metersPerUnit) .. '\n') outFile:write('\tupAxis = "' .. tostring(upAxis) .. '"\n') outFile:write(')\n') outFile:write('\n') outFile:write('def Xform "' .. tostring(nodeName) .. '" (\n') outFile:write('\tkind = "assembly"\n') outFile:write(')\n') outFile:write('{\n') outFile:write('\tdef Xform "' .. tostring(nodeName) .. 'ReferenceAssembly" (\n') outFile:write('\t\tkind = "assembly"\n') outFile:write('\t\tprepend references = @' .. DupSlashes(filename) .. '@\n') outFile:write('\t)\n') -- AlembicMesh3D info -- Note: Fusion v9 appears to only support the Alembic HDF5 "legacy" (pre-Maya 2014 Extension 1) era .abc mesh format. Newer Ogawa formatted abc files fail to load in my tests. This means you need to have compiled PIXAR's open source "usdview" or your USD for Maya/Katana/Houdini/etc... plugins with HDF5 support enabled if you want to interact with Fusion compatible Alembic files. outFile:write('\t{\n') outFile:write('\t\tfloat3 xformOp:rotateXYZ = (' .. rx .. ', ' .. ry .. ', ' .. rz .. ')\n') outFile:write('\t\tdouble3 xformOp:translate = (' .. tx .. ', ' .. ty .. ', ' .. tz .. ')\n') outFile:write('\t\tuniform token[] xformOpOrder = ["xformOp:translate", "xformOp:rotateXYZ"]\n') outFile:write('\t}\n') -- Write a PIXAR USD ASCII footer entry outFile:write('}\n') elseif fileExt == 'mov' then -- Maya MOVE ASCII (.mov) export -- Per frame Translate and Rotate XYZ values start -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do tx = selectedNode:GetInput('Transform3DOp.Translate.X', frame) ty = selectedNode:GetInput('Transform3DOp.Translate.Y', frame) tz = selectedNode:GetInput('Transform3DOp.Translate.Z', frame) rx = selectedNode:GetInput('Transform3DOp.Rotate.X', frame) ry = selectedNode:GetInput('Transform3DOp.Rotate.Y', frame) rz = selectedNode:GetInput('Transform3DOp.Rotate.Z', frame) print('\t[Frame] ' .. tostring(frame) .. ' [Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) print('\t[Frame] ' .. tostring(frame) .. ' [Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) -- Example: 1.0 2.0 3.0 4.0 5.0 6.0 outFile:write(tx .. ' ' .. ty .. ' ' .. tz .. ' ' .. rx .. ' ' .. ry .. ' ' .. rz .. '\n') end -- Per frame Translate and Rotate XYZ values end -- File writing complete outFile:write('\n') end -- Close the file pointer on our Camera textfile outFile:close() print('[Export Alembic Mesh] [File] ' .. tostring(pointcloudFile)) -- Show the output folder using a desktop file browser openDirectory(outputDirectory) elseif nodeType == 'PointCloud3D' then -- Grab the settings table for the PointCloud3D node local nodeTable = comp:CopySettings(selectedNode) -- print('[PointCloud3D Settings]') -- dump(nodeTable) -- The system temporary directory path (Example: $TEMP/Kartaverse/) -- outputDirectory = comp:MapPath('Temp:\\Kartaverse\\') -- Open up the file pointer for the output textfile outFile, err = io.open(pointcloudFile,'w') if err then print('[Point Cloud] [Error opening file for writing] ' .. tostring(pointcloudFile)) disp:ExitLoop() end if fileExt == 'mov' then -- Maya MOVE ASCII (.mov) export -- Per frame Translate and Rotate XYZ values start -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do tx = selectedNode:GetInput('Transform3DOp.Translate.X', frame) ty = selectedNode:GetInput('Transform3DOp.Translate.Y', frame) tz = selectedNode:GetInput('Transform3DOp.Translate.Z', frame) rx = selectedNode:GetInput('Transform3DOp.Rotate.X', frame) ry = selectedNode:GetInput('Transform3DOp.Rotate.Y', frame) rz = selectedNode:GetInput('Transform3DOp.Rotate.Z', frame) print('\t[Frame] ' .. tostring(frame) .. ' [Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) print('\t[Frame] ' .. tostring(frame) .. ' [Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) -- Example: 1.0 2.0 3.0 4.0 5.0 6.0 outFile:write(tx .. ' ' .. ty .. ' ' .. tz .. ' ' .. rx .. ' ' .. ry .. ' ' .. rz .. '\n') end -- Per frame Translate and Rotate XYZ values end -- File writing complete outFile:write('\n') -- Check for a non nil settings lua table elseif nodeTable and nodeTable['Tools'] and nodeTable['Tools'][nodeName] and nodeTable['Tools'][nodeName]['Positions'] then -- Grab the positions Lua table elements local positionsTable = nodeTable['Tools'][nodeName]['Positions'] or {} local positionsElements = tonumber(table.getn(positionsTable)) -- Handle array off by 1 vertexCount = 0 if positionsTable[0] then vertexCount = tonumber(positionsElements + 1) end if fileExt == 'ma' then -- Write a Maya ASCII header entry outFile:write('//Maya ASCII scene\n') outFile:write('//Name: ' .. tostring(nodeName) .. '.' .. tostring(fileExt) .. '\n') outFile:write('//Created by Kartaverse: ' .. _VERSION .. '\n') outFile:write('//Created: ' .. tostring(os.date('%Y-%m-%d %I:%M:%S %p')) .. '\n') outFile:write('//Locator Count: ' ..tostring(vertexCount) .. '\n') outFile:write('requires maya "2019";\n') outFile:write('currentUnit -l centimeter -a degree -t film;\n') outFile:write('fileInfo "application" "maya";\n') outFile:write('createNode transform -s -n "persp";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".v" no;\n') outFile:write('\tsetAttr ".t" -type "double3" 42.542190019936143 11.856220346068302 7.6545481521220538 ;\n') outFile:write('\tsetAttr ".r" -type "double3" -15.338352729601354 79.799999999999187 8.9803183372077805e-15 ;\n') outFile:write('createNode camera -s -n "perspShape" -p "persp";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr -k off ".v" no;\n') outFile:write('\tsetAttr ".fl" 34.999999999999986;\n') outFile:write('\tsetAttr ".coi" 44.82186966202994;\n') outFile:write('\tsetAttr ".imn" -type "string" "persp";\n') outFile:write('\tsetAttr ".den" -type "string" "persp_depth";\n') outFile:write('\tsetAttr ".man" -type "string" "persp_mask";\n') outFile:write('\tsetAttr ".hc" -type "string" "viewSet -p %camera";\n') outFile:write('createNode transform -n "PointCloudGroup";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') elseif fileExt == 'usda' then -- Write a PIXAR USD ASCII header entry outFile:write('#usda 1.0\n') outFile:write('(\n') outFile:write('\tdefaultPrim = "persp"\n') outFile:write('\tdoc = """Generated from Composed Stage of root layer ' .. tostring(pointcloudFile) .. '"""\n') outFile:write('\tmetersPerUnit = ' .. tostring(metersPerUnit) .. '\n') outFile:write('\tupAxis = "' .. tostring(upAxis) .. '"\n') outFile:write(')\n') outFile:write('\n') outFile:write('def Xform "PointCloudGroup" (\n') outFile:write('\tkind = "assembly"\n') outFile:write(')\n') outFile:write('{\n') elseif fileExt == 'ply' then -- Write a ply ASCII header entry outFile:write('ply\n') outFile:write('format ascii 1.0\n') outFile:write('comment Created by Kartaverse ' .. _VERSION .. '\n') outFile:write('comment Created ' .. tostring(os.date('%Y-%m-%d %I:%M:%S %p')) .. '\n') outFile:write('obj_info Generated by Kartaverse!\n') outFile:write('element vertex ' .. tostring(vertexCount) .. '\n') outFile:write('property float x\n') outFile:write('property float y\n') outFile:write('property float z\n') outFile:write('end_header\n') end -- Scan through the positions table for i = 0, positionsElements do -- Check if there are 5+ elements are in the positions table element. We only need 4 of those elements at this time. local tableElements = table.getn(positionsTable[i] or {}) if tableElements >= 4 then local x, y, z, name = positionsTable[i][1], positionsTable[i][2], positionsTable[i][3], positionsTable[i][4] -- Display the data for one point cloud sample print('[' .. tostring(i + 1) .. '] [' .. tostring(name) .. '] [XYZ] ' .. tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z)) -- Write the point cloud data if fileExt == 'ma' then -- ma (Maya ASCII) outFile:write('createNode transform -n "locator' .. tostring(i + 1) .. '" -p "PointCloudGroup";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".t" -type "double3" ' .. tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z) .. ';\n') outFile:write('\tsetAttr ".s" -type "double3" ' .. mayaLocatorSize .. " " .. mayaLocatorSize .. " " .. mayaLocatorSize .. ';\n') outFile:write('createNode locator -n "locatorShape' .. tostring(i + 1) .. '" -p "locator' .. tostring(i + 1) .. '";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr -k off ".v";\n') elseif fileExt == 'usda' then -- usdz (USD ASCII) outFile:write('\n') outFile:write('\tdef Xform "locator' .. tostring(i + 1) .. '"\n') outFile:write('\t{\n') outFile:write('\t\tdouble3 xformOp:translate = (' .. tostring(x) .. ', ' .. tostring(y) .. ', ' .. tostring(z) .. ')\n') outFile:write('\t\tuniform token[] xformOpOrder = ["xformOp:translate"]\n') outFile:write('\t}\n') elseif fileExt == 'ply' then -- ply - Add a trailing space before the newline character outFile:write(tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z) .. ' ' .. '\n') else -- xyz outFile:write(tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z) .. '\n') end else print('[Error][PointCloud3D Positions] Not enough table elements. Only ' .. tostring(tableElements) .. ' were found. 5 are expected.') disp:ExitLoop() end end if fileExt == 'ma' then -- Write out the Maya ASCII footer -- Playback frame range outFile:write('createNode script -n "sceneConfigurationScriptNode";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".b" -type "string" "playbackOptions -min ' .. startFrame .. ' -max ' .. endFrame .. ' -ast ' .. startFrameGlobal .. ' -aet ' .. endFrameGlobal .. ' ";\n') outFile:write('\tsetAttr ".st" 6;\n') -- End timeline range outFile:write('select -ne :time1;\n') outFile:write('\tsetAttr ".o" ' .. endFrame .. ';\n') -- Current playhead timeline frame outFile:write('\tsetAttr ".unw" ' .. endFrame .. ';\n') outFile:write('// End of Maya ASCII\n') elseif fileExt == 'usda' then -- Write out the USD ASCII footer outFile:write('}\n') end -- File writing complete outFile:write('\n') -- Close the file pointer on our point cloud textfile outFile:close() -- List how many PointCloud3D vertices were found in the OBJ mesh print('[PointCloud3D Positions] ' .. tostring(vertexCount)) print('[OpenUSD Scene Exporter] [File] ' .. tostring(pointcloudFile)) -- Show the output folder using a desktop file browser openDirectory(outputDirectory) else print('[Error][PointCloud3D Positions] No points found on ' .. tostring(nodeName) .. ' node.') disp:ExitLoop() end elseif nodeType == 'SurfaceFBXMesh' then meshFile = selectedNode:GetInput('ImportFile') -- Display the name of the source FBX/OBJ mesh print('[FBXMesh3D Source File] ' .. tostring(meshFile)) -- The system temporary directory path (Example: $TEMP/Kartaverse/) -- outputDirectory = comp:MapPath('Temp:\\Kartaverse\\') -- Use the Export Directory from the UI Manager GUI outputDirectory = pointcloudFolder os.execute('mkdir "' .. outputDirectory ..'"') pointcloudFile = '' -- Save a copy of the point cloud to the $TEMP/Kartaverse/ folder pointcloudFile = outputDirectory .. nodeName .. '.' .. fileExt print('[PointCloud3D Format] "' .. tostring(exportFormat) .. '"') -- Open up the file pointer for the output textfile outFile, err = io.open(pointcloudFile,'w') if err then print('[Point Cloud] [Error opening file for writing] ' .. tostring(pointcloudFile)) disp:ExitLoop() end if fileExt == 'mov' then -- Maya MOVE ASCII (.mov) export -- Per frame Translate and Rotate XYZ values start -- Step through the timeline at the comp's "StepBy" interval for frame = startFrame, endFrame, renderStep do tx = selectedNode:GetInput('Transform3DOp.Translate.X', frame) ty = selectedNode:GetInput('Transform3DOp.Translate.Y', frame) tz = selectedNode:GetInput('Transform3DOp.Translate.Z', frame) rx = selectedNode:GetInput('Transform3DOp.Rotate.X', frame) ry = selectedNode:GetInput('Transform3DOp.Rotate.Y', frame) rz = selectedNode:GetInput('Transform3DOp.Rotate.Z', frame) print('\t[Frame] ' .. tostring(frame) .. ' [Translate] [X] ' .. tx .. ' [Y] ' .. ty .. ' [Z] ' .. tz) print('\t[Frame] ' .. tostring(frame) .. ' [Rotate] [X] ' .. rx .. ' [Y] ' .. ry .. ' [Z] ' .. rz) -- Example: 1.0 2.0 3.0 4.0 5.0 6.0 outFile:write(tx .. ' ' .. ty .. ' ' .. tz .. ' ' .. rx .. ' ' .. ry .. ' ' .. rz .. '\n') end -- Per frame Translate and Rotate XYZ values end -- File writing complete outFile:write('\n') elseif meshFile and string.match(string.lower(meshFile), '^.+(%..+)$') == '.obj' then -- Display the name of the source OBJ mesh -- Count the number of vertices in the file for the PLY header local vertexCount = 0 for oneLine in io.lines(comp:MapPath(meshFile)) do -- One line of data -- print('[' .. vertexCount .. '] ' .. oneLine) -- Check if this line is an OBJ vertex local searchString = '^v%s.*' if oneLine:match(searchString) then -- Track how many vertices were found vertexCount = vertexCount + 1 end end if fileExt == 'ma' then -- Write a Maya ASCII header entry outFile:write('//Maya ASCII scene\n') outFile:write('//Name: ' .. tostring(nodeName) .. '.' .. tostring(fileExt) .. '\n') outFile:write('//Created by Kartaverse: ' .. _VERSION .. '\n') outFile:write('//Created: ' .. tostring(os.date('%Y-%m-%d %I:%M:%S %p')) .. '\n') outFile:write('//Locator Count: ' ..tostring(vertexCount) .. '\n') outFile:write('requires maya "2019";\n') outFile:write('currentUnit -l centimeter -a degree -t film;\n') outFile:write('fileInfo "application" "maya";\n') outFile:write('createNode transform -s -n "persp";\n') outFile:write('\trename -uid "BDD1D327-CA4A-FAF4-4EC1-508AA473BFD6";\n') outFile:write('\tsetAttr ".v" no;\n') outFile:write('\tsetAttr ".t" -type "double3" 42.542190019936143 11.856220346068302 7.6545481521220538 ;\n') outFile:write('\tsetAttr ".r" -type "double3" -15.338352729601354 79.799999999999187 8.9803183372077805e-15 ;\n') outFile:write('createNode camera -s -n "perspShape" -p "persp";\n') outFile:write('\trename -uid "B4797D18-2047-C2A9-CAF1-8998F20276B3";\n') outFile:write('\tsetAttr -k off ".v" no;\n') outFile:write('\tsetAttr ".fl" 34.999999999999986;\n') outFile:write('\tsetAttr ".coi" 44.82186966202994;\n') outFile:write('\tsetAttr ".imn" -type "string" "persp";\n') outFile:write('\tsetAttr ".den" -type "string" "persp_depth";\n') outFile:write('\tsetAttr ".man" -type "string" "persp_mask";\n') outFile:write('\tsetAttr ".hc" -type "string" "viewSet -p %camera";\n') outFile:write('createNode transform -n "PointCloudGroup";\n') outFile:write('\trename -uid "6A38A338-4C48-6A5F-2EFE-D79EFCBFBA09";\n') elseif fileExt == 'usda' then -- Write a PIXAR USD ASCII header entry outFile:write('#usda 1.0\n') outFile:write('(\n') outFile:write('\tdefaultPrim = "locator' .. tostring(0) .. '"\n') outFile:write('\tdoc = """Generated from Composed Stage of root layer ' .. tostring(pointcloudFile) .. '"""\n') outFile:write('\tmetersPerUnit = ' .. tostring(metersPerUnit) .. '\n') outFile:write('\tupAxis = "' .. tostring(upAxis) .. '"\n') outFile:write(')\n') outFile:write('\n') outFile:write('def Xform "PointCloudGroup" (\n') outFile:write('\tkind = "assembly"\n') outFile:write(')\n') outFile:write('{\n') elseif fileExt == 'ply' then -- Write a ply ASCII header entry outFile:write('ply\n') outFile:write('format ascii 1.0\n') outFile:write('comment Created by Kartaverse ' .. _VERSION .. '\n') outFile:write('comment Created ' .. tostring(os.date('%Y-%m-%d %I:%M:%S %p')) .. '\n') outFile:write('obj_info Generated by Kartaverse!\n') outFile:write('element vertex ' .. tostring(vertexCount) .. '\n') outFile:write('property float x\n') outFile:write('property float y\n') outFile:write('property float z\n') outFile:write('end_header\n') end local lineCounter = 0 for oneLine in io.lines(comp:MapPath(meshFile)) do -- One line of data -- print('[' .. lineCounter .. '] ' .. oneLine) -- Check if this line is an OBJ vertex local searchString = '^v%s.*' if oneLine:match(searchString) then -- Extract the vertex XYZ positions, using %s as a white space character -- Example: v 0.5 0.5 -0.5 local x, y, z = string.match(oneLine, '^v%s(%g+)%s(%g+)%s(%g+)') -- Write the point cloud data i = lineCounter if fileExt == 'ma' then -- ma (Maya ASCII) outFile:write('createNode transform -n "locator' .. tostring(i + 1) .. '" -p "PointCloudGroup";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".t" -type "double3" ' .. tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z) .. ';\n') outFile:write('\tsetAttr ".s" -type "double3" ' .. mayaLocatorSize .. " " .. mayaLocatorSize .. " " .. mayaLocatorSize .. ';\n') outFile:write('createNode locator -n "locatorShape' .. tostring(i + 1) .. '" -p "locator' .. tostring(i + 1) .. '";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr -k off ".v";\n') elseif fileExt == 'usda' then -- usdz (USD ASCII) outFile:write('\n') outFile:write('\tdef Xform "locator' .. tostring(i + 1) .. '"\n') outFile:write('\t{\n') outFile:write('\t\tdouble3 xformOp:translate = (' .. tostring(x) .. ', ' .. tostring(y) .. ', ' .. tostring(z) .. ')\n') outFile:write('\t\tuniform token[] xformOpOrder = ["xformOp:translate"]\n') outFile:write('\t}\n') elseif fileExt == 'ply' then -- ply - Add a trailing space before the newline character outFile:write(tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z) .. ' ' .. '\n') else -- xyz outFile:write(tostring(x) .. ' ' .. tostring(y) .. ' ' .. tostring(z) .. '\n') end -- Track how many vertices were found lineCounter = lineCounter + 1 end end if fileExt == 'ma' then -- Write out the Maya ASCII footer -- Playback frame range outFile:write('createNode script -n "sceneConfigurationScriptNode";\n') outFile:write('\trename -uid "' .. tostring(bmd.createuuid()) .. '";\n') outFile:write('\tsetAttr ".b" -type "string" "playbackOptions -min ' .. startFrame .. ' -max ' .. endFrame .. ' -ast ' .. startFrameGlobal .. ' -aet ' .. endFrameGlobal .. ' ";\n') outFile:write('\tsetAttr ".st" 6;\n') -- End timeline range outFile:write('select -ne :time1;\n') outFile:write('\tsetAttr ".o" ' .. endFrame .. ';\n') -- Current playhead timeline frame outFile:write('\tsetAttr ".unw" ' .. endFrame .. ';\n') outFile:write('// End of Maya ASCII\n') elseif fileExt == 'usda' then -- Write out the USD ASCII footer outFile:write('}\n') end -- File writing complete outFile:write('\n') -- List how many FBXMesh3D vertices were found in the OBJ mesh print('[FBXMesh3D Positions] ' .. tostring(vertexCount)) else print('[Error][OpenUSD Scene Exporter] Please select an FBXMesh3D node that has an OBJ model loaded.') disp:ExitLoop() end -- Close the file pointer on our point cloud textfile outFile:close() print('[Export PointCloud3D] [File] ' .. tostring(pointcloudFile)) -- Show the output folder using a desktop file browser openDirectory(outputDirectory) else print('[Error][OpenUSD Scene Exporter] No PointCloud3D or FBXMesh3D node was selected. Please select either a PointCloud3D node or an FBXMesh3D node in the flow view and run the script again.') disp:ExitLoop() end else print('[Error][OpenUSD Scene Exporter] No PointCloud3D or FBXMesh3D node was selected. Please select either a PointCloud3D node or an FBXMesh3D node in the flow view and run the script again.') disp:ExitLoop() end disp:ExitLoop() end end end -- The Select Folder Button was clicked function epcwin.On.SelectFolderButton.Clicked(ev) selectedPath = fusion:RequestDir(exportDirectory) if selectedPath ~= nil then print('[Select Folder] "' .. tostring(selectedPath) .. '"') epcitm.ExportDirectoryText.Text = tostring(selectedPath) else print('[Select Folder] Cancelled Dialog') end end -- The Cancel Button was clicked function epcwin.On.CancelButton.Clicked(ev) epcwin:Hide() print('[OpenUSD Scene Exporter] Cancelled') disp:ExitLoop() end -- The app:AddConfig() command that will capture the "Control + W" or "Control + F4" hotkeys so they will close the window instead of closing the foreground composite. app:AddConfig('OpenUSDSceneExporter', { Target { ID = 'OpenUSDSceneExporter', }, Hotkeys { Target = 'OpenUSDSceneExporter', Defaults = true, CONTROL_W = 'Execute{ cmd = [[app.UIManager:QueueEvent(obj, "Close", {})]] }', CONTROL_F4 = 'Execute{ cmd = [[app.UIManager:QueueEvent(obj, "Close", {})]] }', }, }) -- Point Cloud Export format list: FormatTable = { {text = 'XYZ ASCII (.xyz)'}, {text = 'PLY ASCII (.ply)'}, {text = 'Maya ASCII (.ma)'}, {text = 'Maya MOVE ASCII (.mov)'}, {text = 'PIXAR USDA ASCII (.usda)'}, } -- Add the Format entries to the ComboControl menu for i = 1, table.getn(FormatTable) do if FormatTable[i].text ~= nil then epcitm.FormatCombo:AddItem(FormatTable[i].text) end end -- The default value for the Point Cloud Format ComboBox epcitm.FormatCombo.CurrentIndex = GetPreferenceData('CompX.OpenUSDSceneExporter.PointCloudFormat', 0, false) -- We want to be notified whenever the 'Comp_Activate_Tool' action has been executed local notify = ui:AddNotify('Comp_Activate_Tool', comp) -- The Fusion "Comp_Activate_Tool" command was used function disp.On.Comp_Activate_Tool(ev) -- Verify a PointCloud3D node was selected if ev and ev.Args and ev.Args.tool then if ev.Args.tool:GetAttrs('TOOLS_RegID') == 'PointCloud3D' then -- PointCloud3D node -- Update the selected node selectedNode = ev.Args.tool:GetAttrs('TOOLS_Name') print('[Selected ' .. tostring(ev.Args.tool:GetAttrs('TOOLS_RegID')) .. ' Node] ' .. tostring(selectedNode or 'None')) epcitm.NodeNameText.Text = tostring(selectedNode or '') elseif ev.Args.tool:GetAttrs('TOOLS_RegID') == 'SurfaceFBXMesh' then -- FBXMesh3D node with an OBJ model present meshFile = ev.Args.tool:GetInput('ImportFile') -- Make sure its not a nil if meshFile and string.match(string.lower(meshFile), '^.+(%..+)$') == '.obj' then -- Update the selected node selectedNode = ev.Args.tool:GetAttrs('TOOLS_Name') print('[Selected ' .. tostring(ev.Args.tool:GetAttrs('TOOLS_RegID')) .. ' Node] ' .. tostring(selectedNode or 'None')) epcitm.NodeNameText.Text = tostring(selectedNode or '') else print('[Error] [Selected ' .. tostring(ev.Args.tool:GetAttrs('TOOLS_RegID')) .. ' Node] Does not have an OBJ model loaded in ' .. tostring(selectedNode or 'None')) end end end end epcwin:Show() disp:RunLoop() epcwin:Hide() -- Cleanup after the window was closed app:RemoveConfig('OpenUSDSceneExporter') collectgarbage() return epcwin,epcwin:GetItems() end ------------------------------------------------------------------------ -- Where the magic happens function Main() -- Check if Fusion is running if not fusion then print('[Error] This script needs to be run from inside of Fusion.') return end -- Check if a composite is open in Fusion Standalone or the Resolve Fusion page if not comp then print('[Error] A Fusion composite needs to be open.') return end print('[Kartaverse][CompX][OpenUSD Scene Exporter] ' .. tostring(_VERSION)) print('[Created By] Andrew Hazelden <andrew@andrewhazelden.com>') -- Show the UI Manager GUI OpenUSDSceneExporterWin() end -- Run the main function Main() print('[Done]')
-- This is the primary barebones gamemode script and should be used to assist in initializing your game mode -- Set this to true if you want to see a complete debug output of all events/processes done by barebones -- You can also change the cvar 'barebones_spew' at any time to 1 or 0 for output/no output BAREBONES_DEBUG_SPEW = true if GameMode == nil then DebugPrint( '[BAREBONES] creating barebones game mode' ) _G.GameMode = class({}) end -- This library allow for easily delayed/timed actions require('timers') -- This library can be used for advancted physics/motion/collision of units. See PhysicsReadme.txt for more information. require('libraries/physics') -- This library can be used for advanced 3D projectile systems. require('libraries/projectiles') -- This library can be used for sending panorama notifications to the UIs of players/teams/everyone require('libraries/notifications') -- This library can be used for starting customized animations on units from lua require('libraries/animations') -- These internal libraries set up barebones's events and processes. Feel free to inspect them/change them if you need to. require('internal/gamemode') require('internal/events') -- settings.lua is where you can specify many different properties for your game mode and is one of the core barebones files. require('settings') -- events.lua is where you can specify the actions to be taken when any event occurs and is one of the core barebones files. require('events') require('duel') --[[ This function should be used to set up Async precache calls at the beginning of the gameplay. In this function, place all of your PrecacheItemByNameAsync and PrecacheUnitByNameAsync. These calls will be made after all players have loaded in, but before they have selected their heroes. PrecacheItemByNameAsync can also be used to precache dynamically-added datadriven abilities instead of items. PrecacheUnitByNameAsync will precache the precache{} block statement of the unit and all precache{} block statements for every Ability# defined on the unit. This function should only be called once. If you want to/need to precache more items/abilities/units at a later time, you can call the functions individually (for example if you want to precache units in a new wave of holdout). This function should generally only be used if the Precache() function in addon_game_mode.lua is not working. ]] function GameMode:PostLoadPrecache() DebugPrint("[BAREBONES] Performing Post-Load precache") --PrecacheItemByNameAsync("item_example_item", function(...) end) --PrecacheItemByNameAsync("example_ability", function(...) end) --PrecacheUnitByNameAsync("npc_dota_hero_viper", function(...) end) --PrecacheUnitByNameAsync("npc_dota_hero_enigma", function(...) end) end --[[ This function is called once and only once as soon as the first player (almost certain to be the server in local lobbies) loads in. It can be used to initialize state that isn't initializeable in InitGameMode() but needs to be done before everyone loads in. ]] function GameMode:OnFirstPlayerLoaded() DebugPrint("[BAREBONES] First Player has loaded") innateAbilityTable = {} end --[[ This function is called once and only once after all players have loaded into the game, right as the hero selection time begins. It can be used to initialize non-hero player state or adjust the hero selection (i.e. force random etc) ]] function GameMode:OnAllPlayersLoaded() DebugPrint("[BAREBONES] All Players have loaded into the game") GameRules.APPLIER = CreateItem("item_duel", nil, nil) local unitGate1 = Entities:FindByName( nil, "cornergate1" ) local unitGate2 = Entities:FindByName( nil, "cornergate2" ) local unitGate3 = Entities:FindByName( nil, "cornergate3" ) local unitGate4 = Entities:FindByName( nil, "cornergate4" ) local unitGate5 = Entities:FindByName( nil, "bossgate1" ) local unitGate6 = Entities:FindByName( nil, "bossgate2" ) unitGate1:RemoveModifierByName("modifier_invulnerable") unitGate2:RemoveModifierByName("modifier_invulnerable") unitGate3:RemoveModifierByName("modifier_invulnerable") unitGate4:RemoveModifierByName("modifier_invulnerable") unitGate5:RemoveModifierByName("modifier_invulnerable") unitGate6:RemoveModifierByName("modifier_invulnerable") DUEL = false GameRules:GetGameModeEntity():SetDamageFilter( Dynamic_Wrap( GameMode, "FilterModifyDamage" ), self ) GameRules:GetGameModeEntity():SetModifyGoldFilter( Dynamic_Wrap( GameMode, "FilterModifyGold" ), self ) GameRules.PlayerBountyEligibility = {} end --function GameMode:OnEntityKilled( keys ) --print("PRINTING KEYS") --DeepPrintTable( keys ) --print("SOMEONE JUST DIED") --local killer = EntIndexToHScript(keys.entindex_attacker) --local killed = EntIndexToHScript(keys.entindex_killed) --local killerID = killer:GetPlayerOwner():GetPlayerID() --local stringID = tostring(killerID) --print(killerID) --if killed:IsRealHero() and not(killed:IsIllusion()) and not(killed:IsReincarnating()) then -- if GameRules.PlayerBountyEligibility[stringID] == nil then -- GameRules.PlayerBountyEligibility[stringID] = 0 -- end -- GameRules.PlayerBountyEligibility[stringID] = 1 --end --end function GameMode:FilterModifyGold( filterTable ) print("printing FILTERTAbLE") PrintTable(filterTable) print("someone modify gold") --if filterTable["reason_const"] == DOTA_ModifyGold_Death then -- return filterTable["gold"] == 0 --end --print("CHECKING FOR VALUE PRIOR IF") --print(GameRules.PlayerBountyEligibility[tostring(filterTable["player_id_const"])]) if GameRules.PlayerBountyEligibility[filterTable["player_id_const"]] == nil then GameRules.PlayerBountyEligibility[filterTable["player_id_const"]] = 0 end filterTable["reliable"] = 0 local playerKills = PlayerResource:GetKills(filterTable["player_id_const"]) if filterTable["reason_const"] == DOTA_ModifyGold_HeroKill then if filterTable["gold"] ~= 0 then if GameRules.PlayerBountyEligibility[filterTable["player_id_const"]] < playerKills then filterTable["gold"] = 500 GameRules.PlayerBountyEligibility[filterTable["player_id_const"]] = GameRules.PlayerBountyEligibility[filterTable["player_id_const"]] + 1 else filterTable["gold"] = 0 end end end return true end function GameMode:FilterModifyDamage( filterTable ) print("SOMEONE WAS DAMAGED") PrintTable( filterTable ) local herodamaged = EntIndexToHScript(filterTable["entindex_victim_const"]) local attacker_name = EntIndexToHScript(filterTable["entindex_attacker_const"]):GetUnitName() --print(attacker_name) if herodamaged:GetHealth() < filterTable["damage"] and (attacker_name == "building_tower_blue" or "building_tower_red") then filterTable["damage"] = 0 local damageTable = { victim = EntIndexToHScript(filterTable["entindex_victim_const"]), attacker = EntIndexToHScript(filterTable["entindex_victim_const"]), damage = herodamaged:GetHealth(), damage_type = DAMAGE_TYPE_PURE } ApplyDamage( damageTable ) end return true end function GameMode:OnNPCSpawned(keys) --print("[PMP] NPC Spawned") --DeepPrintTable(keys) local heroID = keys.entindex local npc = EntIndexToHScript(keys.entindex) local spawnPoint = Entities:FindByName( nil, "unitChecker"):GetAbsOrigin() if npc:IsRealHero() and npc.bFirstSpawned == nil then npc.bFirstSpawned = true table.insert(GameRules.heroList, npc) GameMode:ModifyStatBonuses(npc) Timers:CreateTimer( 0.03, function() if not npc:IsIllusion() then FindClearSpaceForUnit(npc, spawnPoint, false) SendToConsole("dota_camera_center") end return nil end ) for k, v in pairs( GameRules.HeroInit ) do print(k) if npc:GetUnitName() == k then do v(npc) end end end end Timers:CreateTimer({ endTime = 0.05, callback = function() local hero = EntIndexToHScript( keys.entindex ) local model_name = "" -- Check if npc is hero if not hero:IsHero() then return end -- Getting model name if GameRules.model_lookup[ hero:GetName() ] ~= nil and hero:GetModelName() ~= GameRules.model_lookup[ hero:GetName() ] then model_name = GameRules.model_lookup[ hero:GetName() ] else model_name = GameRules.model_lookup[ hero:GetName() ] end -- Check if it's correct format local model = hero:FirstMoveChild() while model ~= nil do if model:GetClassname() == "dota_item_wearable" then model:AddEffects(EF_NODRAW) -- Set model hidden end model = model:NextMovePeer() end if hero:GetModelName() == "models/development/invisiblebox.vmdl" then hero:SetModel( model_name ) hero:SetOriginalModel( model_name ) Timers:CreateTimer({ endTime = 0.05, callback = function() hero:RespawnUnit() end }) end end }) --ApplyModifier(npc, "modifier_attackable") -- Ignore default gold bounty end --[[ This function is called once and only once when the game completely begins (about 0:00 on the clock). At this point, gold will begin to go up in ticks if configured, creeps will spawn, towers will become damageable etc. This function is useful for starting any game logic timers/thinkers, beginning the first round, etc. ]] function GameMode:OnGameInProgress() DebugPrint("[BAREBONES] The game has officially begun") Timers:CreateTimer({ endTime = 300, callback = function() duelStart() end }) Timers:CreateTimer({ endTime = 360, callback = function() local point1 = Entities:FindByName(nil, "bossspawn1"):GetAbsOrigin() local point2 = Entities:FindByName(nil, "bossspawn2"):GetAbsOrigin() local unit1 = CreateUnitByName("unit_boss_1", point1, true, nil, nil, DOTA_TEAM_NEUTRALS) unit1:SetHullRadius(56) local unit2 = CreateUnitByName("unit_boss_1a", point2, true, nil, nil, DOTA_TEAM_NEUTRALS) unit2:SetHullRadius(56) end }) local repeat_interval = 30 -- Rerun this timer every *repeat_interval* game-time seconds local start_after = 0 -- Start this timer *start_after* game-time seconds later local startAfter = 0 local thinkerInterval = 2 local unitsLocation = {} function SpawnCreeps1() local point1 = Entities:FindByName( nil, "spawner1"):GetAbsOrigin() local point2 = Entities:FindByName( nil, "spawner2"):GetAbsOrigin() local point3 = Entities:FindByName( nil, "spawner3"):GetAbsOrigin() local point4 = Entities:FindByName( nil, "spawner4"):GetAbsOrigin() local point5 = Entities:FindByName( nil, "spawner5"):GetAbsOrigin() local point6 = Entities:FindByName( nil, "spawner6"):GetAbsOrigin() local point7 = Entities:FindByName( nil, "spawner7"):GetAbsOrigin() local point8 = Entities:FindByName( nil, "spawner8"):GetAbsOrigin() local point9 = Entities:FindByName( nil, "spawner9"):GetAbsOrigin() local point10 = Entities:FindByName( nil, "spawner10"):GetAbsOrigin() local point11 = Entities:FindByName( nil, "spawner11"):GetAbsOrigin() local point12 = Entities:FindByName( nil, "spawner12"):GetAbsOrigin() local units_to_spawn1 = 4 for i=1, units_to_spawn1 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_lesser_skeleton", point1+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn2 = 4 for i=1, units_to_spawn2 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_gnoll_hunter", point2+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn3 = 4 for i=1, units_to_spawn3 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_spiderling", point3+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn4 = 2 for i=1, units_to_spawn4 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_arachnid", point4+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn5 = 4 for i=1, units_to_spawn5 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_lesser_skeleton", point5+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn6 = 4 for i=1, units_to_spawn6 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_gnoll_hunter", point6+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn7 = 4 for i=1, units_to_spawn7 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_spiderling", point7+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn8 = 2 for i=1, units_to_spawn8 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_arachnid", point8+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn9 = 4 for i=1, units_to_spawn9 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_lesser_skeleton", point9+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn10 = 4 for i=1, units_to_spawn10 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_gnoll_hunter", point10+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn11 = 4 for i=1, units_to_spawn11 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_spiderling", point11+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn12 = 2 for i=1, units_to_spawn12 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_arachnid", point12+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end end function SpawnCreeps2() local point1 = Entities:FindByName( nil, "spawner1"):GetAbsOrigin() local point2 = Entities:FindByName( nil, "spawner2"):GetAbsOrigin() local point3 = Entities:FindByName( nil, "spawner3"):GetAbsOrigin() local point4 = Entities:FindByName( nil, "spawner4"):GetAbsOrigin() local point5 = Entities:FindByName( nil, "spawner5"):GetAbsOrigin() local point6 = Entities:FindByName( nil, "spawner6"):GetAbsOrigin() local point7 = Entities:FindByName( nil, "spawner7"):GetAbsOrigin() local point8 = Entities:FindByName( nil, "spawner8"):GetAbsOrigin() local point9 = Entities:FindByName( nil, "spawner9"):GetAbsOrigin() local point10 = Entities:FindByName( nil, "spawner10"):GetAbsOrigin() local point11 = Entities:FindByName( nil, "spawner11"):GetAbsOrigin() local point12 = Entities:FindByName( nil, "spawner12"):GetAbsOrigin() local units_to_spawn1 = 5 for i=1, units_to_spawn1 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_skeleton", point1+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn2 = 1 for i=1, units_to_spawn2 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_general", point1+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn3 = 5 for i=1, units_to_spawn3 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_spellcaster", point2+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn4 = 1 for i=1, units_to_spawn4 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mage", point2+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn5 = 6 for i=1, units_to_spawn5 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_rock_golem", point3+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn6 = 1 for i=1, units_to_spawn6 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_commander", point4+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn7 = 5 for i=1, units_to_spawn7 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_knight", point4+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn8 = 5 for i=1, units_to_spawn8 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_spellcaster", point5+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn9 = 5 for i=1, units_to_spawn9 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_skeleton", point6+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn10 = 5 for i=1, units_to_spawn10 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_knight", point7+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn11 = 5 for i=1, units_to_spawn11 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_rock_golem", point8+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn12 = 6 for i=1, units_to_spawn12 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_rock_golem", point9+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn13 = 1 for i=1, units_to_spawn13 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_commander", point10+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn14 = 5 for i=1, units_to_spawn14 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_knight", point10+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn15 = 1 for i=1, units_to_spawn15 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_general", point11+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn16 = 5 for i=1, units_to_spawn16 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_skeleton", point11+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn17 = 1 for i=1, units_to_spawn17 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mage", point12+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn18 = 5 for i=1, units_to_spawn18 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_spellcaster", point12+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end end function SpawnCreeps3() local point1 = Entities:FindByName( nil, "spawner1"):GetAbsOrigin() local point2 = Entities:FindByName( nil, "spawner2"):GetAbsOrigin() local point3 = Entities:FindByName( nil, "spawner3"):GetAbsOrigin() local point4 = Entities:FindByName( nil, "spawner4"):GetAbsOrigin() local point5 = Entities:FindByName( nil, "spawner5"):GetAbsOrigin() local point6 = Entities:FindByName( nil, "spawner6"):GetAbsOrigin() local point7 = Entities:FindByName( nil, "spawner7"):GetAbsOrigin() local point8 = Entities:FindByName( nil, "spawner8"):GetAbsOrigin() local point9 = Entities:FindByName( nil, "spawner9"):GetAbsOrigin() local point10 = Entities:FindByName( nil, "spawner10"):GetAbsOrigin() local point11 = Entities:FindByName( nil, "spawner11"):GetAbsOrigin() local point12 = Entities:FindByName( nil, "spawner12"):GetAbsOrigin() local units_to_spawn1 = 3 for i=1, units_to_spawn1 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_general", point1+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn2 = 2 for i=1, units_to_spawn2 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_primal_furbolg", point1+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn3 = 2 for i=1, units_to_spawn3 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_death_mage", point2+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn4 = 3 for i=1, units_to_spawn4 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mage", point2+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn5 = 4 for i=1, units_to_spawn5 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mutant_golem", point3+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn6 = 3 for i=1, units_to_spawn6 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_commander", point4+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn7 = 2 for i=1, units_to_spawn7 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_primal_werebeast", point4+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn8 = 3 for i=1, units_to_spawn8 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mage", point5+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn9 = 3 for i=1, units_to_spawn9 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_general", point6+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn10 = 3 for i=1, units_to_spawn10 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_commander", point7+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn11 = 2 for i=1, units_to_spawn11 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mutant_golem", point8+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn12 = 4 for i=1, units_to_spawn12 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mutant_golem", point9+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn13 = 3 for i=1, units_to_spawn13 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_commander", point10+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn14 = 2 for i=1, units_to_spawn14 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_primal_werebeast", point10+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn15 = 3 for i=1, units_to_spawn15 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_general", point11+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn16 = 2 for i=1, units_to_spawn16 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_primal_furbolg", point11+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn17 = 3 for i=1, units_to_spawn17 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_mage", point12+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end local units_to_spawn18 = 2 for i=1, units_to_spawn18 do Timers:CreateTimer(function() local unit = CreateUnitByName("unit_death_mage", point12+RandomVector(RandomInt(100,200)), true, nil, nil, DOTA_TEAM_NEUTRALS) local origin = unit:GetAbsOrigin() unitsLocation[unit] = origin unit:SetHullRadius(56) end) end end function CheckUnit() local point = Entities:FindByName( nil, "unitChecker"):GetAbsOrigin() local unitChecker = #Entities:FindAllInSphere(point, 3200) local gameTime = GameRules:GetGameTime() if unitChecker <= 300 then if gameTime >= 360 then if gameTime >= 1200 then SpawnCreeps3() repeat_interval = 120 else SpawnCreeps2() repeat_interval = 60 end else SpawnCreeps1() end end end function moveUnit() Timers:CreateTimer(function() for k,v in pairs(unitsLocation) do if not k:IsAlive() or k:IsDominated() then unitsLocation[k] = nil else local unitPosition = k:GetAbsOrigin() if unitPosition ~= v then local attackState = k:GetAggroTarget() if attackState == nil then k:MoveToPosition(v) else local attackTarget = attackState:GetAbsOrigin() local targetDistance = (attackTarget - unitPosition):Length2D() if targetDistance >= 1800 then k:MoveToPosition(v) end end end end end end) end Timers:CreateTimer(start_after, function() CheckUnit() return repeat_interval end) Timers:CreateTimer(startAfter, function() moveUnit() return thinkerInterval end) end -- This function initializes the game mode and is called before anyone loads into the game -- It can be used to pre-initialize any values/tables that will be needed later function GameMode:InitGameMode() GameMode = self DebugPrint('[BAREBONES] Starting to load Barebones gamemode...') GameRules.heroList = {} GameRules:SetCustomGameSetupTimeout( 60 ) -- Call the internal function to set up the rules/behaviors specified in constants.lua -- This also sets up event hooks for all event handlers in events.lua -- Check out internals/gamemode to see/modify the exact code GameMode:_InitGameMode() ListenToGameEvent('npc_spawned', Dynamic_Wrap(GameMode, 'OnNPCSpawned'), self) -- Commands can be registered for debugging purposes or as functions that can be called by the custom Scaleform UI Convars:RegisterCommand( "duel_on", Dynamic_Wrap(GameMode, 'ToggleDuelON'), "Toggling duel on", FCVAR_CHEAT ) Convars:RegisterCommand( "duel_off", Dynamic_Wrap(GameMode, 'ToggleDuelOFF'), "Toggling duel off", FCVAR_CHEAT ) Convars:RegisterCommand( "duel_check", Dynamic_Wrap(GameMode, 'CheckDuel'), "checking duel state", FCVAR_CHEAT ) Convars:RegisterCommand( "camera2000", Dynamic_Wrap(GameMode, 'setCamera1'), "setting camera to 2000", FCVAR_CHEAT ) Convars:RegisterCommand( "camera2700", Dynamic_Wrap(GameMode, 'setCamera2'), "setting camera to 2700", FCVAR_CHEAT ) DebugPrint('[BAREBONES] Done loading Barebones gamemode!\n\n') end -- This is an example console command function GameMode:ToggleDuelON() print( 'Duel state on' ) local cmdPlayer = Convars:GetCommandClient() if cmdPlayer then local playerID = cmdPlayer:GetPlayerID() if playerID ~= nil and playerID ~= -1 then -- Do something here for the player who called this command local point = Entities:FindByName( nil, "redDuel1"):GetAbsOrigin() FindClearSpaceForUnit(Convars:GetCommandClient(), point, false) DUEL = true end end print( '*********************************************' ) end function GameMode:setCamera1() print('setting camera distance 2000') local cmdPlayer = Convars:GetCommandClient() if cmdPlayer then local playerID = cmdPlayer:GetPlayerID() if playerID ~= nil and playerID ~= -1 then -- Do something here for the player who called this command GameRules:GetGameModeEntity():SetCameraDistanceOverride(2000) end end print( '*********************************************' ) end function GameMode:setCamera2() print('setting camera distance 2000') local cmdPlayer = Convars:GetCommandClient() if cmdPlayer then local playerID = cmdPlayer:GetPlayerID() if playerID ~= nil and playerID ~= -1 then -- Do something here for the player who called this command GameRules:GetGameModeEntity():SetCameraDistanceOverride(2700) end end print( '*********************************************' ) end function GameMode:ToggleDuelOFF() print("Duel state off") DUEL = false end function GameMode:CheckDuel() if DUEL then print("Duel is on!") else print("Duel is off") end end
---@class htexture 纹理(遮罩/警示圈) htexture = { --- 系统自带遮罩 DEFAULT_MARKS = { WHITE = "ReplaceableTextures\\CameraMasks\\White_mask.blp", --白色迷雾 BLACK = "ReplaceableTextures\\CameraMasks\\Black_mask.blp", --黑色迷雾 HAZE = "ReplaceableTextures\\CameraMasks\\HazeFilter_mask.blp", --薄雾 GROUND_FOG = "ReplaceableTextures\\CameraMasks\\GroundFog_mask.blp", --地面迷雾 HAZE_AND_FOG = "ReplaceableTextures\\CameraMasks\\HazeAndFogFilter_Mask.blp", --薄雾和迷雾 DIAGONAL_SLASH = "ReplaceableTextures\\CameraMasks\\DiagonalSlash_mask.blp", --对角线 DREAM = "ReplaceableTextures\\CameraMasks\\DreamFilter_Mask.blp", --梦境(四周模糊) SCOPE = "ReplaceableTextures\\CameraMasks\\Scope_Mask.blp", --范围 }, } ---@private htexture.cinematicFilterGeneric = function(duration, bmode, tex, red0, green0, blue0, trans0, red1, green1, blue1, trans1) if cg.bj_cineFadeContinueTimer ~= nil then cj.DestroyTimer(cg.bj_cineFadeContinueTimer) end if cg.bj_cineFadeFinishTimer ~= nil then cj.DestroyTimer(cg.bj_cineFadeFinishTimer) end cj.SetCineFilterTexture(tex) cj.SetCineFilterBlendMode(bmode) cj.SetCineFilterTexMapFlags(TEXMAP_FLAG_NONE) cj.SetCineFilterStartUV(0, 0, 1, 1) cj.SetCineFilterEndUV(0, 0, 1, 1) cj.SetCineFilterStartColor( red0, green0, blue0, 255 - trans0 ) cj.SetCineFilterEndColor( red1, green1, blue1, 255 - trans1 ) cj.SetCineFilterDuration(duration) cj.DisplayCineFilter(true) end --- 创建一个遮罩 ---@public ---@param path string 贴图路径 512x256 png->blp ---@param during number 持续时间,默认3秒 ---@param whichPlayer userdata|nil 玩家 ---@param red number 0-255 ---@param green number 0-255 ---@param blue number 0-255 htexture.mark = function(path, during, whichPlayer, red, green, blue) if (path == nil) then return end red = red or 255 green = green or 255 blue = blue or 255 during = during or 3 if (whichPlayer == nil) then htexture.cinematicFilterGeneric( 0.50, BLEND_MODE_ADDITIVE, path, red, green, blue, 255, red, green, blue, 0 ) htime.setTimeout(during, function(t) htime.delTimer(t) htexture.cinematicFilterGeneric( 0.50, BLEND_MODE_ADDITIVE, path, red, green, blue, 0, red, green, blue, 255 ) end) elseif (whichPlayer ~= nil) then if (hcache.get(whichPlayer, CONST_CACHE.PLAYER_MARKING, false) ~= true) then hcache.set(whichPlayer, CONST_CACHE.PLAYER_MARKING, true) if (whichPlayer == cj.GetLocalPlayer()) then htexture.cinematicFilterGeneric( 0.50, BLEND_MODE_ADDITIVE, path, red, green, blue, 255, red, green, blue, 0 ) end htime.setTimeout(during, function(t) htime.delTimer(t) hcache.set(whichPlayer, CONST_CACHE.PLAYER_MARKING, false) if (whichPlayer == cj.GetLocalPlayer()) then htexture.cinematicFilterGeneric( 0.50, BLEND_MODE_ADDITIVE, path, red, green, blue, 0, red, green, blue, 255 ) end end) end end end --- 创建一个警示圈 ---@param diameter number 直径范围(px) ---@param x number 坐标X ---@param y number 坐标Y ---@param during number 持续时间,警示圈不允许永久存在,during默认为3秒 ---@param token number 马甲单位ID,默认叹号!马甲单位原始直径应为128px(刚好一小格) ---@param color userdata 警示圈马甲单位的颜色,仅支持玩家队伍色,参考 blizzard:^PLAYER_COLOR_? htexture.alertCircle = function(diameter, x, y, during, token, color) if (diameter == nil or diameter < 64) then return end during = during or 3 if (during <= 0) then during = 3 end token = token or HL_ID.texture_alert_circle_exclamation local modelScale = hslk.i2v(token, "slk", "modelScale") if (modelScale == nil) then return end if (type(token) == "string") then token = string.char2id(token) end color = color or PLAYER_COLOR_RED modelScale = math.round(math.round(modelScale, 3) * (diameter / 128), 2) local u = cj.CreateUnit(hplayer.player_passive, token, x, y, 270) cj.SetUnitColor(u, color) cj.SetUnitScale(u, modelScale, modelScale, modelScale) hunit.del(u, during) end
-- @file godot_dictionary.lua Wrapper for GDNative's Dictionary -- This file is part of Godot Lua PluginScript: https://github.com/gilzoide/godot-lua-pluginscript -- -- Copyright (C) 2021 Gil Barbosa Reis. -- -- 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. --- Dictionary metatype, wrapper for `godot_dictionary`. -- Construct using the idiom `Dictionary(from)`, which calls `__new`. -- @classmod Dictionary local Dictionary_erase = api_1_1 ~= nil and api_1_1.godot_dictionary_erase_with_return or api.godot_dictionary_erase local methods = { fillvariant = api.godot_variant_new_dictionary, varianttype = VariantType.Dictionary, --- Returns the number of keys in the Dictionary. -- @function size -- @treturn int size = api.godot_dictionary_size, --- Returns `true` if the Dictionary is empty. -- @function empty -- @treturn bool empty = api.godot_dictionary_empty, --- Clear the Dictionary, removing all key/value pairs. -- @function clear clear = api.godot_dictionary_clear, --- Returns `true` if the Dictionary has a given key. -- @function has -- @param key -- @treturn bool has = function(self, key) return api.godot_dictionary_has(self, Variant(key)) end, --- Returns `true` if the dictionary has all the given keys. -- @function has_all -- @param ... If only a table or Array value is passed, its values are used as search keys. -- Otherwise, all passed arguments will be used as search keys. -- @treturn bool has_all = function(self, keys, ...) if select('#', ...) > 0 or not ffi_istype(Array, keys) then keys = Array(keys, ...) end return api.godot_dictionary_has_all(self, keys) end, --- Erase a dictionary key/value pair by key. -- Returns `true` if the given key was present in the Dictionary, `false` otherwise. -- Does not erase elements while iterating over the dictionary. -- @function erase -- @param key Key, boxed with `Variant.__new` -- @treturn bool erase = function(self, key) return Dictionary_erase(self, Variant(key)) end, --- Returns a hashed integer value representing the Dictionary contents. -- This can be used to compare Dictionaries by value. -- Note: Dictionaries with the same keys/values but in a different order will have a different hash. -- @function hash -- @treturn int hash = api.godot_dictionary_hash, --- Returns the list of keys in the Dictionary. -- @function keys -- @treturn Array keys = function(self) return ffi_gc(api.godot_dictionary_keys(self), api.godot_array_destroy) end, --- Returns the list of values in the Dictionary. -- @function values -- @treturn Array values = function(self) return ffi_gc(api.godot_dictionary_values(self), api.godot_array_destroy) end, --- Returns the current value for the specified `key` in the Dictionary. -- If the key does not exist, the method returns the value of the optional `default` argument, or `nil` if it is omitted. -- @function get -- @param key -- @param[opt] default Default value to be returned if key doesn't exist in Dictionary -- @return Unboxed value or `default` or nil get = function(self, key, default) if default ~= nil and api_1_1 ~= nil then return ffi_gc(api_1_1.godot_dictionary_get_with_default(self, Variant(key), Variant(default)), api.godot_variant_destroy):unbox() else return ffi_gc(api.godot_dictionary_get(self, Variant(key)), api.godot_variant_destroy):unbox() end end, --- Set a new value for the specified `key` in the Dictionary. -- @function set -- @param key -- @param value set = function(self, key, value) api.godot_dictionary_set(self, Variant(key), Variant(value)) end, --- Returns the next key/value pair Dictionary's, similar to Lua's [next](https://www.lua.org/manual/5.1/manual.html#pdf-next). -- This is used to iterate over Dictionaries in `__pairs`. -- @usage -- local key, value = nil -- First key being `nil`, the iteration begins -- while true do -- key, value = dict:next(key) -- if key == nil then break end -- -- do something -- end -- @function next -- @param key If `nil`, returns the first key/value pair. -- Otherwise, returns the next key/value pair. -- @return[1] Key -- @return[1] Value -- @treturn[2] nil If there are no more keys -- @see __pairs next = function(self, key) if key ~= nil then key = Variant(key) end local next_key = api.godot_dictionary_next(self, key) if next_key ~= nil then return next_key:unbox(), self:get(next_key) else return nil end end, --- Returns a String with JSON representation of the Dictionary's contents. -- @function to_json -- @treturn String to_json = function(self) return ffi_gc(api.godot_dictionary_to_json(self), api.godot_string_destroy) end, } if api_1_2 ~= nil then --- Creates a copy of the dictionary, and returns it. -- The `deep` parameter causes inner Dictionaries and Arrays to be copied recursively, but does not apply to Objects. -- @function duplicate -- @param[opt=false] deep -- @treturn Dictionary methods.duplicate = function(self, deep) return ffi_gc(api_1_2.godot_dictionary_duplicate(self, deep or false), api.godot_dictionary_destroy) end end Dictionary = ffi_metatype('godot_dictionary', { --- Dictionary constructor, called by the idiom `Dictionary(value)`. -- @function __new -- @param[opt] value If passed, the key/value pairs will be iterated with -- `pairs` and inserted into the new Dictionary using `set`. -- Notice that both tables and userdata/cdata with a `__pairs` metamethod -- are valid, including another Dictionary. -- @treturn Dictionary __new = function(mt, value) local self = ffi_new('godot_dictionary') api.godot_dictionary_new(self) if value then for k, v in pairs(value) do self[k] = v end end return self end, __index = function(self, key) return methods[key] or methods.get(self, key) end, --- Set a value to Dictionary. -- If `value` is `nil`, the `key` will be `erase`d, similarly to Lua tables. -- To insert a Nil Variant into Dictionary, use `set` instead. -- @function __newindex -- @param key -- @param value __newindex = function(self, key, value) if type(value) == 'nil' then api.godot_dictionary_erase(self, Variant(key)) else api.godot_dictionary_set(self, Variant(key), Variant(value)) end end, __gc = api.godot_dictionary_destroy, --- Returns a Lua string representation of this Dictionary. -- @function __tostring -- @treturn string __tostring = gd_tostring, --- Concatenates values. -- @function __concat -- @param a First value, stringified with `GD.str` -- @param b First value, stringified with `GD.str` -- @treturn String __concat = concat_gdvalues, --- Alias for `size`. -- @function __len -- @treturn int -- @see size __len = function(self) return methods.size(self) end, --- Returns the `next` iterator and `self`, called by the idiom `pairs(dictionary)`. -- @usage -- for k, v in pairs(dictionary) do -- -- do something -- end -- @function __pairs -- @treturn function -- @treturn Dictionary self __pairs = function(self) return methods.next, self end, })
local function shift(list, shifts) local listType = type(list) assert(listType == "table", "expected a table for first argument, got " .. listType) shifts = shifts or 1 local shiftsType = type(shifts) assert(shiftsType == "number" and shifts % 1 == 0, "expected an integer for second argument, got " .. shiftsType) local new = {} for i = 1 + shifts, #list do new[i - shifts] = list[i] end return new end return shift
-- initially based on https://github.com/nodemcu/nodemcu-firmware/blob/master/lua_examples/webap_toggle_pin.lua -- start wifi client or AP mode --dofile('wificlient.lua') dofile('wifiap.lua') -- LED init (strip with 72 leds) print("Initializing LED strip...") ws2812.init() strip_buffer = ws2812.newBuffer(6, 3) ws2812_effects.init(strip_buffer) -- initially all leds off ws2812_effects.set_speed(200) ws2812_effects.set_brightness(0) ws2812_effects.set_color(0,0,0) ws2812_effects.start() print("done.") print() -- helper functions -- send a file from memory to the client; max. line length = 1024 bytes! function send_file(client, filename) if file.open(filename, "r") then repeat local line=file.read('\n') if line then client:send(line) end until not line file.close() end end -- web server srv = net.createServer(net.TCP) srv:listen(80, function(conn) conn:on("receive", function(client, request) local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP") if (method == nil) then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP") end local _GET = {} if (vars ~= nil) then for k, v in string.gmatch(vars, "(%w+)=([a-z0-9_]+)&*") do _GET[k] = v end end if (_GET.set == "effect") then print("setting effect", _GET.effect) ws2812_effects.set_mode(_GET.effect) ws2812_effects.set_speed(200) ws2812_effects.set_brightness(50) ws2812_effects.start() end if (_GET.set == "color") then print("setting color (RGB)", _GET.r, _GET.g, _GET.b) ws2812_effects.set_color(_GET.g, _GET.r, _GET.b) -- obviously our strip is GRB and not RGB end send_file(client, 'index.html') end) conn:on("sent", function(c) c:close() end) end)
-- Put functions in this file to use them in several other scripts. -- To get access to the functions, you need to put: -- require "my_directory.my_file" -- in any script using the functions local M = {} M.rooms = {} M.elevators = {} M.keypuzzle = {} M.paused = false M.map = nil M.map_visited = nil M.current_elevator = nil --indice del current elevator (1, 8) M.current_floor = nil --indice del piano corrente (1, 12) quello in alto e' 1 M.player_tunnel = nil --tunnel del player (0 = tunnel sx, 1 = elevator (middle), 2 = tunnel dx) M.current_room = nil --indice della room corrente M.player_roomentry = nil -- {door_pos, door_dir} M.in_game = false function M.new() -- initialize the 32 rooms for i=1, 32 do M.rooms[i] = {objects = {}, visited = false, door_left = nil, door_right = nil} end -- initialize 8 elevators for i=1,8 do M.elevators[i] = {} end -- initialize the 16 puzzle keys for i=1, 16 do M.keypuzzle[i] = false end M.map = nil --blocchi visitati nella mappa della scena elevator M.map_visited = {} for y=1,6 do M.map_visited[y] = {} for x=1,19 do M.map_visited[y][x] = false end end end function M.get_object(room_id, object_id) return M.rooms[room_id][object_id] end function M.add_object(room_id, object_id, object_bag) M.rooms[room_id][object_id] = {timer = 10000, bag = object_bag} end function M.set_object_timer(room_id, object_id, timer) -- if timer == 0 the object is disabled M.rooms[room_id][object_id].timer = timer end function M.room_visited(room_id) M.current_room = room_id M.rooms[room_id].visited = true end function M.set_elevator_scene(elevator_id, floor_index, player_tunnel) --player_tunnel = 0 (sx) 1 (elevator) 2 (dx) M.current_elevator = elevator_id M.current_floor = floor_index M.player_tunnel = player_tunnel M.current_room = nil end function M.set_room_scene(room_id, door_pos, door_dir) --door_pos = 1 (top), 2 (bottom) --door_dir = false (left), true (right) M.current_room = room_id M.current_elevator = nil M.player_roomentry = {door_pos = door_pos, door_dir = door_dir} end return M
-- Author: Divran local Obj = EGP:NewObject( "Poly" ) Obj.w = nil Obj.h = nil Obj.x = nil Obj.y = nil Obj.vertices = {} Obj.verticesindex = "vertices" Obj.HasUV = true -- Returns whether c is to the left of the line from a to b. local function counterclockwise( a, b, c ) local area = (a.x - c.x) * (b.y - c.y) - (b.x - c.x) * (a.y - c.y) return area > 0 end Obj.Draw = function( self ) if (self.a>0 and #self.vertices>2) then render.CullMode(counterclockwise(unpack(self.vertices)) and MATERIAL_CULLMODE_CCW or MATERIAL_CULLMODE_CW) surface.SetDrawColor( self.r, self.g, self.b, self.a ) surface.DrawPoly( self.vertices ) render.CullMode(MATERIAL_CULLMODE_CCW) end end Obj.Transmit = function( self, Ent, ply ) if (#self.vertices <= 28) then net.WriteUInt( #self.vertices, 8 ) for i=1,#self.vertices do net.WriteInt( self.vertices[i].x, 16 ) net.WriteInt( self.vertices[i].y, 16 ) net.WriteFloat( self.vertices[i].u or 0 ) net.WriteFloat( self.vertices[i].v or 0 ) end else net.WriteUInt( 0, 8 ) EGP:InsertQueue( Ent, ply, EGP._SetVertex, "SetVertex", self.index, self.vertices ) end net.WriteInt( self.parent, 16 ) EGP:SendMaterial( self ) EGP:SendColor( self ) end Obj.Receive = function( self ) local tbl = {} tbl.vertices = {} for i=1,net.ReadUInt(8) do tbl.vertices[ #tbl.vertices+1 ] = { x = net.ReadInt(16), y = net.ReadInt(16), u = net.ReadFloat(), v = net.ReadFloat() } end tbl.parent = net.ReadInt(16) EGP:ReceiveMaterial( tbl ) EGP:ReceiveColor( tbl, self ) return tbl end Obj.DataStreamInfo = function( self ) return { vertices = self.vertices, material = self.material, r = self.r, g = self.g, b = self.b, a = self.a, parent = self.parent } end
TOOL.Category = "Wire Extras/Visuals/Indicators" TOOL.Name = "Adv. Hud Indicator 2" TOOL.Command = nil TOOL.ConfigName = "" if ( CLIENT ) then language.Add( "Tool_wire_adv_hud_indicator_2_name", "Adv. HUD Indicator 2 ! (Wire)" ) language.Add( "Tool_wire_adv_hud_indicator_2_desc", "Spawns an Adv. HUD Indicator 2 for use with the wire system." ) language.Add( "Tool_wire_adv_hud_indicator_2_0", "Primary: Create/Update Hud Indicator Secondary: Hook/Unhook a HUD Indicator" ) language.Add( "Tool_wire_adv_hud_indicator_2_1", "Now use Reload on a vehicle to link this HUD Indicator to it, or on the same HUD Indicator to unlink it" ) language.Add( "Tool_wire_adv_hud_menu_showEditor", "Open the HML Editor" ) language.Add( "undone_gmod_wire_hud_indicator_2", "Undone Wire Adv. HUD Indicator 2" ) end //--Runs SERVERSIDE--// function TOOL:LeftClick( trace ) if (CLIENT) then return true end if trace.Entity:IsPlayer() then return false end local player = self:GetOwner() local model = "models/jaanus/wiretool/wiretool_siren.mdl" local position = trace.HitPos local material = "models/debug/debugwhite" local ent = nil local hmlCode = self:GetClientInfo( "hml_code" ) --Angle and correction-- local angle = trace.HitNormal:Angle() angle.pitch = angle.pitch + 90 -- If we've clicked an already active SENT... if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_hud_indicator_2" && trace.Entity.pl == ply ) then ent = trace.Entity -- Update code here! FIXME! else -- Build the entity, and set its parameters ent = BuildWireAdvHudIndicator2( player, model, angle, position, material ) if(ent == false) then return false end end local const = WireLib.Weld(ent, trace.Entity, trace.PhysicsBone, true) undo.Create("gmod_wire_hud_indicator_2") undo.AddEntity( ent ) undo.AddEntity( const ) undo.SetPlayer( player ) undo.Finish() //-- Now that we have an entity, invoke its owner to send us code! player:SendLua("HUD2_uploadCode(" .. ent:EntIndex() .. ")") return true end if SERVER then function BuildWireAdvHudIndicator2( pl, Model, Ang, Pos, material, hml ) local sent = ents.Create( "gmod_wire_hud_indicator_2" ) if( sent:IsValid() ) then sent:SetModel( Model ) sent:SetMaterial( material ) sent:SetAngles( Ang ) sent:SetPos( Pos ) sent:Spawn() local phys = sent:GetPhysicsObject() if ( phys:IsValid() ) then phys:EnableCollisions(true) end //-- Breaks for some reason...? //--pl:AddCount( "wire_adv_indicators", wire_adv_indicator ) print("<HML>: ", hml ) --sent:RegisterPlayer( pl ) sent:ReloadCode( hml or "" ) //-- DONT SEND NIL HML! --// return sent end Msg("[WW] Got a nil entity!\n") return false end duplicator.RegisterEntityClass("gmod_wire_hud_indicator_2", BuildWireAdvHudIndicator2, "Model", "Ang", "Pos", "material" ) end function TOOL:RightClick( trace ) if trace.Entity:IsPlayer() then return false end local player = self:GetOwner() if (trace.Entity && trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_hud_indicator_2") then local sent = trace.Entity sent:ToggleHooked( player ) return true end return false end // Hook HUD Indicator to vehicle function TOOL:Reload( trace ) if (!trace.Entity || !trace.Entity:IsValid()) then return false end if trace.Entity:IsPlayer() then return false end if (CLIENT) then return true end local iNum = self:NumObjects() if (iNum == 0) then if (trace.Entity:GetClass() != "gmod_wire_hud_indicator_2") then WireLib.AddNotify(self:GetOwner(), "You must select a HUD Indicator to link first.", NOTIFY_GENERIC, 7) return false end local Phys = trace.Entity:GetPhysicsObjectNum( trace.PhysicsBone ) self:SetObject( 1, trace.Entity, trace.HitPos, Phys, trace.PhysicsBone, trace.HitNormal ) self:SetStage(1) elseif (iNum == 1) then if (trace.Entity != self:GetEnt(1)) then if (!string.find(trace.Entity:GetClass(), "prop_vehicle_")) then WireLib.AddNotify(self:GetOwner(), "HUD Indicators can only be linked to vehicles.", NOTIFY_GENERIC, 7) self:ClearObjects() self:SetStage(0) return false end local ent = self:GetEnt(1) local bool = ent:GetTable():LinkVehicle(trace.Entity) if (!bool) then WireLib.AddNotify(self:GetOwner(), "Could not link HUD Indicator!", NOTIFY_GENERIC, 7) return false end WireLib.AddNotify(self:GetOwner(), "HUD Linked!", NOTIFY_GENERIC, 5) else // Unlink HUD Indicator from this vehicle trace.Entity:GetTable():UnLinkVehicle() WireLib.AddNotify(self:GetOwner(), "HUD UnLinked!", NOTIFY_GENERIC, 5) end self:ClearObjects() self:SetStage(0) end return true end function TOOL:Holster() self:ReleaseGhostEntity() self:GetWeapon():SetNetworkedBool("HUDIndicatorCheckRegister", false) end function TOOL.BuildCPanel( panel ) panel:ClearControls() panel:AddControl("Header", { Text = "#Tool_wire_adv_hud_menu_name", Description = "#Tool_wire_adv_hud_menu_desc" }) panel:AddControl("Label", { Text = "HML is loaded to the entity from whatever is open in the editor."}) panel:AddControl("Button", { Label = "#Tool_wire_adv_hud_menu_showEditor", Text = "Open Editor", Command = "openH2Editor" }) panel:AddControl("Label", { Text = "" }) panel:AddControl("CheckBox", { Label = "Show stats?", Command = "HUD2_showStats" }) end
repeat task.wait() until game:IsLoaded() == true local customdir = (shared.VapePrivate and "vapeprivate/" or "vape/") local betterisfile = function(file) local suc, res = pcall(function() return readfile(file) end) return suc and res ~= nil end local function GetURL(scripturl) if shared.VapeDeveloper then if not betterisfile("vape/"..scripturl) then error("File not found : vape/"..scripturl) end return readfile("vape/"..scripturl) else local res = game:HttpGet("https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/"..scripturl, true) assert(res ~= "404: Not Found", "File not found") return res end end local getasset = getsynasset or getcustomasset or function(location) return "rbxasset://"..location end local queueteleport = syn and syn.queue_on_teleport or queue_on_teleport or fluxus and fluxus.queue_on_teleport or function() end local requestfunc = syn and syn.request or http and http.request or http_request or fluxus and fluxus.request or request or function(tab) if tab.Method == "GET" then return { Body = game:HttpGet(tab.Url, true), Headers = {}, StatusCode = 200 } else return { Body = "bad exploit", Headers = {}, StatusCode = 404 } end end local function checkassetversion() local req = requestfunc({ Url = "https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/assetsversion.dat", Method = "GET" }) if req.StatusCode == 200 then return req.Body else return nil end end if not (getasset and requestfunc and queueteleport) then print("Vape not supported with your exploit.") return end if shared.VapeExecuted then error("Vape Already Injected") return else shared.VapeExecuted = true end if isfolder(customdir:gsub("/", "")) == false then makefolder(customdir:gsub("/", "")) end if isfolder("vape") == false then makefolder("vape") end if not betterisfile("vape/assetsversion.dat") then writefile("vape/assetsversion.dat", "1") end if isfolder(customdir.."CustomModules") == false then makefolder(customdir.."CustomModules") end if isfolder(customdir.."Profiles") == false then makefolder(customdir.."Profiles") end if not betterisfile("vape/language.dat") then local suc, res = pcall(function() return gethiddenproperty(game:GetService("Players").LocalPlayer, "ReplicatedLocaleId") end) writefile("vape/language.dat", suc and res or "en-us") end if not pcall(function() return GetURL("translations/"..readfile("vape/language.dat")..".vapetranslation") end) then writefile("vape/language.dat", "en-us") end local assetver = checkassetversion() if assetver and assetver > readfile("vape/assetsversion.dat") then if shared.VapeDeveloper == nil then if isfolder("vape/assets") then if delfolder then delfolder("vape/assets") end end writefile("vape/assetsversion.dat", assetver) end end if isfolder("vape/assets") == false then makefolder("vape/assets") end local GuiLibrary = loadstring(GetURL("NewGuiLibrary.lua"))() local translations = loadstring(GetURL("translations/"..GuiLibrary["Language"]..".vapetranslation"))() local translatedlogo = pcall(function() return GetURL("translations/"..GuiLibrary["Language"].."/VapeLogo1.png") end) local checkpublicreponum = 0 local checkpublicrepo checkpublicrepo = function(id) local suc, req = pcall(function() return requestfunc({ Url = "https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/CustomModules/"..id..".vape", Method = "GET" }) end) if not suc then checkpublicreponum = checkpublicreponum + 1 spawn(function() local textlabel = Instance.new("TextLabel") textlabel.Size = UDim2.new(1, 0, 0, 36) textlabel.Text = "Loading CustomModule Failed!, Attempts : "..checkpublicreponum textlabel.BackgroundTransparency = 1 textlabel.TextStrokeTransparency = 0 textlabel.TextSize = 30 textlabel.Font = Enum.Font.SourceSans textlabel.TextColor3 = Color3.new(1, 1, 1) textlabel.Position = UDim2.new(0, 0, 0, -36) textlabel.Parent = GuiLibrary["MainGui"] task.wait(2) textlabel:Remove() end) task.wait(2) return checkpublicrepo(id) end if req.StatusCode == 200 then return req.Body end return nil end local function getcustomassetfunc(path) if not betterisfile(path) then spawn(function() local textlabel = Instance.new("TextLabel") textlabel.Size = UDim2.new(1, 0, 0, 36) textlabel.Text = "Downloading "..path textlabel.BackgroundTransparency = 1 textlabel.TextStrokeTransparency = 0 textlabel.TextSize = 30 textlabel.Font = Enum.Font.SourceSans textlabel.TextColor3 = Color3.new(1, 1, 1) textlabel.Position = UDim2.new(0, 0, 0, -36) textlabel.Parent = GuiLibrary["MainGui"] repeat task.wait() until betterisfile(path) textlabel:Remove() end) local req = requestfunc({ Url = "https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/"..path:gsub("vape/assets", "assets"), Method = "GET" }) writefile(path, req.Body) end return getasset(path) end shared.GuiLibrary = GuiLibrary local workspace = game:GetService("Workspace") local cam = workspace.CurrentCamera local selfdestructsave = coroutine.create(function() while task.wait(10) do GuiLibrary["SaveSettings"]() end end) local GUI = GuiLibrary.CreateMainWindow() local Combat = GuiLibrary.CreateWindow({ ["Name"] = "Combat", ["Icon"] = "vape/assets/CombatIcon.png", ["IconSize"] = 15 }) local Blatant = GuiLibrary.CreateWindow({ ["Name"] = "Blatant", ["Icon"] = "vape/assets/BlatantIcon.png", ["IconSize"] = 16 }) local Render = GuiLibrary.CreateWindow({ ["Name"] = "Render", ["Icon"] = "vape/assets/RenderIcon.png", ["IconSize"] = 17 }) local Utility = GuiLibrary.CreateWindow({ ["Name"] = "Utility", ["Icon"] = "vape/assets/UtilityIcon.png", ["IconSize"] = 17 }) local World = GuiLibrary.CreateWindow({ ["Name"] = "World", ["Icon"] = "vape/assets/WorldIcon.png", ["IconSize"] = 16 }) local Friends = GuiLibrary.CreateWindow2({ ["Name"] = "Friends", ["Icon"] = "vape/assets/FriendsIcon.png", ["IconSize"] = 17 }) local Profiles = GuiLibrary.CreateWindow2({ ["Name"] = "Profiles", ["Icon"] = "vape/assets/ProfilesIcon.png", ["IconSize"] = 19 }) GUI.CreateDivider() GUI.CreateButton({ ["Name"] = "Combat", ["Function"] = function(callback) Combat.SetVisible(callback) end, ["Icon"] = "vape/assets/CombatIcon.png", ["IconSize"] = 15 }) GUI.CreateButton({ ["Name"] = "Blatant", ["Function"] = function(callback) Blatant.SetVisible(callback) end, ["Icon"] = "vape/assets/BlatantIcon.png", ["IconSize"] = 16 }) GUI.CreateButton({ ["Name"] = "Render", ["Function"] = function(callback) Render.SetVisible(callback) end, ["Icon"] = "vape/assets/RenderIcon.png", ["IconSize"] = 17 }) GUI.CreateButton({ ["Name"] = "Utility", ["Function"] = function(callback) Utility.SetVisible(callback) end, ["Icon"] = "vape/assets/UtilityIcon.png", ["IconSize"] = 17 }) GUI.CreateButton({ ["Name"] = "World", ["Function"] = function(callback) World.SetVisible(callback) end, ["Icon"] = "vape/assets/WorldIcon.png", ["IconSize"] = 16 }) GUI.CreateDivider("MISC") GUI.CreateButton({ ["Name"] = "Friends", ["Function"] = function(callback) Friends.SetVisible(callback) end, }) GUI.CreateButton({ ["Name"] = "Profiles", ["Function"] = function(callback) Profiles.SetVisible(callback) end, }) local FriendsTextList = {["RefreshValues"] = function() end} local FriendsColor = {["Value"] = 0.44} FriendsTextList = Friends.CreateCircleTextList({ ["Name"] = "FriendsList", ["TempText"] = "Username / Alias", ["Color"] = Color3.fromRGB(5, 133, 104), ["CustomFunction"] = function(obj) obj.ItemText.TextColor3 = Color3.new(1, 1, 1) local friendcircle = Instance.new("Frame") friendcircle.Size = UDim2.new(0, 10, 0, 10) friendcircle.Name = "FriendCircle" friendcircle.BackgroundColor3 = Color3.fromHSV(FriendsColor["Value"], 0.7, 0.9) friendcircle.BorderSizePixel = 0 friendcircle.Position = UDim2.new(0, 10, 0, 13) friendcircle.Parent = obj local friendcorner = Instance.new("UICorner") friendcorner.CornerRadius = UDim.new(0, 8) friendcorner.Parent = friendcircle obj.ItemText.Position = UDim2.new(0, 36, 0, 0) obj.ItemText.Size = UDim2.new(0, 157, 0, 33) end }) FriendsTextList.FriendRefresh = Instance.new("BindableEvent") spawn(function() local currentval = #FriendsTextList["ObjectList"] repeat task.wait(0.1) if currentval ~= #FriendsTextList["ObjectList"] then FriendsTextList.FriendRefresh:Fire() end currentval = #FriendsTextList["ObjectList"] until (not shared.VapeExecuted) end) Friends.CreateToggle({ ["Name"] = "Use Friends", ["Function"] = function(callback) end, ["Default"] = true }) Friends.CreateToggle({ ["Name"] = "Use Alias", ["Function"] = function(callback) end, ["Default"] = true, }) Friends.CreateToggle({ ["Name"] = "Spoof alias", ["Function"] = function(callback) end, }) Friends.CreateToggle({ ["Name"] = "Recolor visuals", ["Function"] = function(callback) end, ["Default"] = true }) FriendsColor = Friends.CreateColorSlider({ ["Name"] = "Friends Color", ["Function"] = function(val) end }) local ProfilesTextList = {["RefreshValues"] = function() end} local profilesloaded = false ProfilesTextList = Profiles.CreateTextList({ ["Name"] = "ProfilesList", ["TempText"] = "Type name", ["AddFunction"] = function(user) GuiLibrary["Profiles"][user] = {["Keybind"] = "", ["Selected"] = false} end, ["RemoveFunction"] = function(num) if #ProfilesTextList["ObjectList"] == 0 then table.insert(ProfilesTextList["ObjectList"], "default") ProfilesTextList["RefreshValues"](ProfilesTextList["ObjectList"]) end end, ["CustomFunction"] = function(obj, profilename) if GuiLibrary["Profiles"][profilename] == nil then GuiLibrary["Profiles"][profilename] = {["Keybind"] = ""} end obj.MouseButton1Click:connect(function() GuiLibrary["SwitchProfile"](profilename) end) local newsize = UDim2.new(0, 20, 0, 21) local bindbkg = Instance.new("TextButton") bindbkg.Text = "" bindbkg.AutoButtonColor = false bindbkg.Size = UDim2.new(0, 20, 0, 21) bindbkg.Position = UDim2.new(1, -50, 0, 6) bindbkg.BorderSizePixel = 0 bindbkg.BackgroundColor3 = Color3.fromRGB(255, 255, 255) bindbkg.BackgroundTransparency = 0.95 bindbkg.Visible = GuiLibrary["Profiles"][profilename]["Keybind"] ~= "" bindbkg.Parent = obj local bindimg = Instance.new("ImageLabel") bindimg.Image = getcustomassetfunc("vape/assets/KeybindIcon.png") bindimg.BackgroundTransparency = 1 bindimg.Size = UDim2.new(0, 12, 0, 12) bindimg.Position = UDim2.new(0, 4, 0, 5) bindimg.ImageTransparency = 0.2 bindimg.Active = false bindimg.Visible = (GuiLibrary["Profiles"][profilename]["Keybind"] == "") bindimg.Parent = bindbkg local bindtext = Instance.new("TextLabel") bindtext.Active = false bindtext.BackgroundTransparency = 1 bindtext.TextSize = 16 bindtext.Parent = bindbkg bindtext.Font = Enum.Font.SourceSans bindtext.Size = UDim2.new(1, 0, 1, 0) bindtext.TextColor3 = Color3.fromRGB(85, 85, 85) bindtext.Visible = (GuiLibrary["Profiles"][profilename]["Keybind"] ~= "") local bindtext2 = Instance.new("TextLabel") bindtext2.Text = "PRESS A KEY TO BIND" bindtext2.Size = UDim2.new(0, 150, 0, 33) bindtext2.Font = Enum.Font.SourceSans bindtext2.TextSize = 17 bindtext2.TextColor3 = Color3.fromRGB(201, 201, 201) bindtext2.BackgroundColor3 = Color3.fromRGB(37, 37, 37) bindtext2.BorderSizePixel = 0 bindtext2.Visible = false bindtext2.Parent = obj local bindround = Instance.new("UICorner") bindround.CornerRadius = UDim.new(0, 4) bindround.Parent = bindbkg bindbkg.MouseButton1Click:connect(function() if GuiLibrary["KeybindCaptured"] == false then GuiLibrary["KeybindCaptured"] = true spawn(function() bindtext2.Visible = true repeat task.wait() until GuiLibrary["PressedKeybindKey"] ~= "" local key = (GuiLibrary["PressedKeybindKey"] == GuiLibrary["Profiles"][profilename]["Keybind"] and "" or GuiLibrary["PressedKeybindKey"]) if key == "" then GuiLibrary["Profiles"][profilename]["Keybind"] = key newsize = UDim2.new(0, 20, 0, 21) bindbkg.Size = newsize bindbkg.Visible = true bindbkg.Position = UDim2.new(1, -(30 + newsize.X.Offset), 0, 6) bindimg.Visible = true bindtext.Visible = false bindtext.Text = key else local textsize = game:GetService("TextService"):GetTextSize(key, 16, bindtext.Font, Vector2.new(99999, 99999)) newsize = UDim2.new(0, 13 + textsize.X, 0, 21) GuiLibrary["Profiles"][profilename]["Keybind"] = key bindbkg.Visible = true bindbkg.Size = newsize bindbkg.Position = UDim2.new(1, -(30 + newsize.X.Offset), 0, 6) bindimg.Visible = false bindtext.Visible = true bindtext.Text = key end GuiLibrary["PressedKeybindKey"] = "" GuiLibrary["KeybindCaptured"] = false bindtext2.Visible = false end) end end) bindbkg.MouseEnter:connect(function() bindimg.Image = getcustomassetfunc("vape/assets/PencilIcon.png") bindimg.Visible = true bindtext.Visible = false bindbkg.Size = UDim2.new(0, 20, 0, 21) bindbkg.Position = UDim2.new(1, -50, 0, 6) end) bindbkg.MouseLeave:connect(function() bindimg.Image = getcustomassetfunc("vape/assets/KeybindIcon.png") if GuiLibrary["Profiles"][profilename]["Keybind"] ~= "" then bindimg.Visible = false bindtext.Visible = true bindbkg.Size = newsize bindbkg.Position = UDim2.new(1, -(30 + newsize.X.Offset), 0, 6) end end) obj.MouseEnter:connect(function() bindbkg.Visible = true end) obj.MouseLeave:connect(function() bindbkg.Visible = GuiLibrary["Profiles"][profilename]["Keybind"] ~= "" end) if GuiLibrary["Profiles"][profilename]["Keybind"] ~= "" then bindtext.Text = GuiLibrary["Profiles"][profilename]["Keybind"] local textsize = game:GetService("TextService"):GetTextSize(GuiLibrary["Profiles"][profilename]["Keybind"], 16, bindtext.Font, Vector2.new(99999, 99999)) newsize = UDim2.new(0, 13 + textsize.X, 0, 21) bindbkg.Size = newsize bindbkg.Position = UDim2.new(1, -(30 + newsize.X.Offset), 0, 6) end if profilename == GuiLibrary["CurrentProfile"] then obj.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) obj.ImageButton.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) obj.ItemText.TextColor3 = Color3.new(1, 1, 1) obj.ItemText.TextStrokeTransparency = 0.75 bindbkg.BackgroundTransparency = 0.9 bindtext.TextColor3 = Color3.fromRGB(214, 214, 214) end end }) local OnlineProfilesButton = Instance.new("TextButton") OnlineProfilesButton.Name = "OnlineProfilesButton" OnlineProfilesButton.LayoutOrder = 1 OnlineProfilesButton.AutoButtonColor = false OnlineProfilesButton.Size = UDim2.new(0, 45, 0, 29) OnlineProfilesButton.BackgroundColor3 = Color3.fromRGB(26, 25, 26) OnlineProfilesButton.Active = false OnlineProfilesButton.Text = "" OnlineProfilesButton.ZIndex = 1 OnlineProfilesButton.Font = Enum.Font.SourceSans OnlineProfilesButton.TextXAlignment = Enum.TextXAlignment.Left OnlineProfilesButton.Position = UDim2.new(0, 166, 0, 6) OnlineProfilesButton.Parent = ProfilesTextList["Object"] local OnlineProfilesButtonBKG = Instance.new("UIStroke") OnlineProfilesButtonBKG.Color = Color3.fromRGB(38, 37, 38) OnlineProfilesButtonBKG.Thickness = 1 OnlineProfilesButtonBKG.ApplyStrokeMode = Enum.ApplyStrokeMode.Border OnlineProfilesButtonBKG.Parent = OnlineProfilesButton local OnlineProfilesButtonImage = Instance.new("ImageLabel") OnlineProfilesButtonImage.BackgroundTransparency = 1 OnlineProfilesButtonImage.Position = UDim2.new(0, 14, 0, 7) OnlineProfilesButtonImage.Size = UDim2.new(0, 17, 0, 16) OnlineProfilesButtonImage.Image = getcustomassetfunc("vape/assets/OnlineProfilesButton.png") OnlineProfilesButtonImage.ImageColor3 = Color3.fromRGB(121, 121, 121) OnlineProfilesButtonImage.ZIndex = 1 OnlineProfilesButtonImage.Active = false OnlineProfilesButtonImage.Parent = OnlineProfilesButton local OnlineProfilesbuttonround1 = Instance.new("UICorner") OnlineProfilesbuttonround1.CornerRadius = UDim.new(0, 5) OnlineProfilesbuttonround1.Parent = OnlineProfilesButton local OnlineProfilesbuttonround2 = Instance.new("UICorner") OnlineProfilesbuttonround2.CornerRadius = UDim.new(0, 5) OnlineProfilesbuttonround2.Parent = OnlineProfilesButtonBKG local OnlineProfilesFrame = Instance.new("Frame") OnlineProfilesFrame.Size = UDim2.new(0, 660, 0, 445) OnlineProfilesFrame.Position = UDim2.new(0.5, -330, 0.5, -223) OnlineProfilesFrame.BackgroundColor3 = Color3.fromRGB(26, 25, 26) OnlineProfilesFrame.Parent = GuiLibrary["MainGui"].ScaledGui.OnlineProfiles local OnlineProfilesExitButton = Instance.new("ImageButton") OnlineProfilesExitButton.Name = "OnlineProfilesExitButton" OnlineProfilesExitButton.ImageColor3 = Color3.fromRGB(121, 121, 121) OnlineProfilesExitButton.Size = UDim2.new(0, 24, 0, 24) OnlineProfilesExitButton.AutoButtonColor = false OnlineProfilesExitButton.Image = getcustomassetfunc("vape/assets/ExitIcon1.png") OnlineProfilesExitButton.Visible = true OnlineProfilesExitButton.Position = UDim2.new(1, -31, 0, 8) OnlineProfilesExitButton.BackgroundColor3 = Color3.fromRGB(26, 25, 26) OnlineProfilesExitButton.Parent = OnlineProfilesFrame local OnlineProfilesExitButtonround = Instance.new("UICorner") OnlineProfilesExitButtonround.CornerRadius = UDim.new(0, 16) OnlineProfilesExitButtonround.Parent = OnlineProfilesExitButton OnlineProfilesExitButton.MouseEnter:connect(function() game:GetService("TweenService"):Create(OnlineProfilesExitButton, TweenInfo.new(0.1, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut), {BackgroundColor3 = Color3.fromRGB(60, 60, 60), ImageColor3 = Color3.fromRGB(255, 255, 255)}):Play() end) OnlineProfilesExitButton.MouseLeave:connect(function() game:GetService("TweenService"):Create(OnlineProfilesExitButton, TweenInfo.new(0.1, Enum.EasingStyle.Quad, Enum.EasingDirection.InOut), {BackgroundColor3 = Color3.fromRGB(26, 25, 26), ImageColor3 = Color3.fromRGB(121, 121, 121)}):Play() end) local OnlineProfilesFrameShadow = Instance.new("ImageLabel") OnlineProfilesFrameShadow.AnchorPoint = Vector2.new(0.5, 0.5) OnlineProfilesFrameShadow.Position = UDim2.new(0.5, 0, 0.5, 0) OnlineProfilesFrameShadow.Image = getcustomassetfunc("vape/assets/WindowBlur.png") OnlineProfilesFrameShadow.BackgroundTransparency = 1 OnlineProfilesFrameShadow.ZIndex = -1 OnlineProfilesFrameShadow.Size = UDim2.new(1, 6, 1, 6) OnlineProfilesFrameShadow.ImageColor3 = Color3.new(0, 0, 0) OnlineProfilesFrameShadow.ScaleType = Enum.ScaleType.Slice OnlineProfilesFrameShadow.SliceCenter = Rect.new(10, 10, 118, 118) OnlineProfilesFrameShadow.Parent = OnlineProfilesFrame local OnlineProfilesFrameIcon = Instance.new("ImageLabel") OnlineProfilesFrameIcon.Size = UDim2.new(0, 19, 0, 16) OnlineProfilesFrameIcon.Image = getcustomassetfunc("vape/assets/ProfilesIcon.png") OnlineProfilesFrameIcon.Name = "WindowIcon" OnlineProfilesFrameIcon.BackgroundTransparency = 1 OnlineProfilesFrameIcon.Position = UDim2.new(0, 10, 0, 13) OnlineProfilesFrameIcon.ImageColor3 = Color3.fromRGB(200, 200, 200) OnlineProfilesFrameIcon.Parent = OnlineProfilesFrame local OnlineProfilesFrameText = Instance.new("TextLabel") OnlineProfilesFrameText.Size = UDim2.new(0, 155, 0, 41) OnlineProfilesFrameText.BackgroundTransparency = 1 OnlineProfilesFrameText.Name = "WindowTitle" OnlineProfilesFrameText.Position = UDim2.new(0, 36, 0, 0) OnlineProfilesFrameText.TextXAlignment = Enum.TextXAlignment.Left OnlineProfilesFrameText.Font = Enum.Font.SourceSans OnlineProfilesFrameText.TextSize = 17 OnlineProfilesFrameText.Text = "Profiles" OnlineProfilesFrameText.TextColor3 = Color3.fromRGB(201, 201, 201) OnlineProfilesFrameText.Parent = OnlineProfilesFrame local OnlineProfilesFrameText2 = Instance.new("TextLabel") OnlineProfilesFrameText2.TextSize = 15 OnlineProfilesFrameText2.TextColor3 = Color3.fromRGB(85, 84, 85) OnlineProfilesFrameText2.Text = "YOUR PROFILES" OnlineProfilesFrameText2.Font = Enum.Font.SourceSans OnlineProfilesFrameText2.BackgroundTransparency = 1 OnlineProfilesFrameText2.TextXAlignment = Enum.TextXAlignment.Left OnlineProfilesFrameText2.TextYAlignment = Enum.TextYAlignment.Top OnlineProfilesFrameText2.Size = UDim2.new(1, 0, 0, 20) OnlineProfilesFrameText2.Position = UDim2.new(0, 10, 0, 48) OnlineProfilesFrameText2.Parent = OnlineProfilesFrame local OnlineProfilesFrameText3 = Instance.new("TextLabel") OnlineProfilesFrameText3.TextSize = 15 OnlineProfilesFrameText3.TextColor3 = Color3.fromRGB(85, 84, 85) OnlineProfilesFrameText3.Text = "PUBLIC PROFILES" OnlineProfilesFrameText3.Font = Enum.Font.SourceSans OnlineProfilesFrameText3.BackgroundTransparency = 1 OnlineProfilesFrameText3.TextXAlignment = Enum.TextXAlignment.Left OnlineProfilesFrameText3.TextYAlignment = Enum.TextYAlignment.Top OnlineProfilesFrameText3.Size = UDim2.new(1, 0, 0, 20) OnlineProfilesFrameText3.Position = UDim2.new(0, 231, 0, 48) OnlineProfilesFrameText3.Parent = OnlineProfilesFrame local OnlineProfilesBorder1 = Instance.new("Frame") OnlineProfilesBorder1.BackgroundColor3 = Color3.fromRGB(40, 39, 40) OnlineProfilesBorder1.BorderSizePixel = 0 OnlineProfilesBorder1.Size = UDim2.new(1, 0, 0, 1) OnlineProfilesBorder1.Position = UDim2.new(0, 0, 0, 41) OnlineProfilesBorder1.Parent = OnlineProfilesFrame local OnlineProfilesBorder2 = Instance.new("Frame") OnlineProfilesBorder2.BackgroundColor3 = Color3.fromRGB(40, 39, 40) OnlineProfilesBorder2.BorderSizePixel = 0 OnlineProfilesBorder2.Size = UDim2.new(0, 1, 1, -41) OnlineProfilesBorder2.Position = UDim2.new(0, 220, 0, 41) OnlineProfilesBorder2.Parent = OnlineProfilesFrame local OnlineProfilesList = Instance.new("ScrollingFrame") OnlineProfilesList.BackgroundTransparency = 1 OnlineProfilesList.Size = UDim2.new(0, 408, 0, 319) OnlineProfilesList.Position = UDim2.new(0, 230, 0, 122) OnlineProfilesList.CanvasSize = UDim2.new(0, 408, 0, 319) OnlineProfilesList.Parent = OnlineProfilesFrame local OnlineProfilesListGrid = Instance.new("UIGridLayout") OnlineProfilesListGrid.CellSize = UDim2.new(0, 134, 0, 144) OnlineProfilesListGrid.CellPadding = UDim2.new(0, 4, 0, 4) OnlineProfilesListGrid.Parent = OnlineProfilesList local OnlineProfilesFrameCorner = Instance.new("UICorner") OnlineProfilesFrameCorner.CornerRadius = UDim.new(0, 4) OnlineProfilesFrameCorner.Parent = OnlineProfilesFrame OnlineProfilesButton.MouseButton1Click:connect(function() GuiLibrary["MainGui"].ScaledGui.OnlineProfiles.Visible = true GuiLibrary["MainGui"].ScaledGui.ClickGui.Visible = false if profilesloaded == false then local onlineprofiles = {} local success, result = pcall(function() return game:GetService("HttpService"):JSONDecode((shared.VapeDeveloper and readfile("vape/OnlineProfiles.vapeonline") or game:HttpGet("https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/OnlineProfiles.vapeonline", true))) end) onlineprofiles = (success and result or {}) for i2,v2 in pairs(onlineprofiles) do if v2["ProfileGame"] == game.PlaceId then local profilebox = Instance.new("Frame") profilebox.BackgroundColor3 = Color3.fromRGB(31, 30, 31) profilebox.Parent = OnlineProfilesList local profiletext = Instance.new("TextLabel") profiletext.TextSize = 15 profiletext.TextColor3 = Color3.fromRGB(137, 136, 137) profiletext.Size = UDim2.new(0, 100, 0, 20) profiletext.Position = UDim2.new(0, 18, 0, 25) profiletext.Font = Enum.Font.SourceSans profiletext.TextXAlignment = Enum.TextXAlignment.Left profiletext.TextYAlignment = Enum.TextYAlignment.Top profiletext.BackgroundTransparency = 1 profiletext.Text = i2 profiletext.Parent = profilebox local profiledownload = Instance.new("TextButton") profiledownload.BackgroundColor3 = Color3.fromRGB(31, 30, 31) profiledownload.Size = UDim2.new(0, 69, 0, 31) profiledownload.Font = Enum.Font.SourceSans profiledownload.TextColor3 = Color3.fromRGB(200, 200, 200) profiledownload.TextSize = 15 profiledownload.AutoButtonColor = false profiledownload.Text = "DOWNLOAD" profiledownload.Position = UDim2.new(0, 14, 0, 96) profiledownload.Visible = false profiledownload.Parent = profilebox profiledownload.ZIndex = 2 local profiledownloadbkg = Instance.new("Frame") profiledownloadbkg.Size = UDim2.new(0, 71, 0, 33) profiledownloadbkg.BackgroundColor3 = Color3.fromRGB(42, 41, 42) profiledownloadbkg.Position = UDim2.new(0, 13, 0, 95) profiledownloadbkg.ZIndex = 1 profiledownloadbkg.Visible = false profiledownloadbkg.Parent = profilebox profilebox.MouseEnter:connect(function() profiletext.TextColor3 = Color3.fromRGB(200, 200, 200) profiledownload.Visible = true profiledownloadbkg.Visible = true end) profilebox.MouseLeave:connect(function() profiletext.TextColor3 = Color3.fromRGB(137, 136, 137) profiledownload.Visible = false profiledownloadbkg.Visible = false end) profiledownload.MouseEnter:connect(function() profiledownload.BackgroundColor3 = Color3.fromRGB(5, 134, 105) end) profiledownload.MouseLeave:connect(function() profiledownload.BackgroundColor3 = Color3.fromRGB(31, 30, 31) end) profiledownload.MouseButton1Click:connect(function() writefile(customdir.."Profiles/"..v2["ProfileName"]..tostring(game.PlaceId)..".vapeprofile.txt", (shared.VapeDeveloper and readfile("vape/OnlineProfiles/"..v2["OnlineProfileName"]) or game:HttpGet("https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/OnlineProfiles/"..v2["OnlineProfileName"], true))) GuiLibrary["Profiles"][v2["ProfileName"]] = {["Keybind"] = "", ["Selected"] = false} if table.find(ProfilesTextList["ObjectList"], v2["ProfileName"]) == nil then table.insert(ProfilesTextList["ObjectList"], v2["ProfileName"]) end ProfilesTextList["RefreshValues"](ProfilesTextList["ObjectList"]) end) local profileround = Instance.new("UICorner") profileround.CornerRadius = UDim.new(0, 4) profileround.Parent = profilebox local profileround2 = Instance.new("UICorner") profileround2.CornerRadius = UDim.new(0, 4) profileround2.Parent = profiledownload local profileround3 = Instance.new("UICorner") profileround3.CornerRadius = UDim.new(0, 4) profileround3.Parent = profiledownloadbkg end end profilesloaded = true end end) OnlineProfilesExitButton.MouseButton1Click:connect(function() GuiLibrary["MainGui"].ScaledGui.OnlineProfiles.Visible = false GuiLibrary["MainGui"].ScaledGui.ClickGui.Visible = true end) GUI.CreateDivider() ---GUI.CreateCustomButton("Favorites", "vape/assets/FavoritesListIcon.png", UDim2.new(0, 17, 0, 14), function() end, function() end) --GUI.CreateCustomButton("Text GUIVertical", "vape/assets/TextGUIIcon3.png", UDim2.new(1, -56, 0, 15), function() end, function() end) local TextGui = GuiLibrary.CreateCustomWindow({ ["Name"] = "Text GUI", ["Icon"] = "vape/assets/TextGUIIcon1.png", ["IconSize"] = 21 }) local TextGuiCircleObject = {["CircleList"] = {}} --GUI.CreateCustomButton("Text GUI", "vape/assets/TextGUIIcon2.png", UDim2.new(1, -23, 0, 15), function() TextGui.SetVisible(true) end, function() TextGui.SetVisible(false) end, "OptionsButton") GUI.CreateCustomToggle({ ["Name"] = "Text GUI", ["Icon"] = "vape/assets/TextGUIIcon3.png", ["Function"] = function(callback) TextGui.SetVisible(callback) end, ["Priority"] = 2 }) local rainbowval = ColorSequence.new({ColorSequenceKeypoint.new(0, Color3.fromHSV(0, 0, 1)), ColorSequenceKeypoint.new(1, Color3.fromHSV(0, 0, 1))}) local rainbowval2 = ColorSequence.new({ColorSequenceKeypoint.new(0, Color3.fromHSV(0, 0, 0.42)), ColorSequenceKeypoint.new(1, Color3.fromHSV(0, 0, 0.42))}) local rainbowval3 = ColorSequence.new({ColorSequenceKeypoint.new(0, Color3.fromHSV(0, 0, 1)), ColorSequenceKeypoint.new(1, Color3.fromHSV(0, 0, 1))}) local guicolorslider = {["RainbowValue"] = false} local textguiscaleslider = {["Value"] = 10} local onething = Instance.new("ImageLabel") onething.Parent = TextGui.GetCustomChildren() onething.Name = "Logo" onething.Size = UDim2.new(0, 100, 0, 27) onething.Position = UDim2.new(1, -140, 0, 3) onething.BackgroundColor3 = Color3.new(0, 0, 0) onething.BorderSizePixel = 0 onething.BackgroundTransparency = 1 onething.Visible = false onething.Image = getcustomassetfunc(translatedlogo and "vape/translations/"..GuiLibrary["Language"].."/VapeLogo3.png" or "vape/assets/VapeLogo3.png") local onething2 = Instance.new("ImageLabel") onething2.Parent = onething onething2.Size = UDim2.new(0, 41, 0, 24) onething2.Name = "Logo2" onething2.Position = UDim2.new(1, 0, 0, 1) onething2.BorderSizePixel = 0 onething2.BackgroundColor3 = Color3.new(0, 0, 0) onething2.BackgroundTransparency = 1 onething2.Image = getcustomassetfunc("vape/assets/VapeLogo4.png") local onething3 = onething:Clone() onething3.ImageColor3 = Color3.new(0, 0, 0) onething3.ImageTransparency = 0.5 onething3.ZIndex = 0 onething3.Position = UDim2.new(0, 1, 0, 1) onething3.Visible = false onething3.Parent = onething onething3.Logo2.ImageColor3 = Color3.new(0, 0, 0) onething3.Logo2.ZIndex = 0 onething3.Logo2.ImageTransparency = 0.5 local onetext = Instance.new("TextLabel") onetext.Parent = TextGui.GetCustomChildren() onetext.Size = UDim2.new(1, 0, 1, 0) onetext.Position = UDim2.new(1, -154, 0, 35) onetext.TextColor3 = Color3.new(1, 1, 1) onetext.RichText = true onetext.BackgroundTransparency = 1 onetext.TextXAlignment = Enum.TextXAlignment.Left onetext.TextYAlignment = Enum.TextYAlignment.Top onetext.BorderSizePixel = 0 onetext.BackgroundColor3 = Color3.new(0, 0, 0) onetext.Font = Enum.Font.SourceSans onetext.Text = "" onetext.TextSize = 23 local onetext2 = Instance.new("TextLabel") onetext2.Name = "ExtraText" onetext2.Parent = onetext onetext2.Size = UDim2.new(1, 0, 1, 0) onetext2.Position = UDim2.new(0, 1, 0, 1) onetext2.BorderSizePixel = 0 onetext2.Visible = false onetext2.ZIndex = 0 onetext2.Text = "" onetext2.BackgroundTransparency = 1 onetext2.TextTransparency = 0.5 onetext2.TextXAlignment = Enum.TextXAlignment.Left onetext2.TextYAlignment = Enum.TextYAlignment.Top onetext2.TextColor3 = Color3.new(0, 0, 0) onetext2.Font = Enum.Font.SourceSans onetext2.TextSize = 23 local onebackground = Instance.new("Frame") onebackground.BackgroundTransparency = 1 onebackground.BorderSizePixel = 0 onebackground.BackgroundColor3 = Color3.new(0, 0, 0) onebackground.Size = UDim2.new(1, 0, 1, 0) onebackground.Visible = false onebackground.Parent = TextGui.GetCustomChildren() onebackground.ZIndex = 0 local onebackgroundsort = Instance.new("UIListLayout") onebackgroundsort.FillDirection = Enum.FillDirection.Vertical onebackgroundsort.SortOrder = Enum.SortOrder.LayoutOrder onebackgroundsort.Padding = UDim.new(0, 0) onebackgroundsort.Parent = onebackground local onescale = Instance.new("UIScale") onescale.Parent = TextGui.GetCustomChildren() local textguirenderbkg = {["Enabled"] = false} local function refreshbars(textlists) for i,v in pairs(onebackground:GetChildren()) do if v:IsA("Frame") then v:Remove() end end for i2,v2 in pairs(textlists) do local newstr = v2:gsub(":", " ") local textsize = game:GetService("TextService"):GetTextSize(newstr, onetext.TextSize, onetext.Font, Vector2.new(1000000, 1000000)) local frame = Instance.new("Frame") frame.BorderSizePixel = 0 frame.BackgroundTransparency = 0.62 frame.BackgroundColor3 = Color3.new(0,0,0) frame.Visible = true frame.ZIndex = 0 frame.LayoutOrder = i2 frame.Size = UDim2.new(0, textsize.X + 8, 0, textsize.Y - (onescale.Scale - 1)) frame.Parent = onebackground local colorframe = Instance.new("Frame") colorframe.Size = UDim2.new(0, 2, 1, 0) colorframe.Position = (onebackgroundsort.HorizontalAlignment == Enum.HorizontalAlignment.Left and UDim2.new(0, 0, 0, 0) or UDim2.new(1, -2, 0, 0)) colorframe.BorderSizePixel = 0 colorframe.Name = "ColorFrame" colorframe.Parent = frame local extraframe = Instance.new("Frame") extraframe.BorderSizePixel = 0 extraframe.BackgroundTransparency = 0.96 extraframe.BackgroundColor3 = Color3.new(0, 0, 0) extraframe.ZIndex = 0 extraframe.Size = UDim2.new(1, 0, 0, 2) extraframe.Position = UDim2.new(0, 0, 1, -1) extraframe.Parent = frame end end onething.Visible = true onetext.Position = UDim2.new(0, 0, 0, 41) local sortingmethod = "Alphabetical" local textwithoutthing = "" local function getSpaces(str) local strSize = game:GetService("TextService"):GetTextSize(str, onetext.TextSize, onetext.TextSize, Vector2.new(10000, 10000)) return math.ceil(strSize.X / 3) end local function UpdateHud() local text = "" local text2 = "" local tableofmodules = {} local first = true for i,v in pairs(GuiLibrary["ObjectsThatCanBeSaved"]) do if v["Type"] == "OptionsButton" and v["Api"]["Name"] ~= "Text GUI" then if v["Api"]["Enabled"] then local blacklisted = table.find(TextGuiCircleObject["CircleList"]["ObjectList"], v["Api"]["Name"]) and TextGuiCircleObject["CircleList"]["ObjectListEnabled"][table.find(TextGuiCircleObject["CircleList"]["ObjectList"], v["Api"]["Name"])] if not blacklisted then table.insert(tableofmodules, {["Text"] = v["Api"]["Name"], ["ExtraText"] = v["Api"]["GetExtraText"]}) end end end end if sortingmethod == "Alphabetical" then table.sort(tableofmodules, function(a, b) return a["Text"]:lower() < b["Text"]:lower() end) else table.sort(tableofmodules, function(a, b) local textsize1 = (translations[a["Text"]] ~= nil and translations[a["Text"]] or a["Text"])..(a["ExtraText"] and a["ExtraText"]() or "") local textsize2 = (translations[b["Text"]] ~= nil and translations[b["Text"]] or b["Text"])..(b["ExtraText"] and b["ExtraText"]() or "") textsize1 = game:GetService("TextService"):GetTextSize(textsize1, onetext.TextSize, onetext.Font, Vector2.new(1000000, 1000000)) textsize2 = game:GetService("TextService"):GetTextSize(textsize2, onetext.TextSize, onetext.Font, Vector2.new(1000000, 1000000)) return textsize1.X > textsize2.X end) end local textlists = {} for i2,v2 in pairs(tableofmodules) do if first then text = (translations[v2["Text"]] ~= nil and translations[v2["Text"]] or v2["Text"])..(v2["ExtraText"]() ~= "" and ":"..v2["ExtraText"]() or "") first = false else text = text..'\n'..(translations[v2["Text"]] ~= nil and translations[v2["Text"]] or v2["Text"])..(v2["ExtraText"]() ~= "" and ":"..v2["ExtraText"]() or "") end table.insert(textlists, (translations[v2["Text"]] ~= nil and translations[v2["Text"]] or v2["Text"])..(v2["ExtraText"]() ~= "" and ":"..v2["ExtraText"]() or "")) end textwithoutthing = text onetext.Text = text onetext2.Text = text:gsub(":", " ") local newsize = game:GetService("TextService"):GetTextSize(text, onetext.TextSize, onetext.Font, Vector2.new(1000000, 1000000)) if text == "" then newsize = Vector2.new(0, 0) end onetext.Size = UDim2.new(0, 154, 0, newsize.Y) if TextGui.GetCustomChildren().Parent then if (TextGui.GetCustomChildren().Parent.Position.X.Offset + TextGui.GetCustomChildren().Parent.Size.X.Offset / 2) >= (cam.ViewportSize.X / 2) then onetext.TextXAlignment = Enum.TextXAlignment.Right onetext2.TextXAlignment = Enum.TextXAlignment.Right onetext2.Position = UDim2.new(0, 1, 0, 1) onething.Position = UDim2.new(1, -142, 0, 8) onetext.Position = UDim2.new(1, -154, 0, (onething.Visible and (textguirenderbkg["Enabled"] and 41 or 35) or 5)) onebackgroundsort.HorizontalAlignment = Enum.HorizontalAlignment.Right onebackground.Position = onetext.Position + UDim2.new(0, -60, 0, 2) else onetext.TextXAlignment = Enum.TextXAlignment.Left onetext2.TextXAlignment = Enum.TextXAlignment.Left onetext2.Position = UDim2.new(0, 5, 0, 1) onething.Position = UDim2.new(0, 2, 0, 8) onetext.Position = UDim2.new(0, 6, 0, (onething.Visible and (textguirenderbkg["Enabled"] and 41 or 35) or 5)) onebackgroundsort.HorizontalAlignment = Enum.HorizontalAlignment.Left onebackground.Position = onetext.Position + UDim2.new(0, -1, 0, 2) end end refreshbars(textlists) GuiLibrary["UpdateUI"]() end TextGui.GetCustomChildren().Parent:GetPropertyChangedSignal("Position"):connect(UpdateHud) onescale:GetPropertyChangedSignal("Scale"):connect(function() local childrenobj = TextGui.GetCustomChildren() local check = (childrenobj.Parent.Position.X.Offset + childrenobj.Parent.Size.X.Offset / 2) >= (cam.ViewportSize.X / 2) childrenobj.Position = UDim2.new((check and -(onescale.Scale - 1) or 0), (check and 0 or -6 * (onescale.Scale - 1)), 1, -6 * (onescale.Scale - 1)) UpdateHud() end) GuiLibrary["UpdateHudEvent"].Event:connect(UpdateHud) TextGui.CreateDropdown({ ["Name"] = "Sort", ["List"] = {"Alphabetical", "Length"}, ["Function"] = function(val) sortingmethod = val GuiLibrary["UpdateHudEvent"]:Fire() end }) TextGui.CreateToggle({ ["Name"] = "Shadow", ["Function"] = function(callback) onetext2.Visible = callback onething3.Visible = callback end, ["HoverText"] = "Renders shadowed text." }) local TextGuiUseCategoryColor = TextGui.CreateToggle({ ["Name"] = "Use Category Color", ["Function"] = function(callback) GuiLibrary["UpdateUI"]() end }) TextGui.CreateToggle({ ["Name"] = "Watermark", ["Function"] = function(callback) onething.Visible = callback UpdateHud() end, ["HoverText"] = "Renders a vape watermark" }) textguirenderbkg = TextGui.CreateToggle({ ["Name"] = "Render background", ["Function"] = function(callback) onebackground.Visible = callback UpdateHud() end }) TextGuiCircleObject = TextGui.CreateCircleWindow({ ["Name"] = "Blacklist", ["Type"] = "Blacklist", ["UpdateFunction"] = function() GuiLibrary["UpdateHudEvent"]:Fire() end }) textguiscaleslider = TextGui.CreateSlider({ ["Name"] = "Scale", ["Min"] = 1, ["Max"] = 50, ["Default"] = 10, ["Function"] = function(val) onescale.Scale = val / 10 end }) local healthColorToPosition = { [Vector3.new(Color3.fromRGB(255, 28, 0).r, Color3.fromRGB(255, 28, 0).g, Color3.fromRGB(255, 28, 0).b)] = 0.1; [Vector3.new(Color3.fromRGB(250, 235, 0).r, Color3.fromRGB(250, 235, 0).g, Color3.fromRGB(250, 235, 0).b)] = 0.5; [Vector3.new(Color3.fromRGB(27, 252, 107).r, Color3.fromRGB(27, 252, 107).g, Color3.fromRGB(27, 252, 107).b)] = 0.8; } local min = 0.1 local minColor = Color3.fromRGB(255, 28, 0) local max = 0.8 local maxColor = Color3.fromRGB(27, 252, 107) local function HealthbarColorTransferFunction(healthPercent) if healthPercent < min then return minColor elseif healthPercent > max then return maxColor end local numeratorSum = Vector3.new(0,0,0) local denominatorSum = 0 for colorSampleValue, samplePoint in pairs(healthColorToPosition) do local distance = healthPercent - samplePoint if distance == 0 then return Color3.new(colorSampleValue.x, colorSampleValue.y, colorSampleValue.z) else local wi = 1 / (distance*distance) numeratorSum = numeratorSum + wi * colorSampleValue denominatorSum = denominatorSum + wi end end local result = numeratorSum / denominatorSum return Color3.new(result.x, result.y, result.z) end local TargetInfo = GuiLibrary.CreateCustomWindow({ ["Name"] = "Target Info", ["Icon"] = "vape/assets/TargetInfoIcon1.png", ["IconSize"] = 16 }) local TargetInfoDisplayNames = TargetInfo.CreateToggle({ ["Name"] = "Use Display Name", ["Function"] = function() end, ["Default"] = true }) local targetinfobkg1 = Instance.new("Frame") targetinfobkg1.BackgroundColor3 = Color3.fromRGB(26, 25, 26) targetinfobkg1.BorderSizePixel = 0 targetinfobkg1.Size = UDim2.new(0, 220, 0, 72) targetinfobkg1.Position = UDim2.new(0, 0, 0, 0) targetinfobkg1.Parent = TargetInfo.GetCustomChildren() local targetinfobkg2 = targetinfobkg1:Clone() targetinfobkg2.ZIndex = 0 targetinfobkg2.Position = UDim2.new(0, 0, 0, -6) targetinfobkg2.Size = UDim2.new(0, 220, 0, 86) targetinfobkg2.Parent = targetinfobkg1 local targetinfobkg3 = Instance.new("Frame") targetinfobkg3.BackgroundColor3 = Color3.fromRGB(31, 30, 31) targetinfobkg3.Size = UDim2.new(0, 220, 0, 80) targetinfobkg3.Position = UDim2.new(0, 0, 0, -5) targetinfobkg3.Name = "MainInfo" targetinfobkg3.Parent = targetinfobkg1 local targetname = Instance.new("TextLabel") targetname.TextSize = 17 targetname.Font = Enum.Font.SourceSans targetname.TextColor3 = Color3.fromRGB(162, 162, 162) targetname.Position = UDim2.new(0, 72, 0, 7) targetname.TextStrokeTransparency = 0.75 targetname.BackgroundTransparency = 1 targetname.Size = UDim2.new(0, 80, 0, 16) targetname.TextScaled = true targetname.Text = "Target name" targetname.ZIndex = 2 targetname.TextXAlignment = Enum.TextXAlignment.Left targetname.TextYAlignment = Enum.TextYAlignment.Top targetname.Parent = targetinfobkg3 local targethealth = Instance.new("TextLabel") targethealth.TextColor3 = Color3.fromRGB(95, 94, 95) targethealth.Font = Enum.Font.SourceSans targethealth.Size = UDim2.new(0, 0, 0, 0) targethealth.TextSize = 17 targethealth.Position = UDim2.new(0, 210, 0, 6) targethealth.BackgroundTransparency = 1 targethealth.Text = '20'..' hp' targethealth.TextScaled = false targethealth.ZIndex = 2 targethealth.TextXAlignment = Enum.TextXAlignment.Right targethealth.TextYAlignment = Enum.TextYAlignment.Top targethealth.Parent = targetinfobkg3 local targethealthbkg = Instance.new("Frame") targethealthbkg.BackgroundColor3 = Color3.fromRGB(43, 42, 43) targethealthbkg.Size = UDim2.new(0, 138, 0, 4) targethealthbkg.Position = UDim2.new(0, 72, 0, 29) targethealthbkg.Parent = targetinfobkg3 local targethealthgreen = Instance.new("Frame") targethealthgreen.BackgroundColor3 = Color3.fromRGB(40, 137, 109) targethealthgreen.Size = UDim2.new(1, 0, 0, 4) targethealthgreen.ZIndex = 3 targethealthgreen.Parent = targethealthbkg local targetimage = Instance.new("ImageLabel") targetimage.Size = UDim2.new(0, 61, 0, 61) targetimage.BackgroundTransparency = 1 targetimage.Image = 'rbxthumb://type=AvatarHeadShot&id='..game:GetService("Players").LocalPlayer.UserId..'&w=420&h=420' targetimage.Position = UDim2.new(0, 5, 0, 10) targetimage.Parent = targetinfobkg3 local round1 = Instance.new("UICorner") round1.CornerRadius = UDim.new(0, 4) round1.Parent = targetinfobkg2 local round2 = Instance.new("UICorner") round2.CornerRadius = UDim.new(0, 4) round2.Parent = targetinfobkg3 local round3 = Instance.new("UICorner") round3.CornerRadius = UDim.new(0, 8) round3.Parent = targethealthbkg local round4 = Instance.new("UICorner") round4.CornerRadius = UDim.new(0, 8) round4.Parent = targethealthgreen local round5 = Instance.new("UICorner") round5.CornerRadius = UDim.new(0, 4) round5.Parent = targetimage local oldhealth = 100 local allowedtween = true TargetInfo.GetCustomChildren().Parent:GetPropertyChangedSignal("Size"):connect(function() if TargetInfo.GetCustomChildren().Parent.Size ~= UDim2.new(0, 220, 0, 0) then targetinfobkg3.Position = UDim2.new(0, 0, 0, -5) targetinfobkg2.BackgroundTransparency = 0 targetinfobkg1.BackgroundTransparency = 0 else targetinfobkg3.Position = UDim2.new(0, 0, 0, 40) targetinfobkg2.BackgroundTransparency = 1 targetinfobkg1.BackgroundTransparency = 1 end end) shared.VapeTargetInfo = { ["UpdateInfo"] = function(tab, targetsize) targetinfobkg3.Visible = (targetsize > 0) or (TargetInfo.GetCustomChildren().Parent.Size ~= UDim2.new(0, 220, 0, 0)) for i,v in pairs(tab) do local plr = game:GetService("Players"):FindFirstChild(i) targetimage.Image = 'rbxthumb://type=AvatarHeadShot&id='..v["UserId"]..'&w=420&h=420' targethealthgreen:TweenSize(UDim2.new(v["Health"] / v["MaxHealth"], 0, 0, 4), Enum.EasingDirection.InOut, Enum.EasingStyle.Quad, 0.05, true) targethealth.Text = (math.floor((v["Health"] / 5) * 10) / 10).." hp" targethealthgreen.BackgroundColor3 = HealthbarColorTransferFunction(v["Health"] / v["MaxHealth"]) targetname.Text = (TargetInfoDisplayNames["Enabled"] and plr and plr.DisplayName or i) end end, ["Object"] = TargetInfo } GUI.CreateCustomToggle({ ["Name"] = "Target Info", ["Icon"] = "vape/assets/TargetInfoIcon2.png", ["Function"] = function(callback) TargetInfo.SetVisible(callback) end, ["Priority"] = 1 }) local GeneralSettings = GUI.CreateDivider2("General Settings") local ModuleSettings = GUI.CreateDivider2("Module Settings") local GUISettings = GUI.CreateDivider2("GUI Settings") ModuleSettings.CreateToggle({ ["Name"] = "Teams by server", ["Function"] = function() end, }) ModuleSettings.CreateToggle({ ["Name"] = "Teams by color", ["Function"] = function() end, ["Default"] = true, ["HoverText"] = "Ignore players with the selected name color" }) local MiddleClickInput ModuleSettings.CreateToggle({ ["Name"] = "MiddleClick friends", ["Function"] = function(callback) if callback then MiddleClickInput = game:GetService("UserInputService").InputBegan:connect(function(input1) if input1.UserInputType == Enum.UserInputType.MouseButton3 then if mouse.Target.Parent:FindFirstChild("HumanoidRootPart") or mouse.Target.Parent:IsA("Accessory") and mouse.Target.Parent.Parent:FindFirstChild("HumanoidRootPart") then local user = (mouse.Target.Parent:IsA("Accessory") and mouse.Target.Parent.Parent.Name or mouse.Target.Parent.Name) if table.find(FriendsTextList["ObjectList"], user) == nil then table.insert(FriendsTextList["ObjectList"], user) FriendsTextList["RefreshValues"](FriendsTextList["ObjectList"]) else table.remove(FriendsTextList["ObjectList"], table.find(FriendsTextList["ObjectList"], user)) FriendsTextList["RefreshValues"](FriendsTextList["ObjectList"]) end end end end) else if MiddleClickInput then MiddleClickInput:Disconnect() end end end, ["HoverText"] = "Click middle mouse button to add the player you are hovering over as a friend" }) ModuleSettings.CreateToggle({ ["Name"] = "Lobby Check", ["Function"] = function() end, ["Default"] = true, ["HoverText"] = "Temporarily disables certain features in server lobbies." }) local blatantmode = GUI.CreateToggle({ ["Name"] = "Blatant mode", ["Function"] = function() end, ["HoverText"] = "Required for certain features." }) guicolorslider = GUI.CreateColorSlider("GUI Theme", function(val) GuiLibrary["Settings"]["GUIObject"]["Color"] = val GuiLibrary["UpdateUI"]() end) local tabsortorder = { ["CombatButton"] = 1, ["BlatantButton"] = 2, ["RenderButton"] = 3, ["UtilityButton"] = 4, ["WorldButton"] = 5, ["FriendsButton"] = 6, ["ProfilesButton"] = 7 } local tabcategorycolor = { ["CombatWindow"] = Color3.fromRGB(214, 27, 6), ["BlatantWindow"] = Color3.fromRGB(219, 21, 133), ["RenderWindow"] = Color3.fromRGB(135, 14, 165), ["UtilityWindow"] = Color3.fromRGB(27, 145, 68), ["WorldWindow"] = Color3.fromRGB(70, 73, 16) } GuiLibrary["UpdateUI"] = function() pcall(function() GuiLibrary["ObjectsThatCanBeSaved"]["GUIWindow"]["Object"].Logo1.Logo2.ImageColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) onething.ImageColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) onetext.TextColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) local newtext = "" local newfirst = false local colorforindex = {} for i2,v2 in pairs(textwithoutthing:split("\n")) do local rainbowcolor = GuiLibrary["Settings"]["GUIObject"]["Color"] + (GuiLibrary["ObjectsThatCanBeSaved"]["Gui ColorSliderColor"]["Api"]["RainbowValue"] and (-0.025 * i2) or 0) if rainbowcolor < 0 then rainbowcolor = 1 + rainbowcolor end local newcolor = Color3.fromHSV(rainbowcolor, 0.7, 0.9) local splittext = v2:split(":") splittext = #splittext > 1 and {splittext[1], " "..splittext[2]} or {v2, ""} if TextGuiUseCategoryColor["Enabled"] and GuiLibrary["ObjectsThatCanBeSaved"][splittext[1].."OptionsButton"] and tabcategorycolor[GuiLibrary["ObjectsThatCanBeSaved"][splittext[1].."OptionsButton"]["Object"].Parent.Parent.Name.."Window"] then newcolor = tabcategorycolor[GuiLibrary["ObjectsThatCanBeSaved"][splittext[1].."OptionsButton"]["Object"].Parent.Parent.Name.."Window"] end newtext = newtext..(newfirst and "\n" or " ")..'<font color="rgb('..tostring(math.floor(newcolor.R * 255))..","..tostring(math.floor(newcolor.G * 255))..","..tostring(math.floor(newcolor.B * 255))..')">'..splittext[1]..'</font><font color="rgb(170, 170, 170)">'..splittext[2]..'</font>' newfirst = true colorforindex[i2] = newcolor end if onebackground then for i3,v3 in pairs(onebackground:GetChildren()) do if v3:IsA("Frame") and colorforindex[v3.LayoutOrder] then v3.ColorFrame.BackgroundColor3 = colorforindex[v3.LayoutOrder] end end end onetext.Text = newtext local buttons = 0 for i,v in pairs(GuiLibrary["ObjectsThatCanBeSaved"]) do if v["Type"] == "TargetFrame" then if v["Object2"].Visible then v["Object"].TextButton.Frame.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end end if v["Type"] == "TargetButton" then if v["Api"]["Enabled"] then v["Object"].BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end end if v["Type"] == "CircleListFrame" then if v["Object2"].Visible then v["Object"].TextButton.Frame.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end end if (v["Type"] == "Button" or v["Type"] == "ButtonMain") and v["Api"]["Enabled"] then buttons = buttons + 1 local rainbowcolor = GuiLibrary["Settings"]["GUIObject"]["Color"] + (GuiLibrary["ObjectsThatCanBeSaved"]["Gui ColorSliderColor"]["Api"]["RainbowValue"] and (-0.025 * tabsortorder[i]) or 0) if rainbowcolor < 0 then rainbowcolor = 1 + rainbowcolor end local newcolor = Color3.fromHSV(rainbowcolor, 0.7, 0.9) v["Object"].ButtonText.TextColor3 = newcolor if v["Object"]:FindFirstChild("ButtonIcon") then v["Object"].ButtonIcon.ImageColor3 = newcolor end end if v["Type"] == "OptionsButton" then if v["Api"]["Enabled"] then v["Object"].BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end end if v["Type"] == "ExtrasButton" then if v["Api"]["Enabled"] then local rainbowcolor = GuiLibrary["Settings"]["GUIObject"]["Color"] + (GuiLibrary["ObjectsThatCanBeSaved"]["Gui ColorSliderColor"]["Api"]["RainbowValue"] and (-0.025 * buttons) or 0) if rainbowcolor < 0 then rainbowcolor = 1 + rainbowcolor end local newcolor = Color3.fromHSV(rainbowcolor, 0.7, 0.9) v["Object"].ImageColor3 = newcolor end end if (v["Type"] == "Toggle" or v["Type"] == "ToggleMain") and v["Api"]["Enabled"] then v["Object"].ToggleFrame1.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end if v["Type"] == "Slider" or v["Type"] == "SliderMain" then v["Object"].Slider.FillSlider.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) v["Object"].Slider.FillSlider.ButtonSlider.ImageColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end if v["Type"] == "TwoSlider" then v["Object"].Slider.FillSlider.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) v["Object"].Slider.ButtonSlider.ImageColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) v["Object"].Slider.ButtonSlider2.ImageColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) end end local rainbowcolor = GuiLibrary["Settings"]["GUIObject"]["Color"] + (GuiLibrary["ObjectsThatCanBeSaved"]["Gui ColorSliderColor"]["Api"]["RainbowValue"] and (-0.025 * buttons) or 0) if rainbowcolor < 0 then rainbowcolor = 1 + rainbowcolor end GuiLibrary["ObjectsThatCanBeSaved"]["GUIWindow"]["Object"].Children.Extras.MainButton.ImageColor3 = (GUI["GetVisibleIcons"]() > 0 and Color3.fromHSV(rainbowcolor, 0.7, 0.9) or Color3.fromRGB(199, 199, 199)) for i3, v3 in pairs(ProfilesTextList["ScrollingObject"].ScrollingFrame:GetChildren()) do -- pcall(function() if v3:IsA("TextButton") and v3.ItemText.Text == GuiLibrary["CurrentProfile"] then v3.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) v3.ImageButton.BackgroundColor3 = Color3.fromHSV(GuiLibrary["Settings"]["GUIObject"]["Color"], 0.7, 0.9) v3.ItemText.TextColor3 = Color3.new(1, 1, 1) v3.ItemText.TextStrokeTransparency = 0.75 end -- end) end end) end GeneralSettings.CreateToggle({ ["Name"] = "Auto-load module states", ["Function"] = function() end, ["HoverText"] = "Automatically enable saved module states upon loading profiles.\n(You can save module states by shift-clicking a profile button)" }) GUISettings.CreateToggle({ ["Name"] = "Blur Background", ["Function"] = function(callback) GuiLibrary["MainBlur"].Size = (callback and 25 or 0) end, ["Default"] = true, ["HoverText"] = "Blur the background of the GUI" }) local rescale = GUISettings.CreateToggle({ ["Name"] = "Rescale", ["Function"] = function(callback) GuiLibrary["MainRescale"].Scale = (callback and math.clamp(cam.ViewportSize.X / 1920, 0.5, 1) or 0.99) task.wait(0.01) GuiLibrary["MainRescale"].Scale = (callback and math.clamp(cam.ViewportSize.X / 1920, 0.5, 1) or 1) end, ["Default"] = true }) cam:GetPropertyChangedSignal("ViewportSize"):connect(function() if rescale["Enabled"] then GuiLibrary["MainRescale"].Scale = math.clamp(cam.ViewportSize.X / 1920, 0.5, 1) end end) GeneralSettings.CreateToggle({ ["Name"] = "Enable Multi-Keybinding", ["Function"] = function() end }) local welcomemsg = GUISettings.CreateToggle({ ["Name"] = "GUI bind indicator", ["Function"] = function() end, ["Default"] = true, ["HoverText"] = 'Displays a message indicating your GUI keybind upon injecting.\nI.E "Press RIGHTSHIFT to open GUI"' }) GUISettings.CreateToggle({ ["Name"] = "Show Tooltips", ["Function"] = function(callback) GuiLibrary["ToggleTooltips"] = callback end, ["Default"] = true, ["HoverText"] = "Toggles visibility of these" }) GeneralSettings.CreateToggle({ ["Name"] = "Discord integration", ["Function"] = function() end }) local ToggleNotifications = {["Object"] = nil} local Notifications = {} Notifications = GeneralSettings.CreateToggle({ ["Name"] = "Notifications", ["Function"] = function(callback) GuiLibrary["Notifications"] = callback end, ["Default"] = true, ["HoverText"] = "Shows notifications" }) ToggleNotifications = GUISettings.CreateToggle({ ["Name"] = "Toggle Alert", ["Function"] = function(callback) GuiLibrary["ToggleNotifications"] = callback end, ["Default"] = true, ["HoverText"] = "Notifies you if a module is enabled/disabled." }) ToggleNotifications["Object"].BackgroundTransparency = 0 ToggleNotifications["Object"].BorderSizePixel = 0 ToggleNotifications["Object"].BackgroundColor3 = Color3.fromRGB(20, 20, 20) GUISettings.CreateSlider({ ["Name"] = "Rainbow Speed", ["Function"] = function(val) GuiLibrary["RainbowSpeed"] = val / 10 end, ["Min"] = 1, ["Max"] = 100, ["Default"] = 10 }) local GUIbind = GUI.CreateGUIBind() local teleportfunc = game:GetService("Players").LocalPlayer.OnTeleport:Connect(function(State) if State == Enum.TeleportState.Started then local teleportstr = 'shared.VapeSwitchServers = true if shared.VapeDeveloper then loadstring(readfile("vape/NewMainScript.lua"))() else loadstring(game:HttpGet("https://raw.githubusercontent.com/7GrandDadPGN/VapeV4ForRoblox/main/NewMainScript.lua", true))() end' if shared.VapeDeveloper then teleportstr = 'shared.VapeDeveloper = true '..teleportstr end if shared.VapePrivate then teleportstr = 'shared.VapePrivate = true '..teleportstr end GuiLibrary["SaveSettings"]() queueteleport(teleportstr) end end) GuiLibrary["SelfDestruct"] = function() spawn(function() coroutine.close(selfdestructsave) end) GuiLibrary["SaveSettings"]() game:GetService("UserInputService").OverrideMouseIconBehavior = Enum.OverrideMouseIconBehavior.None for i,v in pairs(GuiLibrary["ObjectsThatCanBeSaved"]) do if (v["Type"] == "Button" or v["Type"] == "OptionsButton") and v["Api"]["Enabled"] then v["Api"]["ToggleButton"](false) end end GuiLibrary["SelfDestructEvent"]:Fire() shared.VapeExecuted = nil shared.VapePrivate = nil shared.VapeSwitchServers = nil shared.GuiLibrary = nil shared.VapeIndependent = nil shared.VapeManualLoad = nil shared.CustomSaveVape = nil GuiLibrary["KeyInputHandler"]:Disconnect() GuiLibrary["KeyInputHandler2"]:Disconnect() if MiddleClickInput then MiddleClickInput:Disconnect() end teleportfunc:Disconnect() GuiLibrary["MainGui"]:Remove() GuiLibrary["MainBlur"]:Remove() end ModuleSettings.CreateButton2({ ["Name"] = "RESET CURRENT PROFILE", ["Function"] = function() local vapeprivate = shared.VapePrivate GuiLibrary["SelfDestruct"]() delfile(customdir.."Profiles/"..(GuiLibrary["CurrentProfile"] == "default" and "" or GuiLibrary["CurrentProfile"])..game.PlaceId..".vapeprofile.txt") shared.VapeSwitchServers = true shared.VapeOpenGui = true shared.VapePrivate = vapeprivate loadstring(GetURL("NewMainScript.lua"))() end }) GUISettings.CreateButton2({ ["Name"] = "RESET GUI POSITIONS", ["Function"] = function() for i,v in pairs(GuiLibrary["ObjectsThatCanBeSaved"]) do if (v["Type"] == "Window" or v["Type"] == "CustomWindow") and GuiLibrary["findObjectInTable"](GuiLibrary["ObjectsThatCanBeSaved"], i) then v["Object"].Position = (i == "GUIWindow" and UDim2.new(0, 6, 0, 6) or UDim2.new(0, 223, 0, 6)) end end end }) GUISettings.CreateButton2({ ["Name"] = "SORT GUI", ["Function"] = function() local sorttable = {} local movedown = false local sortordertable = { ["GUIWindow"] = 1, ["CombatWindow"] = 2, ["BlatantWindow"] = 3, ["RenderWindow"] = 4, ["UtilityWindow"] = 5, ["WorldWindow"] = 6, ["FriendsWindow"] = 7, ["ProfilesWindow"] = 8, ["Text GUICustomWindow"] = 9, ["TargetInfoCustomWindow"] = 10, ["RadarCustomWindow"] = 11, } local storedpos = {} local num = 6 for i,v in pairs(GuiLibrary["ObjectsThatCanBeSaved"]) do if v["Type"] == "Window" and GuiLibrary["findObjectInTable"](GuiLibrary["ObjectsThatCanBeSaved"], i) and v["Object"].Visible then local sortordernum = (sortordertable[i] or #sorttable) sorttable[sortordernum] = v["Object"] end end for i2,v2 in pairs(sorttable) do if num > 1697 then movedown = true num = 6 end v2.Position = UDim2.new(0, num, 0, (movedown and (storedpos[num] and (storedpos[num] + 9) or 400) or 39)) if not storedpos[num] then storedpos[num] = v2.AbsoluteSize.Y if v2.Name == "MainWindow" then storedpos[num] = 400 end end num = num + 223 end end }) GeneralSettings.CreateButton2({ ["Name"] = "UNINJECT", ["Function"] = GuiLibrary["SelfDestruct"] }) if shared.VapeIndependent then spawn(function() repeat task.wait() until shared.VapeManualLoad GuiLibrary["LoadSettings"]() if #ProfilesTextList["ObjectList"] == 0 then table.insert(ProfilesTextList["ObjectList"], "default") ProfilesTextList["RefreshValues"](ProfilesTextList["ObjectList"]) end GUIbind["Reload"]() GuiLibrary["UpdateUI"]() UpdateHud() if not shared.VapeSwitchServers then if blatantmode["Enabled"] then pcall(function() local frame = GuiLibrary["CreateNotification"]("Blatant Enabled", "Vape is now in Blatant Mode.", 5.5, "assets/WarningNotification.png") frame.Frame.Frame.ImageColor3 = Color3.fromRGB(236, 129, 44) end) end GuiLibrary["LoadedAnimation"](welcomemsg["Enabled"]) else shared.VapeSwitchServers = nil end if shared.VapeOpenGui then GuiLibrary["MainGui"].ScaledGui.ClickGui.Visible = true GuiLibrary["MainBlur"].Enabled = true shared.VapeOpenGui = nil end coroutine.resume(selfdestructsave) end) return GuiLibrary else loadstring(GetURL("AnyGame.vape"))() if betterisfile("vape/CustomModules/"..game.PlaceId..".vape") then loadstring(readfile("vape/CustomModules/"..game.PlaceId..".vape"))() else local publicrepo = checkpublicrepo(game.PlaceId) if publicrepo then loadstring(publicrepo)() end end if shared.VapePrivate then if pcall(function() readfile("vapeprivate/CustomModules/"..game.PlaceId..".vape") end) then loadstring(readfile("vapeprivate/CustomModules/"..game.PlaceId..".vape"))() end end GuiLibrary["LoadSettings"]() if #ProfilesTextList["ObjectList"] == 0 then table.insert(ProfilesTextList["ObjectList"], "default") ProfilesTextList["RefreshValues"](ProfilesTextList["ObjectList"]) end GUIbind["Reload"]() GuiLibrary["UpdateUI"]() UpdateHud() if not shared.VapeSwitchServers then if blatantmode["Enabled"] then pcall(function() local frame = GuiLibrary["CreateNotification"]("Blatant Enabled", "Vape is now in Blatant Mode.", 5.5, "assets/WarningNotification.png") frame.Frame.Frame.ImageColor3 = Color3.fromRGB(236, 129, 44) end) end GuiLibrary["LoadedAnimation"](welcomemsg["Enabled"]) else shared.VapeSwitchServers = nil end if shared.VapeOpenGui then GuiLibrary["MainGui"].ScaledGui.ClickGui.Visible = true GuiLibrary["MainBlur"].Enabled = true shared.VapeOpenGui = nil end coroutine.resume(selfdestructsave) end
local awful = require('awful') local gears = require('gears') local wibox = require('wibox') local beautiful = require('beautiful') local dpi = beautiful.xresources.apply_dpi local clickable_container = require('widget.clickable-container') local icons = require('theme.icons') local spawn = require('awful.spawn') local osd_header = wibox.widget { text = 'Brightness', font = 'Hack Nerd Bold 12', align = 'left', valign = 'center', widget = wibox.widget.textbox } local osd_value = wibox.widget { text = '0%', font = 'Hack Nerd Bold 12', align = 'center', valign = 'center', widget = wibox.widget.textbox } local slider_osd = wibox.widget { nil, { id = 'bri_osd_slider', bar_shape = gears.shape.rounded_rect, bar_height = dpi(24), bar_color = '#ffffff20', bar_active_color = '#f2f2f2EE', handle_color = '#ffffff', handle_shape = gears.shape.circle, handle_width = dpi(24), handle_border_color = '#00000012', handle_border_width = dpi(1), maximum = 100, widget = wibox.widget.slider }, nil, expand = 'none', layout = wibox.layout.align.vertical } local bri_osd_slider = slider_osd.bri_osd_slider bri_osd_slider:connect_signal( 'property::value', function() local brightness_level = bri_osd_slider:get_value() spawn('light -S ' .. math.max(brightness_level, 5), false) -- Update textbox widget text osd_value.text = brightness_level .. '%' -- Update the brightness slider if values here change awesome.emit_signal('widget::brightness:update', brightness_level) if awful.screen.focused().show_bri_osd then awesome.emit_signal( 'module::brightness_osd:show', true ) end end ) bri_osd_slider:connect_signal( 'button::press', function() awful.screen.focused().show_bri_osd = true end ) bri_osd_slider:connect_signal( 'mouse::enter', function() awful.screen.focused().show_bri_osd = true end ) -- The emit will come from brightness slider awesome.connect_signal( 'module::brightness_osd', function(brightness) bri_osd_slider:set_value(brightness) end ) local icon = wibox.widget { { image = icons.brightness, resize = true, widget = wibox.widget.imagebox }, forced_height = dpi(150), top = dpi(12), bottom = dpi(12), widget = wibox.container.margin } local osd_height = dpi(250) local osd_width = dpi(250) local osd_margin = dpi(10) screen.connect_signal( 'request::desktop_decoration', function(s) local s = s or {} s.show_bri_osd = false s.brightness_osd_overlay = awful.popup { widget = { -- Removing this block will cause an error... }, ontop = true, visible = false, type = 'notification', screen = s, height = osd_height, width = osd_width, maximum_height = osd_height, maximum_width = osd_width, offset = dpi(5), shape = gears.shape.rectangle, bg = beautiful.transparent, preferred_anchors = 'middle', preferred_positions = {'left', 'right', 'top', 'bottom'} } s.brightness_osd_overlay : setup { { { layout = wibox.layout.fixed.vertical, { { layout = wibox.layout.align.horizontal, expand = 'none', nil, icon, nil }, { layout = wibox.layout.fixed.vertical, spacing = dpi(5), { layout = wibox.layout.align.horizontal, expand = 'none', osd_header, nil, osd_value }, slider_osd }, spacing = dpi(10), layout = wibox.layout.fixed.vertical }, }, left = dpi(24), right = dpi(24), widget = wibox.container.margin }, bg = beautiful.background, shape = gears.shape.rounded_rect, widget = wibox.container.background() } -- Reset timer on mouse hover s.brightness_osd_overlay:connect_signal( 'mouse::enter', function() s.show_bri_osd = true awesome.emit_signal('module::brightness_osd:rerun') end ) end ) local hide_osd = gears.timer { timeout = 2, autostart = true, callback = function() local focused = awful.screen.focused() focused.brightness_osd_overlay.visible = false focused.show_bri_osd = false end } awesome.connect_signal( 'module::brightness_osd:rerun', function() if hide_osd.started then hide_osd:again() else hide_osd:start() end end ) local placement_placer = function() local focused = awful.screen.focused() local brightness_osd = focused.brightness_osd_overlay awful.placement.bottom( brightness_osd, { margins = { left = 0, right = 0, top = 0, bottom = osd_margin } } ) end awesome.connect_signal( 'module::brightness_osd:show', function(bool) placement_placer() awful.screen.focused().brightness_osd_overlay.visible = bool if bool then awesome.emit_signal('module::brightness_osd:rerun') awesome.emit_signal( 'module::volume_osd:show', false ) else if hide_osd.started then hide_osd:stop() end end end )
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] local categoryData = { keyboardData = { name = GetString(SI_ACTIVITY_FINDER_CATEGORY_HOME_SHOW), normalIcon = "EsoUI/Art/LFG/LFG_indexIcon_homeShow_up.dds", pressedIcon = "EsoUI/Art/LFG/LFG_indexIcon_homeShow_down.dds", mouseoverIcon = "EsoUI/Art/LFG/LFG_indexIcon_homeShow_over.dds", }, gamepadData = { name = GetString(SI_ACTIVITY_FINDER_CATEGORY_HOME_SHOW), menuIcon = "EsoUI/Art/LFG/Gamepad/LFG_menuIcon_homeShow.dds", sceneName = "gamepadHomeShow", tooltipDescription = GetString(SI_GAMEPAD_ACTIVITY_FINDER_TOOLTIP_HOME_SHOW), } } local HomeShow_Manager = ZO_ActivityFinderTemplate_Manager:Subclass() function HomeShow_Manager:New(...) return ZO_ActivityFinderTemplate_Manager.New(self, ...) end function HomeShow_Manager:Initialize() local filterModeData = ZO_ActivityFinderFilterModeData:New(LFG_ACTIVITY_HOME_SHOW) ZO_ActivityFinderTemplate_Manager.Initialize(self, "ZO_HomeShow", categoryData, filterModeData) HOME_SHOW_KEYBOARD = self:GetKeyboardObject() HOME_SHOW_GAMEPAD = self:GetGamepadObject() GAMEPAD_HOME_SHOW_SCENE = HOME_SHOW_GAMEPAD:GetScene() end function HomeShow_Manager:GetCategoryData() return categoryData end HOME_SHOW_FINDER_MANAGER = HomeShow_Manager:New()
--- === hs.doc === --- --- Create documentation objects for interactive help within Hammerspoon --- --- The documentation object created is a table with tostring metamethods allowing access to a specific functions documentation by appending the path to the method or function to the object created. --- --- From the Hammerspoon console: --- --- doc = require("hs.doc") --- doc.hs.application --- --- Results in: --- Manipulate running applications --- --- [submodules] --- hs.application.watcher --- --- [subitems] --- hs.application:activate([allWindows]) -> bool --- hs.application:allWindows() -> window[] --- ... --- hs.application:visibleWindows() -> win[] --- --- By default, the internal core documentation and portions of the Lua 5.3 manual, located at http://www.lua.org/manual/5.3/manual.html, are already registered for inclusion within this documentation object, but you can register additional documentation from 3rd party modules with `hs.registerJSONFile(...)`. local module = {} module.spoonsupport = require("hs.doc.spoonsupport") -- private variables and methods ----------------------------------------- local json = require("hs.json") local fs = require("hs.fs") local fnutils = require("hs.fnutils") local inspect = require("hs.inspect") local watchable = require("hs.watchable") local sortFunction = function(m,n) -- sort function so lua manual toc sorts correctly if m:match("^_%d") and n:match("^_%d") then local a, b = fnutils.split(m:match("^_([^%s]+)"), "_"), fnutils.split(n:match("^_([^%s]+)"), "_") if tonumber(a[1]) ~= tonumber(b[1]) then return tonumber(a[1]) < tonumber(b[1]) elseif a[2] == nil and b[2] == nil then return false elseif a[2] == nil then return true elseif b[2] == nil then return false elseif tonumber(a[2]) ~= tonumber(b[2]) then return tonumber(a[2]) < tonumber(b[2]) elseif a[3] == nil and b[3] == nil then return false elseif a[3] == nil then return true elseif b[3] == nil then return false else return tonumber(a[3]) < tonumber(b[3]) end else return m < n end end local fixLinks = function(text) -- replace internal link references which work well in html and dash with something -- more appropriate to inline textual help local content, count = text:gsub("%[([^%]\r\n]+)%]%(#([^%)\r\n]+)%)", "`%1`") return content end local coredocs = {} local rawdocs = { spoon = {} } local docMT docMT = { __index = function(self, key) local path, pos = rawget(self, "__path"), rawget(self, "__pos") local result if not path then result = rawdocs[key] and setmetatable({ __path = key, __pos = rawdocs[key] }, docMT) or nil else result = pos[key] and setmetatable({ __path = path .. "." .. key, __pos = pos[key] }, docMT) or nil end return result end, __tostring = function(self) local result = "" local path, pos = rawget(self, "__path"), rawget(self, "__pos") if not pos then result = "[modules]\n" for k,v in fnutils.sortByKeys(rawdocs, function(a,b) return a:lower() < b:lower() end) do result = result .. k .. "\n" end elseif path == "spoon" then result = "[spoons]\n" for k,v in fnutils.sortByKeys(pos, function(a,b) return a:lower() < b:lower() end) do result = result .. k .. "\n" end elseif pos.__ and not pos.__.json.items then result = pos.__.json.type .. ": " .. (pos.__.json.signature or pos.__.json.def) .. "\n\n" .. pos.__.json.doc .. "\n" else if pos.__ then result = pos.__.json.doc .. "\n\n" else result = "** DOCUMENTATION MISSING **\n\n" end local submodules, items = "", "" for k, v in fnutils.sortByKeys(pos, sortFunction) do if k ~= "__" then -- spoons placeholder will not have __ and older docs (lua) will not have a type for sections (modules) if not v.__ or not v.__.json.type or v.__.json.type == "Module" then submodules = submodules .. k .. "\n" else items = items .. (v.__.json.signature or v.__.json.def) .. "\n" end end end result = result .. "[submodules]\n" .. submodules .. "\n" result = result .. "[subitems]\n" .. items .. "\n" end return fixLinks(result) end, __pairs = function(self) local path, pos = rawget(self, "__path"), rawget(self, "__pos") local source = {} if not pos then source = rawdocs else source = pos end return function(_, k) local v k, v = next(source, k) if k == "__" then k, v = next(source, k) end return k, v end, self, nil end } local helpHolder = setmetatable({}, docMT) -- Public interface ------------------------------------------------------ local buildHoldingTable = function(self) local holder = {} for k,v in pairs(coredocs) do if v.spoon == self.__spoon then for i, v2 in ipairs(v.json) do if not (self.__ignore and (v2.name:match("^" .. self.__ignore .. "$") or v2.name:match("^" .. self.__ignore .. "[%.:]"))) then table.insert(holder, v2) end end end end table.sort(holder, function(a,b) return sortFunction(a.name:lower(), b.name:lower()) end) return holder end local jsonMT = { __index = function(self, key) local holder = buildHoldingTable(self) return holder[key] end, __pairs = function(self) local holder = buildHoldingTable(self) return function(_, k) local v k, v = next(holder, k) return k, v end, self, nil end, __len = function(self) local holder = buildHoldingTable(self) return #holder end, } local changeCount = watchable.new("hs.doc") changeCount.changeCount = 0 module._jsonForSpoons = setmetatable({ __spoon = true, __ignore = false }, jsonMT) module._jsonForNonSpoons = setmetatable({ __spoon = false, __ignore = false }, jsonMT) module._jsonForModules = setmetatable({ __spoon = false, __ignore = "lua" }, jsonMT) --module._coredocs = coredocs --module._help = helpHolder --module._rawdocs = rawdocs --- hs.doc.validateJSONFile(jsonfile) -> status, message|table --- Function --- Validate a JSON file potential inclusion in the Hammerspoon internal documentation. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was validated or not. --- * message|table - If the file did not contain valid JSON data, then a message indicating the error is returned; otherwise the parsed JSON data is returned as a table. module.validateJSONFile = function(jsonFile) local f = io.open(jsonFile) if not f then return false, "Unable to open '"..jsonFile.."'" else local content = f:read("*a") f:close() return pcall(json.decode, content) end end --- hs.doc.registerJSONFile(jsonfile) -> status[, message] --- Function --- Register a JSON file for inclusion when Hammerspoon generates internal documentation. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was registered or not. If the file was not registered, then a message indicating the error is also returned. module.registerJSONFile = function(docFile, isSpoon) if type(docFile) ~= "string" then -- most likely this was called with the result of the locateJSONFile function, -- and the locate function was unable to find the JSON file... return false, "Provided path is not a string." end docFile = fs.pathToAbsolute(docFile) local status, message = module.validateJSONFile(docFile) if status then if coredocs[docFile] then return false, "File '"..docFile.."' already registered" end coredocs[docFile] = { spoon = (isSpoon and type(isSpoon) == "boolean") and true or false, json = message } for i, entry in ipairs(message) do local current = coredocs[docFile].spoon and rawdocs.spoon or rawdocs for s in string.gmatch(entry.name, "[%w_]+") do current[s] = current[s] or {} current = current[s] end if current.__ then print("** hs.doc - duplicate module entry at " .. entry.name .. " -> " .. inspect(entry, { depth = 1 })) else current.__ = { json = entry, file = docFile } end for i2, subitem in ipairs(entry.items or {}) do local itemDocName = subitem.name:gsub("[^%w_]", "") current[itemDocName] = current[itemDocName] or {} if current[itemDocName].__ then print("** hs.doc - duplicate item entry at " .. entry.name .. "." .. subitem.name .. " -> " .. inspect(subitem, { depth = 1 })) else current[itemDocName].__ = { json = subitem, file = docFile } end end end changeCount.changeCount = changeCount.changeCount + 1 return status end return status, message end --- hs.doc.unregisterJSONFile(jsonfile, [isSpoon]) -> status[, message] --- Function --- Remove a JSON file from the list of registered files. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- * isSpoon - an optional boolean, default false, specifying that the documentation should be added to the `spoons` sub heading in the documentation hierarchy. --- --- Returns: --- * status - Boolean flag indicating if the file was unregistered or not. If the file was not unregistered, then a message indicating the error is also returned. module.unregisterJSONFile = function(docFile) if coredocs[docFile] then coredocs[docFile] = nil local purgeFromInside purgeFromInside = function(where) for k,v in pairs(where) do if k ~= "__" and type(v) == "table" then if purgeFromInside(v) then where[k] = nil end end end if where.__ and where.__.file == docFile then return not next(where, "__") elseif not where.__ then return not next(where) else return false end end purgeFromInside(rawdocs) changeCount.changeCount = changeCount.changeCount + 1 return true end return false, "File '"..docFile.."' was not registered" end --- hs.doc.registeredFiles() -> table --- Function --- Returns the list of registered JSON files. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the list of registered JSON files --- --- Notes: --- * The table returned by this function has a metatable including a __tostring method which allows you to see the list of registered files by simply typing `hs.doc.registeredFiles()` in the Hammerspoon Console. --- --- * By default, the internal core documentation and portions of the Lua 5.3 manual, located at http://www.lua.org/manual/5.3/manual.html, are already registered for inclusion within this documentation object. --- --- * You can unregister these defaults if you wish to start with a clean slate with the following commands: --- * `hs.doc.unregisterJSONFile(hs.docstrings_json_file)` -- to unregister the Hammerspoon API docs --- * `hs.doc.unregisterJSONFile((hs.docstrings_json_file:gsub("/docs.json$","/extensions/hs/doc/lua.json")))` -- to unregister the Lua 5.3 Documentation. module.registeredFiles = function(docFile) local registeredJSONFiles = setmetatable({}, { __tostring = function(self) local result = "" for i,v in fnutils.sortByKeyValues(self) do result = result..v.."\n" end return result end, }) for k,v in pairs(coredocs) do table.insert(registeredJSONFiles, k) end return registeredJSONFiles end --- hs.doc.locateJSONFile(module) -> path | false, message --- Function --- Locates the JSON file corresponding to the specified module by searching package.path and package.cpath. --- --- Parameters: --- * module - the name of the module to locate a JSON file for --- --- Returns: --- * the path to the JSON file, or `false, error` if unable to locate a corresponding JSON file. --- --- Notes: --- * The JSON should be named 'docs.json' and located in the same directory as the `lua` or `so` file which is used when the module is loaded via `require`. module.locateJSONFile = function(moduleName) local asLua = package.searchpath(moduleName, package.path) local asC = package.searchpath(moduleName, package.cpath) if asLua then local pathPart = asLua:match("^(.*/).+%.lua$") if pathPart then if fs.attributes(pathPart.."docs.json") then return pathPart.."docs.json" else return false, "No JSON file for "..moduleName.." found" end else return false, "Unable to parse package.path for "..moduleName end elseif asC then local pathPart = asC:match("^(.*/).+%.so$") if pathPart then if fs.attributes(pathPart.."docs.json") then return pathPart.."docs.json" else return false, "No JSON file for "..moduleName.." found" end else return false, "Unable to parse package.cpath for "..moduleName end else return false, "Unable to locate module path for "..moduleName end end --- hs.doc.help(identifier) --- Function --- Prints the documentation for some part of Hammerspoon's API and Lua 5.3. This function has also been aliased as `hs.help` and `help` as a shorthand for use within the Hammerspoon console. --- --- Parameters: --- * identifier - A string containing the signature of some part of Hammerspoon's API (e.g. `"hs.reload"`) --- --- Returns: --- * None --- --- Notes: --- * This function is mainly for runtime API help while using Hammerspoon's Console --- * This function only returns information about the core Hammerspoon API and Lua 5.3. If you register additional files from 3rd party modules, or deregister the initial files for creating your own `hs.doc` objects, it will not affect the results used by this function. --- --- * You can also access the results of this function by the following methods from the console: --- * help("identifier") -- quotes are required, e.g. `help("hs.reload")` --- * help.identifier.path -- no quotes are required, e.g. `help.hs.reload` --- --- * Lua information can be accessed by using the `lua` prefix, rather than `hs`. --- * the identifier `lua._man` provides the table of contents for the Lua 5.3 manual. You can pull up a specific section of the lua manual by including the chapter (and subsection) like this: `lua._man._3_4_8`. --- * the identifier `lua._C` will provide information specifically about the Lua C API for use when developing modules which require external libraries. function module.help(identifier) local result = helpHolder for word in string.gmatch((identifier or ""), '([^.]+)') do result = result[word] end print(result) end -- Return Module Object -------------------------------------------------- module.registerJSONFile(hs.docstrings_json_file) module.registerJSONFile((hs.docstrings_json_file:gsub("/docs.json$","/extensions/hs/doc/lua.json"))) module.spoonsupport.updateDocsFiles() local paths, details = module.spoonsupport.findSpoons() for k,v in pairs(details) do if v.hasDocs then module.registerJSONFile(v.docPath, true) end end -- don't load submodules until needed -- makes it easier to troubleshoot when testing -- upgrades since hs.doc is loaded by _coresetup, but the others don't have to be, and -- hsdocs especially uses a lot of other modules we might be testing and dont' want loaded -- until personal path overrides have been set local submodules = { markdown = "hs.doc.markdown", hsdocs = "hs.doc.hsdocs", builder = "hs.doc.builder", } return setmetatable(module, { __call = function(_, ...) return module.help(...) end, __tostring = function(obj) return tostring(helpHolder) end, __index = function(self, key) if submodules[key] then self[key] = require(submodules[key]) end return helpHolder[key] or rawget(self, key) end, })
--@name Simple Custom Prop --@author Name --@server local fidelity = 16 local x, y, z = 15, 10, 5 local convexes = { -- cube { Vector(0, 0, 0), Vector(x, 0, 0), Vector(x, y, 0), Vector(0, y, 0), Vector(0, 0, z), Vector(x, 0, z), Vector(x, y, z), Vector(0, y, z), }, -- cylinder { -- cone Vector(x/2, y/2, z*3) }, } -- cylinder base for i = 1, fidelity do local t = math.pi*2 / fidelity * i local cos = x/2 + math.cos(t) * x/4 local sin = y/2 + math.sin(t) * y/4 table.insert(convexes[2], Vector(cos, sin, z)) table.insert(convexes[2], Vector(cos, sin, z*2)) end local ent = prop.createCustom(chip():getPos() + chip():getUp()*45, Angle(), convexes, true)
-- https://github.com/rmagatti/auto-session vim.o.sessionoptions = "blank,buffers,curdir,folds,help,tabpages,winsize,winpos,terminal" require("auto-session").setup({ log_level = "info", auto_session_enable_last_session = false, auto_session_root_dir = vim.fn.stdpath("data") .. "/sessions/", auto_session_enabled = true, auto_save_enabled = nil, auto_restore_enabled = false, auto_session_suppress_dirs = nil }) vim.cmd([[ autocmd VimLeavePre * silent! :SaveSession ]])
--@import see.io.Peripheral function AbstractPeripheral:init(location) if not Peripheral.isPresent(location) then throw(InvalidArgumentException:new(1, "see.base.String: location", "invalid location")) end self.location = location end
-- STYLES local styles = data.raw['gui-style'].default styles['green_button'] = { type = 'button_style', parent = 'button', default_graphical_set = { base = {position = {68, 17}, corner_size = 8}, shadow = default_dirt }, hovered_graphical_set = { base = {position = {102, 17}, corner_size = 8}, shadow = default_dirt, glow = default_glow(green_arrow_button_glow_color, 0.5) }, clicked_graphical_set = { base = {position = {119, 17}, corner_size = 8}, shadow = default_dirt }, disabled_graphical_set = { base = {position = {85, 17}, corner_size = 8}, shadow = default_dirt } } styles['green_icon_button'] = { type = 'button_style', parent = 'green_button', padding = 3, size = 28 } styles['titlebar_flow'] = { type = 'horizontal_flow_style', direction = 'horizontal', horizontally_stretchable = 'on', vertical_align = 'center' } styles['invisible_horizontal_filler'] = { type = 'empty_widget_style', horizontally_stretchable = 'on' } styles['invisible_vertical_filler'] = { type = 'empty_widget_style', vertically_stretchable = 'on' } styles['entity_dialog_page_frame'] = { type = 'frame_style', parent = 'window_content_frame', minimal_width = 250, vertically_stretchable = 'on', horizontally_stretchable = 'on', left_padding = 8, top_padding = 6, right_padding = 6, bottom_padding = 6 } styles['camera_frame'] = { type = 'frame_style', parent = 'window_content_frame', padding = 0 } styles['stretchable_button'] = { type = 'button_style', parent = 'button', horizontally_stretchable = 'on' } styles['dropdown_button'].disabled_font_color = styles['button'].disabled_font_color styles['dropdown_button'].disabled_graphical_set = styles['button'].disabled_graphical_set styles['list_box_in_tabbed_pane'] = { type = 'list_box_style', parent = 'list_box', scroll_pane_style = { type = 'scroll_pane_style', parent = 'list_box_scroll_pane', vertical_scroll_policy = 'auto-and-reserve-space', graphical_set = { base = { position = {85, 0}, corner_size = 8, center = {position = {42, 8}, size = 1}, draw_type = 'outer' }, shadow = default_inner_shadow } } } styles['vertically_centered_flow'] = { type='horizontal_flow_style', vertical_align = 'center' } styles['invalid_short_number_textfield'] = { type = 'textbox_style', parent = 'short_number_textfield', default_background = { base = {position = {248,0}, corner_size=8, tint=warning_red_color}, shadow = textbox_dirt }, active_background = { base = {position={265,0}, corner_size=8, tint=warning_red_color}, shadow = textbox_dirt }, disabled_background = { base = {position = {282,0}, corner_size=8, tint=warning_red_color}, shadow = textbox_dirt } } styles['close_button_active'] = { type = 'button_style', parent = 'close_button', default_graphical_set = { base = {position = {272, 169}, corner_size = 8}, shadow = {position = {440, 24}, corner_size = 8, draw_type = 'outer'} }, hovered_graphical_set = { base = {position={369,17}, corner_size=8}, shadow = {position = {440, 24}, corner_size = 8, draw_type = 'outer'} }, clicked_graphical_set = { base = {position={352,17}, corner_size=8}, shadow = {position = {440, 24}, corner_size = 8, draw_type = 'outer'} } } styles['virtual_slot_table_scroll_pane'] = { type = 'scroll_pane_style', parent = 'train_schedule_scroll_pane', background_graphical_set = { base = { position = {282,17}, corner_size = 8, overall_tiling_vertical_size = 32, overall_tiling_horizontal_size = 32, overall_tiling_horizontal_padding = 4, overall_tiling_horizontal_spacing = 8, overall_tiling_vertical_spacing = 8, overall_tiling_vertical_padding = 4 } } } -- ---------------------------------------------------------------------------------------------------- -- SPRITES data:extend{ { type = 'sprite', name = 'im-logo', filename = '__InfinityMode__/graphics/gui/crafting-group.png', size = 128, flags = {'icon'} }, { type = 'sprite', name = 'im-info-black-inline', filename = '__InfinityMode__/graphics/gui/info-black-inline.png', size = {16,40}, flags = {'icon'} }, { type = 'sprite', name = 'im_pin', filename = '__InfinityMode__/graphics/gui/pin.png', size = 32, flags = {'icon'} }, { type = 'sprite', name = 'im_pin_black', filename = '__InfinityMode__/graphics/gui/pin-black.png', size = 32, flags = {'icon'} }, { type = 'sprite', name = 'im_no_default_on', filename = '__InfinityMode__/graphics/gui/needs-restart-white.png', size = {16,40}, scale = 0.5, flags = {'icon'}, tint = green_arrow_button_glow_color }, { type = 'sprite', name = 'im_no_default_off', filename = '__InfinityMode__/graphics/gui/needs-restart-white.png', size = {16,40}, scale = 0.5, flags = {'icon'}, tint = red_arrow_button_glow_color } }
--- @classmod core.physics.CollisionShape --- Defines the shape of a @{core.physics.Solid}. -- -- There are different types of collision shapes, each of them has its own -- constructor function. local engine = require 'engine' local class = require 'middleclass' local Scheduler = require'core/Scheduler' local CollisionShape = class('core/physics/CollisionShape') --- Abstract class. -- -- Use @{core.physics.BoxCollisionShape}, @{core.physics.SphereCollisionShape}, -- @{core.physics.CapsuleCollisionShape}, or @{core.physics.CompoundCollisionShape} -- instead. -- function CollisionShape:initialize( handle ) assert(self.class ~= CollisionShape, 'CollisionShape is an abstract class and not meant to be instanciated directly.') self.handle = handle end function CollisionShape:destroy() Scheduler.blindCall(engine.DestroyCollisionShape, self.handle) self.handle = nil end return CollisionShape
-- Your normal yeast minetest.register_craftitem("yatm_brewery:yeast_brewers", { basename = "yatm_brewery:yeast", base_description = "Yeast", description = "Brewer's Yeast", groups = { yeast = 1, yeast_brewers = 1, }, inventory_image = "yatm_yeast_brewers.png" }) -- Wine! minetest.register_craftitem("yatm_brewery:yeast_bayanus", { basename = "yatm_brewery:yeast", base_description = "Yeast", description = "Bayanus Yeast", groups = { yeast = 1, yeast_bayanus = 1, }, inventory_image = "yatm_yeast_bayanus.png" }) -- Spicy! minetest.register_craftitem("yatm_brewery:yeast_scarlet", { basename = "yatm_brewery:yeast", base_description = "Yeast", description = "Scarlet Yeast", groups = { yeast = 1, yeast_scarlet = 1, }, inventory_image = "yatm_yeast_scarlet.png" }) -- Magical properties, quite frankly, it's weird. minetest.register_craftitem("yatm_brewery:yeast_umbral", { basename = "yatm_brewery:yeast", base_description = "Yeast", description = "Umbral Yeast", groups = { yeast = 1, yeast_umbral = 1, }, inventory_image = "yatm_yeast_umbral.png" })
--[[ Purpose: Library to load plugins from the framework and schema and retrieve plugins that have been loaded. --]] nut.plugin = nut.plugin or {} nut.plugin.buffer = nut.plugin.buffer or {} --[[ Purpose: Library to load plugins from the framework and schema and retrieve plugins that have been loaded. --]] function nut.plugin.IncludeEntities(directory) local entityFiles, entityFolders = file.Find(directory.."/entities/entities/*", "LUA") for k, v in pairs(entityFolders) do ENT = {} ENT.Type = "anim" ENT.ClassName = v local directory2 = directory.."/entities/entities/"..ENT.ClassName.."/" if (file.Exists(directory2.."cl_init.lua", "LUA")) then nut.util.Include(directory2.."init.lua", "server") nut.util.Include(directory2.."cl_init.lua") else nut.util.Include(directory2.."shared.lua", "shared") end scripted_ents.Register(ENT, ENT.ClassName) ENT = nil end for k, v in pairs(entityFiles) do ENT = {} ENT.ClassName = string.sub(v, 1, -5) nut.util.Include(directory.."/entities/entities/"..ENT.ClassName..".lua", "shared") scripted_ents.Register(ENT, ENT.ClassName) ENT = nil end end --[[ Purpose: Includes the effects within the plugin's entities/weapons sub-directory and registers them. --]] function nut.plugin.IncludeWeapons(directory) local weaponFiles, weaponFolders = file.Find(directory.."/entities/weapons/*", "LUA") for k, v in pairs(weaponFolders) do SWEP = {} SWEP.Folder = v SWEP.Base = "weapon_base" SWEP.Primary = {} SWEP.Secondary = {} local directory2 = directory.."/entities/weapons/"..SWEP.Folder.."/" if (file.Exists(directory2.."cl_init.lua", "LUA")) then nut.util.Include(directory2.."init.lua", "server") nut.util.Include(directory2.."cl_init.lua") else nut.util.Include(directory2.."shared.lua", "shared") end weapons.Register(SWEP, SWEP.Folder) SWEP = nil end for k, v in pairs(weaponFiles) do SWEP = { Primary = {}, Secondary = {} } SWEP.Folder = string.sub(v, 1, -5) SWEP.Base = "weapon_base" nut.util.Include(directory.."/entities/weapons/"..v, "shared") weapons.Register(SWEP, SWEP.Folder) SWEP = nil end end --[[ Purpose: Includes the effects within the plugin's entities/effects sub-directory and registers them. --]] function nut.plugin.IncludeEffects(directory) local effectFiles, effectFolders = file.Find(directory.."/entities/effects/*", "LUA") for k, v in pairs(effectFolders) do EFFECT = {} EFFECT.ClassName = v local directory2 = directory.."/entities/effects/"..EFFECT.ClassName.."/" if (file.Exists(directory2.."cl_init.lua", "LUA")) then nut.util.Include(directory2.."init.lua", "server") nut.util.Include(directory2.."cl_init.lua") elseif (file.Exists(directory2.."shared.lua", "LUA")) then nut.util.Include(directory2.."shared.lua", "shared") end if (CLIENT) then effects.Register(EFFECT, EFFECT.ClassName) end EFFECT = nil end for k, v in pairs(effectFiles) do EFFECT = {} EFFECT.ClassName = string.sub(v, 1, -4) nut.util.Include(directory.."/entities/effects/"..EFFECT.ClassName..".lua", "client") if (CLIENT) then effects.Register(EFFECT, EFFECT.ClassName) end EFFECT = nil end end --[[ Purpose: Searches for directories within the given base directory and registers a plugin based off the name of the directories within. After that, each individual file inside plugins/ will be included. Anything between sh_ and .lua will be the plugin's unique id. --]] function nut.plugin.Load(directory) local _, folders = file.Find(directory.."/plugins/*", "LUA") for k, v in pairs(folders) do local blocked = nut.schema.Call("BlockPlugins", v, directory) if (!blocked) then PLUGIN = nut.plugin.Get(v) or {} PLUGIN.uniqueID = v; local pluginDir = directory.."/plugins/"..v; if (file.Exists(pluginDir.."/sh_plugin.lua", "LUA")) then nut.plugin.PluginInit(PLUGIN, v); nut.util.Include(pluginDir.."/sh_plugin.lua") nut.plugin.IncludeEntities(pluginDir) nut.plugin.IncludeWeapons(pluginDir) nut.plugin.IncludeEffects(pluginDir) nut.item.Load(pluginDir); nut.plugin.buffer[v] = PLUGIN end PLUGIN = nil end end local files = file.Find(directory.."/plugins/*.lua", "LUA") for k, v in pairs(files) do local cleanName = string.sub(v, 1, -5) if (cleanName:sub(1, 3) == "sh_") then cleanName = cleanName:sub(4) end local blocked = nut.schema.Call("BlockPlugins", cleanName, directory) if (!blocked) then PLUGIN = nut.plugin.Get(cleanName) or {}; nut.plugin.PluginInit(PLUGIN, v); nut.util.Include(directory.."/plugins/"..v, "shared"); nut.plugin.buffer[cleanName] = PLUGIN; PLUGIN = nil; end end end function nut.plugin.PluginInit(PLUGIN, uniqueID) PLUGIN.uniqueID = uniqueID; // Send Error Log // if(PLUGIN.desc == nil) then PLUGIN.desc = ""; end if(PLUGIN.name == nil) then PLUGIN.name = ""; end if(PLUGIN.author == nil) then PLUGIN.author = ""; end // function PLUGIN:WriteTable(data, ignoreMap, global) return nut.util.WriteTable(self.uniqueID, data, ignoreMap, global) end function PLUGIN:ReadTable(ignoreMap, forceRefresh) return nut.util.ReadTable(self.uniqueID, ignoreMap, forceRefresh) end function PLUGIN:GetPluginIdentifier(key, caller) return AdvNut.util.CreateIdentifier("", caller).."Plugin."..self.uniqueID.."."..key; end; // Private Function. // function PLUGIN:_GetPluginLanguageIdentifier(key) return self:GetPluginIdentifier("").."Language."..key; end; function PLUGIN:AddPluginLanguage(key, value, language) nut.lang.Add(self:_GetPluginLanguageIdentifier(key), value, language); end; function PLUGIN:GetPluginLanguage(key, ...) return nut.lang.Get(self:_GetPluginLanguageIdentifier(key), ...); end; function PLUGIN:GetPluginConfig(key, default) if (self) then if (nut.config[self.uniqueID]) then return nut.config[self.uniqueID][key] or default; else return default; end; else return default; end; end; function PLUGIN:SetPluginConfig(key, value) if(self.uniqueID) then local uniqueID = self.uniqueID; if (!nut.config[uniqueID]) then nut.config[uniqueID] = {}; end; nut.config[self.uniqueID][key] = value; end; end; function PLUGIN:IncludeDir(dir) local path; if (SCHEMA and !self.base) then path = SCHEMA.folderName.."/plugin/"..self.uniqueID.."/"..dir; else path = "nutscript/plugins/"..self.uniqueID.."/"..dir; end; for k, v in pairs(file.Find(path.."/*.lua", "LUA")) do nut.util.Include(path.."/"..v); end end; end --[[ Purpose: Retrieves all of the registered plugins. --]] function nut.plugin.GetAll() return nut.plugin.buffer end --[[ Purpose: Returns a plugin's table based off the uniqueID given. --]] function nut.plugin.Get(uniqueID) return nut.plugin.buffer[uniqueID] end if (CLIENT) then AdvNut.hook.Add("BuildHelpOptions", "nut_PluginHelp", function(data) data:AddHelp("플러그인", function() local html = "" for k, v in SortedPairs(nut.plugin.buffer) do html = html.."<p><b>"..(v.name or k).."</b><br /> 제작자 : "..(v.author or "익명").."<br /> 설명 : "..v.desc or nut.lang.Get("no_desc").."</p>" end return html end, "icon16/plugin.png") end) end
Scene_Splash = Scene_Base:extend("Scene_Splash") function Scene_Splash.prototype:enter() self._splash = require("lib.splashes.o-ten-one")() local scene = self self._splash.onDone = function () scene:startFadeout() end self._alpha = 1 self._splashCanvas = love.graphics.newCanvas(love.graphics.getDimensions()) end function Scene_Splash.prototype:startFadeout() self.update = self.updateFadeout self.draw = self.drawFadeout self._alpha = 1 end function Scene_Splash.prototype:updateFadeout(dt) Scene_Splash.prototype.update(self, dt) if self._alpha > 0 then self._alpha = self._alpha - dt self._exit = true return end if self._exit then Scene_Manager:enter(Scene_Title()) self._exit = false end end function Scene_Splash.prototype:update(dt) self._splash:update(dt) local canvas = love.graphics.getCanvas() love.graphics.setCanvas(self._splashCanvas) self._splash:draw() love.graphics.setCanvas(canvas) end function Scene_Splash.prototype:draw() love.graphics.setColor(1, 1, 1, self._alpha) love.graphics.draw(self._splashCanvas) end function Scene_Splash.prototype:drawFadeout() end function Scene_Splash.prototype:leave() end function Scene_Splash.prototype:keypressed() Audio_Manager:playSFX("menu_back") self._splash:skip() end function Scene_Splash.prototype:gamepadpressed() Audio_Manager:playSFX("menu_back") self._splash:skip() end function Scene_Splash.prototype:mousepressed() Audio_Manager:playSFX("menu_back") self._splash:skip() end
-- konko-mods.lua -- --------------------------- -- Mods:Insert(start, len, ease, modpairs, [offset], [plr]) - Writes mods to branch -- start - Starting time -- len - Length to full percentage -- ease - Ease function -- modpairs - {{end_p, mod, [begin_p]}, ...} -- end_p - Ending percent -- mod - Mod to activate (PascalCase uses player option functions) -- begin_p - Beginning percent (optional) -- offset - Offset between each mod in modpairs (optional) -- plr - Player to apply mods (optional) -- Mods:Define(name, func, return) - Defines a new mod from a function -- Mods:FromFile(path) - Reads mods from a separate file -- Mods:Mirin({start, len, ease, perc, mod, ...}, [offset], [plr]) - Writes mods to branch Mirin style -- Mods:Exsch(start, len, begin_p, end_p, mod, timing, ease, [offset], [plr]) - Write mods to branch Exschwasion style -- Mods:Default(modpairs) - Writes default mods to branch --------------------------- local std = import 'stdlib' local Mods = {} setmetatable(Mods, {}) -- Version number local VERSION = '1.4' local POptions = {} for i, v in ipairs( GAMESTATE:GetEnabledPlayers() ) do POptions[i] = GAMESTATE:GetPlayerState(v):GetPlayerOptions('ModsLevel_Song') end local modlist = {} local mod_percents = {} local note_percents = {} local custom_mods = {} local default_mods = {} local active = {} for pn = 1, #POptions do mod_percents[pn] = {} note_percents[pn] = {} custom_mods[pn] = {} default_mods[pn] = {} active[pn] = {} end --[[ local function ApplyMods(mod, percent, pn) if custom_mods[pn][mod] ~= nil then local new_perc = custom_mods[pn][mod].Function(percent, pn) local new_mod = custom_mods[pn][mod].Return percent = new_perc -- haha :TacMeme2: mod = new_mod end if mod then -- TODO: Fix mod ease calculations so percentage doesn't end up backwards local modstring = '*-1 '..(percent)..' '..mod:lower() if mod:sub(2):lower() == 'mod' then modstring = '*-1 '..percent..mod:sub(1, 1):lower() end if pn then POptions[pn]:FromString(modstring) else for p = 1, #POptions do POptions[p]:FromString(modstring) end end end end --]] -- TODO: Make sure this doesn't run on unnecessary frames. ~Sudo local function ApplyMods() for pn = 1, #POptions do local modstring = '' for mod, percent in pairs(mod_percents[pn]) do if custom_mods[pn][mod] ~= nil then local new_perc = {custom_mods[pn][mod].Function(percent, pn)} local new_mod = custom_mods[pn][mod].Return for i = 1, #new_perc do percent = new_perc[i] mod = new_mod[i] if POptions[pn][mod] then if mod:sub(2) == 'Mod' then POptions[pn][mod](POptions[pn], percent, 9e9) else POptions[pn][mod](POptions[pn], percent * 0.01, 9e9) end elseif mod:lower() == 'xmod' then modstring = modstring..'*-1 '..percent..mod:sub(1, 1):lower()..',' elseif mod:sub(2):lower() == 'mod' then modstring = modstring..'*-1 '..mod:sub(1, 1):lower()..percent..',' else modstring = modstring..'*-1 '..(percent)..' '..mod:lower()..',' end end elseif mod then if POptions[pn][mod] then if mod:sub(2) == 'Mod' then POptions[pn][mod](POptions[pn], percent, 9e9) else POptions[pn][mod](POptions[pn], percent * 0.01, 9e9) end elseif mod:lower() == 'xmod' then modstring = modstring..'*-1 '..percent..mod:sub(1, 1):lower()..',' elseif mod:sub(2):lower() == 'mod' then modstring = modstring..'*-1 '..mod:sub(1, 1):lower()..percent..',' else modstring = modstring..'*-1 '..(percent)..' '..mod:lower()..',' end end end if modstring ~= '' then POptions[pn]:FromString(modstring) end end end local function ApplyNotes(beat, col, mod, percent, pn) -- Code to turn on notemods once will go here once function is implemented engine side mod = mod:lower() if pn then std.PL[pn].Player:AddNoteMod(beat, col, mod, percent * 0.01) else for p = 1, #POptions do std.PL[p].Player:AddNoteMod(beat, col, mod, percent * 0.01) end end end local function UpdateMods() for i, m in ipairs(modlist) do for j, v in ipairs(m.Modifiers) do -- If the player where we're trying to access is not available, then don't even update. if m.Player and not POptions[m.Player] then break end local BEAT = std.BEAT local pn = m.Player if (BEAT >= m.Start and BEAT < (m.Start + m.Length)) then if m.Type == 'Player' then -- Ease blending is a work in progress. Try to make sure two eases don't use the same mod. v[3] = v[3] or mod_percents[pn][v[2]] or 0 active[pn][v[2]] = active[pn][v[2]] or {} v[4] = v[4] or (#active[pn][v[2]] + 1) active[pn][v[2]][v[4]] = m local perc = 0 for n = 1, v[4] do local offset = (n > v[4]) and 1 or 0 local cur_m = active[pn][v[2]][n] local cur_v1 = cur_m.Modifiers[j][1] local cur_v3 = cur_m.Modifiers[j][3] local cur_ease = cur_m.Ease((BEAT - cur_m.Start) / cur_m.Length) - offset if m.Length == 0 then cur_ease = cur_m.Ease(1) - offset end local cur_perc = cur_ease * (cur_v1 - cur_v3) if #active[pn][v[2]] == n then perc = perc + (cur_v3 + cur_perc) end end mod_percents[pn][v[2]] = perc elseif m.Type == 'bup' then v[3] = v[3] or mod_percents[pn][v[2]] or default_mods[pn][v[2]] or 0 local ease = m.Ease((BEAT - m.Start) / m.Length) if m.Length == 0 then ease = m.Ease(1) end local perc = ease * (v[1] - v[3]) mod_percents[pn][v[2]] = perc + v[3] elseif m.Type == 'Note' then local notemod = v[4]..'|'..v[1]..'|'..v[2] v[5] = v[5] or note_percents[pn][notemod] or default_mods[pn][notemod] or 0 active[pn][notemod] = active[pn][notemod] or {} v[6] = v[6] or (#active[pn][notemod] + 1) active[pn][notemod][v[6]] = m local perc = 0 for n = 1, v[6] do local offset = (n > v[6]) and 1 or 0 local cur_m = active[pn][notemod][n] local cur_v3 = cur_m.Modifiers[j][3] local cur_v5 = cur_m.Modifiers[j][5] local cur_ease = cur_m.Ease((BEAT - cur_m.Start) / cur_m.Length) - offset if m.Length == 0 then cur_ease = 1 end local cur_perc = cur_ease * (cur_v3 - cur_v5) if #active[pn][notemod] == n then perc = perc + (cur_v5 + cur_perc) end end note_percents[pn][notemod] = perc end elseif BEAT >= (m.Start + m.Length) then if m.Type == 'Player' then v[3] = v[3] or mod_percents[pn][v[2]] or 0 mod_percents[pn][v[2]] = m.Ease(1) * (v[1] - v[3]) + v[3] if v[4] and active[pn][v[2]] then active[pn][v[2]][v[4]] = nil end elseif m.Type == 'Note' then v[5] = v[5] or note_percents[pn][notemod] or 0 local notemod = v[4]..'|'..v[1]..'|'..v[2] note_percents[pn][notemod] = m.Ease(1) * (v[3] - v[5]) + v[5] if v[6] and active[pn][notemod] then active[pn][notemod][v[6]] = nil end end if j == #m.Modifiers then m.Modifiers = {} end end end end end FG[#FG + 1] = Def.Actor { ReadyCommand = function(self) for pn = 1, #POptions do POptions[pn]:FromString('*-1 clearall', pn) end end, UpdateCommand = function(self) UpdateMods() ApplyMods() end } -- TODO: Create a GetPercent function to get the current mod percent -- Load a mod file. local function FromFile(self, scriptpath) --printerr('Mods:LoadFromFile') run('lua/'..scriptpath) return self end -- Write default mods. local function Default(self, modtable) --printerr('Mods:Default') for pn = 1, #POptions do default_mods[pn] = modtable end local res = self:Insert(std.START, 0, Tweens.instant, modtable) return res end -- Define a new mod. local function Define(self, name, func, ret) --printerr('Mods:Define') local t = {} if type(ret) ~= 'table' then ret = {ret} end t = { Function = func, Return = ret } for pn = 1, #POptions do custom_mods[pn][name] = t end return self end -- Insert a mod. local function Insert(self, start, len, ease, modtable, offset, pn) --printerr('Mods:Insert') local t1, t2 = {}, {} if not offset or offset == 0 then t1 = { Start = start, Length = len, Ease = ease, Modifiers = modtable, Type = 'Player', Player = pn or 1 } table.insert(modlist, t1) if not pn then t2 = { Start = start, Length = len, Ease = ease, Modifiers = modtable, Type = 'Player', Player = 2 } table.insert(modlist, t2) end else for i, v in ipairs(modtable) do t1[i] = { Start = start + (offset * (i - 1)), Length = len, Ease = ease, Modifiers = {v}, Type = 'Player', Player = pn or 1 } table.insert(modlist, t1[i]) if not pn then t2[i] = { Start = start + (offset * (i - 1)), Length = len, Ease = ease, Modifiers = {v}, Type = 'Player', Player = 2 } table.insert(modlist, t2[i]) end end end return self end -- We can't actually add notemods until they stop corrupting the stack. local function Note(self, start, len, ease, notemodtable, offset, pn) --printerr(Mods:Note) local t1, t2 = {}, {} if not offset or offset == 0 then t1 = { Start = start, Length = len, Ease = ease, Modifiers = notemodtable, Type = 'Note', Player = pn or 1 } table.insert(modlist, t1) if not pn then t2 = { Start = start, Length = len, Ease = ease, Modifiers = notemodtable, Type = 'Note', Player = 2 } table.insert(modlist, t2) end else for i, v in ipairs(notemodtable) do t1[i] = { Start = start + (offset * (i - 1)), Length = len, Ease = ease, Modifiers = {v}, Type = 'Note', Player = pn or 1 } table.insert(modlist, t1[i]) if not pn then t2[i] = { Start = start + (offset * (i - 1)), Length = len, Ease = ease, Modifiers = {v}, Type = 'Note', Player = 2 } table.insert(modlist, t2[i]) end end end return self end -- Insert a mod but you like extra wasabi local function Exsch(self, start, len, str1, str2, mod, timing, ease, pn) --printerr('Mods:Exsch') if timing == 'end' then len = len - start end local res = self:Insert(start, len, ease, {{str2, mod, str1}}, 0, pn) return res end -- so-called "free thinkers" when mirin template local function Mirin(self, t, offset, pn) --printerr('Mods:Mirin') local tmods = {} for i = 4, #t, 2 do if t[i] and t[i + 1] then tmods[#tmods + 1] = {t[i], t[i + 1]} end end local res = self:Insert(t[1], t[2], t[3], tmods, offset, pn) return res end Mods = { VERSION = VERSION, FromFile = FromFile, Define = Define, Insert = Insert, --Note = Note, Mirin = Mirin, Exsch = Exsch, Default = Default, } Mods.__index = Mods print('Loaded Konko Mods v'..Mods.VERSION) return Mods
return { summary = 'Get the depth buffer used by the Canvas.', description = [[ Returns the depth buffer used by the Canvas as a Texture. If the Canvas was not created with a readable depth buffer (the `depth.readable` flag in `lovr.graphics.newCanvas`), then this function will return `nil`. ]], arguments = {}, returns = { { name = 'texture', type = 'Texture', description = 'The depth Texture of the Canvas.' } }, related = { 'lovr.graphics.newCanvas' } }
local DowntimeService = require(6317978171) -- Or require by using the file path. (Requiring by ID is better for quicker updates.) local Players = game:GetService("Players") -- Example #1: Kicking Players if Datastores are down. Players.PlayerAdded:Connect(function(player) if DowntimeService:GetDatastoreAPIStatus() == "down" then player:Kick("Datastores are currently down. To prevent critical errors we have kicked you. If this issue persits please contact the game owner. =") end end) -- Example #2 Printing latest tests if something is down or not. while true do if DowntimeService:GetSiteStatus() == "down" then warn("Roblox Website is Currently Down! Please be patient while Roblox works on a fix! :)") elseif DowntimeService.GetSiteStatus() == "degraded" then print("Roblox Website is Currently slow! Please be patient while Roblox works on it! :)") elseif DowntimeService:GetSiteStatus() == "up" then print("Roblox website is currently up!") end wait(300) end
-------------------------------------------------------------------------------- -- -- This file is part of the Doxyrest toolkit. -- -- Doxyrest is distributed under the MIT license. -- For details see accompanying license.txt file, -- the public copy of which is also available at: -- http://tibbo.com/downloads/archive/doxyrest/license.txt -- -------------------------------------------------------------------------------- --! --! \defgroup api-compounds --! \ingroup api --! \grouporder 2 --! \title Doxygen Compounds --! --! This section describes types (enumerations and tables) used to represent --! Doxygen compounds (classes, namespaces, groups, etc). --! --! @{ --! -------------------------------------------------------------------------------- --! --! \luaenum --! CompoundKind = { "class", "struct", "union", "interface", "protocol", "category", "exception", "service", "singleton", "file", "namespace", "group", "page", "example", "dir", } -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --! --! \luastruct --! \luabasetype NamespaceContents --! --! Table of this type describes a Doxygen *compound* such as *class*, --! *namespace*, *group* etc. --! Compound = { --! Holds a string describing compound type. Must be one of `CompoundKind`. compoundKind, --! --! Holds Doxygen identifier string, e.g. --! ``group__type_1gada12e3c9caedb0e18d384bfdc7e7def3``. --! --! This string can be used as a unique identifier for creating labels and --! reference links. --! id, --! Holds a string with the name of the compound. name, --! --! Holds a string with the title (if specified) or an empty string. --! --! Usually compound titles are not used unless this is a ``group`` --! compound. --! title, importId, group, --! --! Holds a string with a forward-slash-separated path to the compound --! starting from the global namespace. For example, C++ class --! ``sys::win::WaitableTimer`` will have its path encoded as --! ``sys/win/WaitableTimer``. --! --! This field can be used to reconstruct a fully qualified name of the --! compound. --! path, importArray, --! Holds a `Description` table with the brief description of the compound. briefDescription, --! Holds a `Description` table with the detailed description of the --! compound. detailedDescription, --! Holds a `Location` table describing the place of declaration. location, } --! --! \luastruct --! \luabasetype Compound --! Group = { --! Holds the group index in the ``innerRef`` array from the original XML --! database. originalIdx, } --! --! \luastruct --! \luabasetype Compound --! Page = { subPageArray, } --! --! \luastruct --! \luabasetype Compound --! Class = { --[[! Holds a table containing an array of all template parameters of the compound. Type of each element of the array is `Param` This field is only set when ``compoundKind`` is one of: | ``struct`` | ``union`` | ``class`` | ``interface`` ]] templateParamArray, --[[! Holds a table containing an array of all template specialization parameters of the compound. Type of each element of the array is `Param` This field is only set when ``compoundKind`` is one of: | ``struct`` | ``union`` | ``class`` | ``interface`` ]] templateSpecParamArray, baseTypeArray, baseTypeProtectionArray, derivedTypeArray, } --! --! \luastruct --! NamespaceContents = { --! --! Holds a table containing an array of all the groups withing the --! compound. --! --! Type of each element of the array is ``Compound``. --! `Compound.compoundKind` should be ``group``. --! groupArray, --! --! Holds a table containing an array of all the nested namespaces. --! --! Type of each element of the array is ``Compound``. --! `Compound.compoundKind` should be ``namespace``. --! namespaceArray, --! --! Holds a table containing an array of all the enums withing the compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``enum``. --! enumArray, --! --! Holds a table containing an array of all the nested structs within the --! compound. --! --! Type of each element of the array is ``Compound``. --! `Compound.compoundKind` should be ``struct``. --! structArray, --! --! Holds a table containing an array of all the nested unions within the --! compound. --! --! Type of each element of the array is ``Compound``. --! `Compound.compoundKind` should be ``union``. --! unionArray, --! --! Holds a table containing an array of all the nested classes within the --! compound. --! --! Type of each element of the array is ``Compound``. --! `Compound.compoundKind` should be ``class``. --! classArray, interfaceArray, protocolArray, exceptionArray, serviceArray, singletonArray, --! --! Holds a table containing an array of all the typedefs within the --! compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``typedef``. --! typedefArray, --![[! --! Holds a table containing an array of all the variables within the --! compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``variable``. --! variableArray, --! --! Holds a table containing an array of all the constructors of the type --! compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``function``. --! constructorArray, --! --! Holds a `Member` table describing the destructor of the type compound --! (if there is any) or ``nil``. --! --! `Member.memberKind` should be ``function``. --! destructor, --! --! Holds a table containing an array of all the functions/methods within --! the compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``function``. --! functionArray, --! --! Holds a table containing an array of all the properties within the --! compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``property``. --! propertyArray, --! --! Holds a table containing an array of all the events within the compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``event``. --! eventArray, --! --! Holds a table containing an array of all the aliases within the --! compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``alias``. --! aliasArray, --! --! Holds a table containing an array of all the macro definitions within --! the compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``define``. --! defineArray, --! --! Holds a table containing an array of all the footnotes defined within --! the compound. --! --! Type of each element of the array is `Member`. `Member.memberKind` --! should be ``footnote``. --! footnoteArray, } --! --! \luastruct --! \luabasetype NamespaceContents --! GlobalNamespace = { path, id, --! always set to "global" compoundKind, --! always set to "namespace" briefDescription, detailedDescription, } -------------------------------------------------------------------------------- --! @}
-- If you have any suggestions you can create an issue at https://github.com/Kistras/2q2WxkSZhzU --------------- -- Remove holos if script was reloaded if HOLOBUILDER then for k,e in pairs(HOLOBUILDER.Holograms) do if e.Entity then e.Entity:Remove() end end end -- For interaction with other scripts HOLOBUILDER = {} -- Global HOLOBUILDER.Active = true -- Is builder active? HOLOBUILDER.Holograms = {} HOLOBUILDER.OriginPos = Vector(0, 0, 0) HOLOBUILDER.SelectedHolo = nil -- A number HOLOBUILDER.HighlightedHolo = nil -- A number HOLOBUILDER.HighlightedDist = nil -- A number HOLOBUILDER.RadialMenu = false -- If it is opened HOLOBUILDER.RadialMenuSelected = nil HOLOBUILDER.DrawnStuff = {} -- Used in radial menu to draw stuff on screen HOLOBUILDER.Functions = {} -- Used in radial menu to do stuff HOLOBUILDER.Used3D2D = {} -- HOLOBUILDER.Mode = "Select" -- Mode specific stuff HOLOBUILDER.MoveDistance = nil -- A number HOLOBUILDER.MoveOffset = Vector(0, 0, 0) -- concommand.Add("holobuilder", function(ply, cmd, args) HOLOBUILDER.Active = not HOLOBUILDER.Active end) -- Hologram class? local holoclass = {} holoclass.Id = 1 holoclass.Model = "models/holograms/cube.mdl" holoclass.Color = Color(255, 255, 255, 255) holoclass.Material = "models/debug/debugwhite" holoclass.Scale = Vector(1, 1, 1) holoclass.ScaleInUnits = false holoclass.Clip = {} holoclass.DisableShadows = false holoclass.Parent = 1 holoclass.Pos = Vector(0, 0, 0) holoclass.Angle = Angle(0, 0, 0) holoclass.Name = "Hologram" holoclass.Draw = true holoclass.Entity = nil HOLOBUILDER.HoloClass = holoclass -- A number local function applydata(id) local holo = HOLOBUILDER.Holograms[id] if holo then local en = holo.Entity if en then en:SetPos(HOLOBUILDER.OriginPos + holo.Pos) en:SetMaterial(holo.Material) en:SetModel(holo.Model) en:SetColor(holo.Color) if not isnumber(holo.Parent) or holo.Parent == holo.Id or holo.Parent == 0 then local ParentHolo = HOLOBUILDER.Holograms[holo.Parent] if ParentHolo and IsValid(ParentHolo.Entity) then en:SetParent(ParentHolo.Entity) end else en:SetParent() // Unparent, yeah end local mat = Matrix() if holo.ScaleInUnits then local boundsMins, boundsMaxs = en:GetModelBounds() local size = boundsMaxs - boundsMins mat:Scale(Vector(holo.Scale.x / size.x, holo.Scale.y / size.y, holo.Scale.z / size.z)) //print(holo.Scale / size) else mat:Scale(holo.Scale) end en:EnableMatrix("RenderMultiply", mat) end end end local function spawnholo(holo) local entity = ClientsideModel(holo.Model) entity:SetPos(HOLOBUILDER.OriginPos + holo.Pos) entity:Spawn() entity:SetRenderMode(RENDERMODE_TRANSCOLOR) holo.Entity = entity HOLOBUILDER.Holograms[holo.Id] = holo applydata(holo.Id) end -- -- Functions go brrr HOLOBUILDER.Functions["New Holo"] = function() local trace = LocalPlayer():GetEyeTrace() local holo = table.Copy(holoclass) holo.Pos = trace.HitPos - HOLOBUILDER.OriginPos + trace.HitNormal * 24 holo.Pos = Vector(math.Round(holo.Pos.x), math.Round(holo.Pos.y), math.Round(holo.Pos.z)) -- Iterate thru ids local Id = 1 while HOLOBUILDER.Holograms[Id] do Id = Id + 1 end holo.Id = Id spawnholo(holo) HOLOBUILDER.SelectedHolo = Id end HOLOBUILDER.Functions["Save"] = function() -- There should be confirmation window or something local str = "if(first()){\n" for id,holo in pairs(HOLOBUILDER.Holograms) do str = str .. " holoCreate(" .. id .. ") holoPos(" .. id .. ", entity():toWorld(vec(" .. holo.Pos.x .. ", " .. holo.Pos.y .. ", " .. holo.Pos.z .. "))) " if not isnumber(holo.Parent) or holo.Parent == holo.Id or holo.Parent == 0 then str = str .. "holoParent(" .. id .. ", entity()) " else local ParentHolo = HOLOBUILDER.Holograms[holo.Parent] if ParentHolo and IsValid(ParentHolo.Entity) then str = str .. "holoParent(" .. id .. ", " .. holo.Parent .. ") " end end str = str .. "\n" end str = str .. "}" file.Write("expression2/HOLOBUILDER_OUTPUT_123.txt", str) chat.AddText("Saved") end HOLOBUILDER.Functions["Load"] = function() end HOLOBUILDER.Functions["Clear"] = function() end HOLOBUILDER.Functions["#Move"] = function() HOLOBUILDER.Mode = "Move" end -- surface.CreateFont("HoloBuilder", { font = "Segoe UI Semibold", extended = false, size = 30, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, }) surface.CreateFont("HoloBuilderRadial", { font = "Segoe UI Semibold", extended = false, size = 20, weight = 500, blursize = 0, scanlines = 0, antialias = true, underline = false, italic = false, strikeout = false, symbol = false, rotary = false, shadow = false, additive = false, outline = false, }) hook.Add("Think", "HoloBuilderHandler", function() if HOLOBUILDER.Active then if table.IsEmpty(HOLOBUILDER.Holograms) then local holo = table.Copy(holoclass) holo.Name = "Origin" local trace = LocalPlayer():GetEyeTrace() HOLOBUILDER.OriginPos = trace.HitPos + trace.HitNormal * 24 spawnholo(holo) print("Origin holo was created.") else -- end end end) -- Get entities player looks at hook.Add("PreDrawTranslucentRenderables", "HoloBuilderHighlighter", function() if HOLOBUILDER.Active then local rayStart = EyePos() local rayDelta = EyeVector() * 256 local trace = LocalPlayer():GetEyeTrace() local tracelen = rayStart:DistToSqr(trace.HitPos) local newHolo = nil local newDist = 99999 local lastPos = nil for id, holo in pairs(HOLOBUILDER.Holograms) do if holo.Entity then local boxOrigin = holo.Entity:GetPos() local boxAngles = holo.Entity:GetAngles() -- Entity:OBBMins() or Entity:OBBMaxs() retuns Vector(0,0,0) -- So I used Entity:GetModelBounds() local boxMins, boxMaxs = holo.Entity:GetModelBounds() if holo.ScaleInUnits then /* local size = boxMaxs - boxMins local propoffset = boxMins + boxMaxs propoffset = Vector(propoffset.x / size.x * holo.Scale.x, propoffset.y / size.y * holo.Scale.y, propoffset.z / size.z * holo.Scale.z) -- Usually they compensate each other. Tell me if something is off boxMins = -holo.Scale / 2 + propoffset boxMaxs = holo.Scale / 2 + propoffset */ -- The thing above was supposed to compensate model shifting, but I can't do anything with it for now. boxMins = -holo.Scale / 2 boxMaxs = holo.Scale / 2 else boxMins = Vector(boxMins.x * holo.Scale.x, boxMins.y * holo.Scale.y, boxMins.z * holo.Scale.z) boxMaxs = Vector(boxMaxs.x * holo.Scale.x, boxMaxs.y * holo.Scale.y, boxMaxs.z * holo.Scale.z) end local hitPos, normalVec, fraction = util.IntersectRayWithOBB(rayStart, rayDelta, boxOrigin, boxAngles, boxMins, boxMaxs) if hitPos then local dist = rayStart:DistToSqr(hitPos) -- Check if this holo is closer to player than entity in front of them -- This way we won't be able to target stuff through walls if dist < tracelen then if dist < newDist then -- If this holo is closer to player newHolo = id newDist = dist lastPos = hitPos end end end end end HOLOBUILDER.HighlightedHolo = newHolo HOLOBUILDER.HighlightedDist = newDist -- Modes -- Move if HOLOBUILDER.Mode == "Move" and input.IsMouseDown(MOUSE_LEFT) then if lastPos and HOLOBUILDER.MoveDistance == nil and HOLOBUILDER.HighlightedHolo == HOLOBUILDER.SelectedHolo and HOLOBUILDER.HighlightedDist < 100000 then //HOLOBUILDER.MoveDistance = (HOLOBUILDER.Holograms[HOLOBUILDER.HighlightedHolo].Pos + HOLOBUILDER.OriginPos):Distance(EyePos()) HOLOBUILDER.MoveDistance = lastPos:Distance(EyePos()) HOLOBUILDER.MoveOffset = HOLOBUILDER.Holograms[HOLOBUILDER.HighlightedHolo].Pos - lastPos + HOLOBUILDER.OriginPos //print(HOLOBUILDER.MoveDistance) end elseif HOLOBUILDER.MoveDistance ~= nil then HOLOBUILDER.MoveDistance = nil end if HOLOBUILDER.MoveDistance ~= nil then //HOLOBUILDER.Holograms[HOLOBUILDER.SelectedHolo].Pos = (EyePos() + EyeVector() * HOLOBUILDER.MoveDistance + HOLOBUILDER.MoveOffset) - HOLOBUILDER.OriginPos local Pos = (EyePos() + EyeVector() * HOLOBUILDER.MoveDistance + HOLOBUILDER.MoveOffset) - HOLOBUILDER.OriginPos Pos = Vector(math.Round(Pos.x * 100) / 100, math.Round(Pos.y * 100) / 100, math.Round(Pos.z * 100) / 100) HOLOBUILDER.Holograms[HOLOBUILDER.SelectedHolo].Pos = Pos applydata(HOLOBUILDER.SelectedHolo) end end end) hook.Add("PreDrawHalos", "HoloBuilderHighlighter", function() if HOLOBUILDER.Active then if HOLOBUILDER.HighlightedHolo ~= nil and HOLOBUILDER.SelectedHolo ~= HOLOBUILDER.HighlightedHolo then local En = HOLOBUILDER.Holograms[HOLOBUILDER.HighlightedHolo].Entity if IsValid(En) then halo.Add({En}, color_red) end end if HOLOBUILDER.SelectedHolo then local En = HOLOBUILDER.Holograms[HOLOBUILDER.SelectedHolo].Entity if IsValid(En) then halo.Add({En}, color_white) end end end end) -- Intercept and replace user input -- local MMOffset = Vector(0, 0, 0) local maxcldist = 25 local Sensitivity = 10 -- Replace binds hook.Add("PlayerBindPress", "HoloBuilderInterceptKeys", function(ply, bind, pressed) if HOLOBUILDER.Active then if string.find(bind, "+zoom") then if pressed then HOLOBUILDER.RadialMenu = true HOLOBUILDER.RadialMenuSelected = nil MMOffset = Vector(0, 0, 0) else local field = HOLOBUILDER.DrawnStuff[HOLOBUILDER.RadialMenuSelected] HOLOBUILDER.RadialMenuSelected = nil HOLOBUILDER.RadialMenu = false if field ~= nil then HOLOBUILDER.Functions[field]() end end return true elseif string.find(bind, "+attack2") then return true elseif string.find(bind, "+attack") then if pressed then if HOLOBUILDER.HighlightedHolo then if HOLOBUILDER.HighlightedHolo == HOLOBUILDER.SelectedHolo then -- Maybe modes else HOLOBUILDER.SelectedHolo = HOLOBUILDER.HighlightedHolo end else HOLOBUILDER.SelectedHolo = nil HOLOBUILDER.Mode = "Select" end end return true end end end) -- Get mouse movements for radial menu hook.Add("InputMouseApply", "RadialMenuControls", function(cmd, x, y) if HOLOBUILDER.Active and HOLOBUILDER.RadialMenu then cmd:SetMouseX(0) cmd:SetMouseY(0) MMOffset = MMOffset + Vector(x / Sensitivity, y / Sensitivity, 0) -- Clamp it local dist = MMOffset:Length2D() if dist > maxcldist then MMOffset.x = MMOffset.x / dist * maxcldist MMOffset.y = MMOffset.y / dist * maxcldist dist = maxcldist end -- Get angles local amo = #HOLOBUILDER.DrawnStuff local ang = MMOffset:Angle().yaw / 360 -- I have no idea why this happens, but this thing has to have some sort of offset -- These numbers... work well for small numbers, but I haven't tested it any further. local offset = ((amo - 4) / 4) -- Why if ang and dist > 6 then HOLOBUILDER.RadialMenuSelected = math.floor(amo * -ang + offset) % amo + 1 else HOLOBUILDER.RadialMenuSelected = nil end // chat.AddText("" .. ang) return true end end) -- Draw stuff on screen local bg_color = Color(0, 0, 0, 128) local InitDistFromCenter = 25 local InitDistToEnd = 100 local InitTextDistToEnd = 90 local GapDistance = 3 local pi05 = math.pi / 2 local pi2 = math.pi * 2 -- https://wiki.facepunch.com/gmod/cam.PushModelMatrix local function rotatedText(text, x, y, font, color, ang) render.PushFilterMag(TEXFILTER.ANISOTROPIC) render.PushFilterMin(TEXFILTER.ANISOTROPIC) local m = Matrix() m:Translate(Vector(x, y, 0)) m:Rotate(Angle(0, ang, 0)) surface.SetFont(font) local w, h = surface.GetTextSize(text) m:Translate(-Vector(w / 2, h / 2, 0)) cam.PushModelMatrix(m) draw.DrawText(text, font, 0, 0, color) cam.PopModelMatrix() render.PopFilterMag() render.PopFilterMin() end -- DO NOT USE this implementation of radial menu -- You probably want to check out this: -- https://steamcommunity.com/sharedfiles/filedetails/?id=265292490 hook.Add("HUDPaint", "HoloBuilderRadialMenu", function() if HOLOBUILDER.Active and HOLOBUILDER.RadialMenu then surface.SetDrawColor(bg_color) draw.NoTexture() if HOLOBUILDER.SelectedHolo then HOLOBUILDER.DrawnStuff = { "#Move", "Rotate", "Color", "Name", "#Scale", "Material", "Parent", "Remove" } else HOLOBUILDER.DrawnStuff = { "New Holo", "Save", "Load", "Clear" } end local amo = #HOLOBUILDER.DrawnStuff if amo > 2 then local GapMod = GapDistance * (5 / amo) -- Approx. numbers local frac = pi2 / amo for h, e in pairs(HOLOBUILDER.DrawnStuff) do -- Used to make selected things "stand out" local PushOut if isnumber(HOLOBUILDER.RadialMenuSelected) and HOLOBUILDER.RadialMenuSelected == h then PushOut = 20 else PushOut = 0 end local DistFromCenter = InitDistFromCenter + PushOut local DistToEnd = InitDistToEnd + PushOut local TextDistToEnd = InitTextDistToEnd + PushOut -- So basically we need to throw a few (#DrawnStuff) lines, get points perpendicular to it -- on some distance (DistToEnd and DistFromCenter), connect those points and we've got -- our radial menu. Still broke something with this gap modificator, so I used just -- very rough approximated numbers. TODO: Works for now, should be fixed later. local LineStartX, LineStartY = math.sin((h) * frac), math.cos((h) * frac) local PerpStartX, PerpStartY = math.sin((h - pi05) * frac), math.cos((h - pi05) * frac) local LineEndX, LineEndY = math.sin((h + 1) * frac), math.cos((h + 1) * frac) local PerpEndX, PerpEndY = math.sin((h + 1 + pi05) * frac), math.cos((h + 1 + pi05) * frac) local Pol = { {x = ScrW() / 2 + LineStartX * DistToEnd - PerpStartX * GapMod, y = ScrH() / 2 + LineStartY * DistToEnd - PerpStartY * GapMod}, {x = ScrW() / 2 + LineStartX * DistFromCenter - PerpStartX * GapMod, y = ScrH() / 2 + LineStartY * DistFromCenter - PerpStartY * GapMod}, {x = ScrW() / 2 + LineEndX * DistFromCenter - PerpEndX * GapMod, y = ScrH() / 2 + LineEndY * DistFromCenter - PerpEndY * GapMod}, {x = ScrW() / 2 + LineEndX * DistToEnd - PerpEndX * GapMod, y = ScrH() / 2 + LineEndY * DistToEnd - PerpEndY * GapMod}, } surface.DrawPoly(Pol) //local DistMod = (2 - 1 / math.sqrt(#DrawnStuff)) //local PosX = (Pol[1].x + Pol[4].x) / 2 local PosX = (ScrW() + LineStartX * TextDistToEnd + LineEndX * TextDistToEnd) / 2 local PosY = (ScrH() + LineStartY * TextDistToEnd + LineEndY * TextDistToEnd) / 2 //print(math.Distance(PosX, PosY, ScrW() / 2, ScrH() / 2)) rotatedText(e, -- Doesn't work cuz I don't know right formula for distance //ScrW() / 2 + math.sin((h + 0.5) * frac) * DistToEnd / DistMod, //ScrH() / 2 + math.cos((h + 0.5) * frac) * DistToEnd / DistMod, PosX, PosY, "HoloBuilderRadial", color_white, ((-360 / amo) * (h + 0.5) + 90) % 180 - 90 ) //print(PerpStartX, PerpStartY) /* for k,e in pairs(Pol) do surface.DrawCircle(e.x, e.y, 15) surface.SetTextPos(e.x, e.y) surface.DrawText(k .. "") end //*/ //break end -- Cursor local Poly = {} local Frac = pi2 / amo local offset = (amo - 4) / 2 * GapMod -- Magic numbers for h = 1, amo do table.insert(Poly, {x = ScrW() / 2 + MMOffset.x * 2.5 + math.sin(Frac * (amo - h)) * (InitDistFromCenter - offset), y = ScrH() / 2 + MMOffset.y * 2.5 + math.cos(Frac * (amo - h)) * (InitDistFromCenter - offset)} ) // surface.SetTextPos(Poly[#Poly].x, Poly[#Poly].y) surface.DrawText(h .. " ") end surface.SetDrawColor(bg_color) surface.DrawPoly(Poly) end end end) local BottomGap = 27 -- Default hud offset for 1920x1280 hook.Add("HUDPaint", "HoloBuilderInfo", function() if HOLOBUILDER.Active then surface.SetFont("HoloBuilder") local Fields = { "Current Mode: " .. HOLOBUILDER.Mode, "-Selected Hologram Info-" } local SHoloId = HOLOBUILDER.SelectedHolo if isnumber(SHoloId) then local SHolo = HOLOBUILDER.Holograms[SHoloId] table.Add(Fields, { "Name: " .. SHolo.Name, "Id: " .. SHolo.Id, "Pos: " .. tostring(SHolo.Pos), }) else table.Add(Fields, { "No holo selected" }) end -- Prepare sizes local Height = 23 * (#Fields) + 4 local Width = 0 for k,e in pairs(Fields) do local size, _ = surface.GetTextSize(e) if size > Width then Width = size end end Width = Width + 8 surface.SetDrawColor(bg_color) surface.DrawRect(ScrW() / 2 - Width / 2, ScrH() - BottomGap - Height, Width, Height) surface.SetTextColor(color_white) for k,e in pairs(Fields) do local sizeX, sizeY = surface.GetTextSize(e) surface.SetTextPos(ScrW() / 2 - sizeX / 2, ScrH() - BottomGap - Height - sizeY / 2 + 23 * (k - 0.55) + 2) surface.DrawText(e) end --surface.SetDrawColor(255, 0, 0, 255) --surface.DrawRect(0, ScrH() - BottomGap - 2, ScrW(), 2) end end)
local function reject() return false end local function set_broken(cell) local vid = random_surface(64, 64) resize_image(vid, 1, 1) cell.types = {{}, {}} cell:set_content(vid) cell.row:invalidate() end local function set_dead(cell, source, status) set_broken(cell) if #status.last_words > 0 then cell:set_error(status.last_words) end return false end return function(row, cfg, identifier) local argstr = "capture" if type(identifier) == "number" then argstr = "no_uvc:capture:device=" .. tostring(identifier) elseif type(identifier) == "string" then argstr = "capture:" .. identifier end local res = pipeworld_cell_template("image", row, cfg) local vid, aid = launch_avfeed(argstr, "decode", pipeworld_segment_handler(res, { segment_request = reject, registered = reject, terminated = set_dead } ) ) if valid_vid(vid) then res.types = {{"video_buffer_handle", "audio_buffer_handle"}} res:set_content(vid, aid) else set_broken(res) end return res end
----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- CLASS DECLARATION -------------------------------------------------------- local _T = {}; _T.__index = _T; --TODO cross reference w/ c_client/storage.cpp -> OUT-OF-DATE _T.names = {"DOCUMENTS", "LAST_REMOVE_DENTRY", "USER_AUTHENTICATION", "STATIONED_USERS", "TO_SYNC_KEYS", "OUT_OF_SYNC_KEYS", "AGENT_KEY_OOO_GCV", "OOO_KEY", "OOO_DELTA", "OOO_DELTA_VERSION", "DELTA_COMMITTED", "DIRTY_KEYS", "FIXLOG", "AGENT_PERMISSONS", "AGENT_SUBSCRIPTIONS", "DELTAS", "DIRTY_DELTAS", "SUBSCRIBER_DELTA_VERSIONS", "AGENT_SENT_DELTAS", "GCV_SUMMARIES", "REPLICATION_CHANNELS", "DEVICE_CHANNELS", "USER_CHANNEL_PERMISSIONS", "USER_CHANNEL_SUBSCRIPTIONS", "USER_CACHED_KEYS", "SUBSCRIBER_LATENCY_HISTOGRAM", "AGENT_PROCESSED", "AGENT_INFO", "CONNECTION_STATUS", "GEO_NODES", "AGENT_CREATEDS", "AGENT_WATCH_KEYS", "KEY_AGENT_VERSION", "DEVICE_SUBSCRIBER_VERSION", "PER_KEY_SUBSCRIBER_VERSION", "KEY_REPLICATION_CHANNELS", "DELTA_NEED_REORDER", "DELTA_NEED_GC_REORDER", "REMOVE_REFERENCE_DELTA", "KEY_INFO", "CACHED_KEYS", "LRU_KEYS", "LRU_KEYS", "KEY_GC_SUMMARY_VERSION_LIST"}; return _T;
require("prototypes.recipe") data:extend({ { type = "custom-input", name = "bluebuild-autobuild", key_sequence = "b", consuming = "none" },{ type = "custom-input", name = "bluebuild-autodemo", key_sequence = "n", consuming = "none" } })
describe('#uint', function() local uint local random_uintstr setup(function() uint = require"novus.util.uint" function random_uintstr() local out = {} for i = 1, 19 do out[i] = math.random(0, 9) end return table.concat(out) end end) describe('touint', function() it('converts strings into encoded uint64s', function() assert.are.equals( -1, uint"18446744073709551615" ) assert.are.equals( 'number', type(uint(random_uintstr())) ) end) it('converts floats into integers', function() assert.are.equal( uint(9.2233720368548e+18), -9223372036854751232 ) end) end) describe('timestamp', function() it('gets the timestamp from a snowflake', function() assert.are.equals( uint.timestamp(21154535154122752), 1425114034 ) end) it('always produces a number if uint(_) is a number', function() assert.is_number( uint.timestamp(random_uintstr()) ) end) end) describe('fromtime', function() it('converts a timestamp into a snowflake', function() assert.are.equal(uint.fromtime(1420070738), 1417674752000) end) it('throws away the inc, pid and worker part of the snowflake', function() assert.are.not_equal( uint.fromtime(uint.timestamp(21154535154122752)), 21154535154122752 ) end) end) describe('sorts', function() it('sorts positive numbers A < B', function() assert.True(uint.id_sort(1, 2)) assert.False(uint.id_sort(-1, 2)) end) it('sorts in the uint64 range', function() assert.True(uint.id_sort(1, random_uintstr())) end) end) end)
function Boton(text,x,y,w,h,bg_ima,bg_ima_hover) local self = {} self.pos = {} self.pos.x = x self.pos.y = y self.text = text local iw = w or 0 local ih = h or 0 if bg_ima then iw = bg_ima:getWidth() ih = bg_ima:getHeight() end self.w = math.max(love.graphics.getFont():getWidth( text )+40,iw) self.h = math.max(love.graphics.getFont():getHeight( text )+20,ih) self.mw = math.floor(self.w/2) self.mh = math.floor(self.h/2) self.rgba_text = {0.9,0.9,0.9,1} self.rgba = {0.1,0.1,0.1,1} self.rgba_hover = {0.15,0.15,0.15,1} self.rgba_text_hover = nil local px = 0 local py = 0 function self.setPointerPos(x,y) px = x py = y end function self.setAlpha(normal, hover) self.rgba_hover[4] = hover self.rgba[4] = normal end function self.isPointerInside() if px < self.pos.x+(self.w-self.mw) and py < self.pos.y+(self.h-self.mh) then if px > self.pos.x-self.mw and py > self.pos.y-self.mh then return true end end return false end function self.draw() local rgb_a_bg = { self.rgba[1], self.rgba[2], self.rgba[3], self.rgba[4] } local rgb_a_text = { self.rgba_text[1], self.rgba_text[2], self.rgba_text[3] } local mdx = 0 local mdy = 0 if self.isPointerInside() then if not self.rgba_text_hover then rgb_a_text[1] = math.min(self.rgba_text[1]+0.5) rgb_a_text[2] = math.min(self.rgba_text[2]+0.5) rgb_a_text[3] = math.min(self.rgba_text[3]+0.5) else rgb_a_text[1] = self.rgba_text_hover[1] rgb_a_text[2] = self.rgba_text_hover[2] rgb_a_text[3] = self.rgba_text_hover[3] rgb_a_text[4] = self.rgba_text_hover[4] end if self.rgba_hover then rgb_a_bg[1] = self.rgba_hover[1] rgb_a_bg[2] = self.rgba_hover[2] rgb_a_bg[3] = self.rgba_hover[3] rgb_a_bg[4] = self.rgba_hover[4] end end love.graphics.setFont(love.graphics.getFont()) if not bg_ima then love.graphics.setColor(rgb_a_bg[1],rgb_a_bg[2],rgb_a_bg[3],rgb_a_bg[4]) love.graphics.rectangle('fill',self.pos.x-self.mw,self.pos.y-self.mh,self.w,self.h,15,15,8) else local inside = self.isPointerInside() if not bg_ima_hover then love.graphics.setColor(0.5,0.5,0.5,rgb_a_bg[4]) if inside then love.graphics.setColor(1,1,1,rgb_a_bg[4]) end love.graphics.draw(bg_ima,self.pos.x-self.mw,self.pos.y-self.mh) else if inside then love.graphics.setColor(1,1,1,rgb_a_bg[4]) love.graphics.draw(bg_ima_hover,self.pos.x-self.mw,self.pos.y-self.mh) else love.graphics.setColor(0.7,0.7,0.7,rgb_a_bg[4]) love.graphics.draw(bg_ima,self.pos.x-self.mw,self.pos.y-self.mh) end end end if self.isPointerInside() then love.graphics.setColor(0,0,0,1) love.graphics.printf(self.text,self.pos.x-self.mw+1,self.pos.y-self.mh+10+4+2,self.w,'center') end love.graphics.setColor(rgb_a_text[1],rgb_a_text[2],rgb_a_text[3],rgb_a_text[4]) love.graphics.printf(self.text,self.pos.x-self.mw,self.pos.y-self.mh+10+mdy,self.w,'center') end return self end
-- automatically generated by the FlatBuffers compiler, do not modify -- namespace: ExtraInfo local flatbuffers = require('flatbuffers') local ReqBody = {} -- the module local ReqBody_mt = {} -- the class metatable function ReqBody.New() local o = {} setmetatable(o, {__index = ReqBody_mt}) return o end function ReqBody.GetRootAsReqBody(buf, offset) if type(buf) == "string" then buf = flatbuffers.binaryArray.New(buf) end local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) local o = ReqBody.New() o:Init(buf, n + offset) return o end function ReqBody_mt:Init(buf, pos) self.view = flatbuffers.view.New(buf, pos) end function ReqBody.Start(builder) builder:StartObject(0) end function ReqBody.End(builder) return builder:EndObject() end return ReqBody -- return the module
repoRoot = os.getcwd() include ("BuildConfig.lua") -- Custom library: include ("Premake/Library.lua") workspace "SAMPEDGEngine" location "Build" platforms { "x86", "x64" } configurations { "Debug", "Release" } -- Linux specific configuration. if os.host() == "linux" then defines { "LINUX" } end -- MSBuild specific configuration if string.match(_ACTION, "vs%d%d%d%d") ~= nil then filter {"system:windows"} systemversion(edge.getWindowsSDKVersion() .. ".0") end -- gmake specific configuration if _ACTION == "gmake" then links { "stdc++fs" } end -- Setup platforms: filter "platforms:*32" architecture "x86" filter "platforms:*64" architecture "x86_64" -- Setup configurations: filter "configurations:Debug" defines { "DEBUG", "_DEBUG", "SAMP_EDGENGINE_DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter {} -- Projects: include ("Engine/Premake5Build.lua") include ("ServerCore/Premake5Build.lua") -- TODO: include other project files here -- Extensions: if userConfig.build.extensions then group "Extensions" include("Extensions/Premake5Build.lua") end -- Examples: if userConfig.build.examples then group "Examples" include("Examples/Premake5Build.lua") end -- UnitTests: if userConfig.build.unitTests then group "UnitTests" include("UnitTests/Premake5Build.lua") end -- ThirdParty: if userConfig.build.thirdParty then group "ThirdParty" include("ThirdParty/Premake5Build.lua") end
local battery = peripheral.find("thermal:energy_cell") local energy = battery.getEnergy print(energy)
C_ItemUpgrade = {} ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.CanUpgradeItem) ---@param baseItem ItemLocationMixin ---@return boolean isValid function C_ItemUpgrade.CanUpgradeItem(baseItem) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.ClearItemUpgrade) function C_ItemUpgrade.ClearItemUpgrade() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.CloseItemUpgrade) function C_ItemUpgrade.CloseItemUpgrade() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.GetItemHyperlink) ---@return string link function C_ItemUpgrade.GetItemHyperlink() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.GetItemUpgradeCurrentLevel) ---@return number itemLevel ---@return boolean isPvpItemLevel function C_ItemUpgrade.GetItemUpgradeCurrentLevel() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.GetItemUpgradeEffect) ---@param effectIndex number ---@param numUpgradeLevels? number ---@return string outBaseEffect ---@return string outUpgradedEffect function C_ItemUpgrade.GetItemUpgradeEffect(effectIndex, numUpgradeLevels) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.GetItemUpgradeItemInfo) ---@return ItemUpgradeItemInfo itemInfo function C_ItemUpgrade.GetItemUpgradeItemInfo() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.GetItemUpgradePvpItemLevelDeltaValues) ---@param numUpgradeLevels number ---@return number currentPvPItemLevel ---@return number upgradedPvPItemLevel function C_ItemUpgrade.GetItemUpgradePvpItemLevelDeltaValues(numUpgradeLevels) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.GetNumItemUpgradeEffects) ---@return number numItemUpgradeEffects function C_ItemUpgrade.GetNumItemUpgradeEffects() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.SetItemUpgradeFromCursorItem) function C_ItemUpgrade.SetItemUpgradeFromCursorItem() end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.SetItemUpgradeFromLocation) ---@param itemToSet ItemLocationMixin function C_ItemUpgrade.SetItemUpgradeFromLocation(itemToSet) end ---[Documentation](https://wowpedia.fandom.com/wiki/API_C_ItemUpgrade.UpgradeItem) ---@param numUpgrades number function C_ItemUpgrade.UpgradeItem(numUpgrades) end ---@class ItemUpgradeCurrencyCost ---@field cost number ---@field currencyID number ---@class ItemUpgradeItemInfo ---@field iconID number ---@field name string ---@field itemUpgradeable boolean ---@field displayQuality number ---@field currUpgrade number ---@field maxUpgrade number ---@field upgradeLevelInfos ItemUpgradeLevelInfo[] ---@class ItemUpgradeLevelInfo ---@field upgradeLevel number ---@field displayQuality number ---@field itemLevelIncrement number ---@field levelStats ItemUpgradeStat[] ---@field costsToUpgrade ItemUpgradeCurrencyCost[] ---@field failureMessage string|nil ---@class ItemUpgradeStat ---@field displayString string ---@field statValue number ---@field active boolean
AddCSLuaFile() SWEP.Base = "weapon_gwbase" SWEP.Name = "Shockwave" SWEP.AbilitySound = "ambient/energy/zap1.wav" SWEP.AbilityRange = 300 SWEP.AbilityShowTargetHalos = true SWEP.AbilityDuration = 4 SWEP.AbilityCastTime = 0.5 SWEP.AbilityDescription = "Somehow you can emit a shockwave that stuns all seekers within $AbilityRange units for $AbilityDuration seconds." function SWEP:Ability() local targets = self:GetSeekersInRange(self.AbilityRange, true) -- dont use ability if no target was found if #targets == 0 then return GW_ABILTY_CAST_ERROR_NO_TARGET end if not SERVER then return end local effectdata = EffectData() effectdata:SetEntity(self:GetOwner()) effectdata:SetRadius(self.AbilityRange) effectdata:SetMagnitude(self.AbilityCastTime) util.Effect("gw_shockwave", effectdata, true, true) for _,v in pairs(targets) do local distanceRatio = v:GetPos():Distance(self:GetOwner():GetPos()) / self.AbilityRange timer.Simple(distanceRatio * self.AbilityCastTime, function() if IsValid(v) then local effect = EffectData() effect:SetEntity(v) effect:SetMagnitude(self.AbilityDuration) util.Effect("gw_stunned", effect, true, true) v:GWApplyStun(self.AbilityDuration) end end) end end
_APL_LEVEL=arg[1] and tonumber(arg[1]) or 2 apl=require"apl" print ("APL Level ".._APL_LEVEL) apl:import() idiom = require "finnaplidiom" local char = string.char local function Str(x,y) if type(x)=='table' then return char(unpack(x)) else return char(x) end end apl.register(1,Str,'§','Str') local tests = {} tests[0] = [[ j←5 3 1 _A←⍳10 A[2] A[5]←-5 !10 '%24.16f'⍕1○○÷6 (∘1)⍕∘1 §65 ⍟¯1 ⍕⍟¯1 ]] tests[1] = [[ j←⍒A←?10⍴100 A[j] A,0↑A[5]←-5 n←(0,⍳10)!10 f←2 3⍴¨5 4 ⊖f ⊃f 1 2 3○○÷6 1 4 ○÷¯1 ¯2 ¯3○⎕←1 2 3○○÷6 1 4 (∘1)⍕∘1 §32+⍳94 ⍟¯1,0○1.4 0 1∘.∨0 1 0 1∘.∧0 1 0 1∘.⍱0 1 0 1∘.⍲0 1 10|(⍳9)∘.+⍳9 'raw'⍕10|(⍳9)∘.+⍳9 10⊥⍳9 (10⍴10)⊤!10 10|(⍳9)∘.×⍳9 10|(⍳9)∘.-⍳9 10|(⍳9)∘.<⍳9 10|(⍳9)∘.≤⍳9 10|(⍳9)∘.=⍳9 10|(⍳9)∘.>⍳9 10|(⍳9)∘.≠⍳9 10|(⍳9)∘.⌈⍳9 10|(⍳9)∘.⌊⍳9 10|(⍳9)∘.|⍳9 ⌈(⍳9)∘.÷⍳9 ⌊(⍳9)∘.÷⍳9 1 2 3=1 3⍴1 2 3 1 2 3≡1 3⍴1 2 3 ⍺←⍳2 ⋄ y←⍺+2 ⋄ x←⍺-y×⍺⌹y x+.×y ⌹3 4 +/(⍳10)⋆2 ⌽+\(⍳10)⋆2 ⌈/0⍴0 ]] tests[2] = [[ 2 3⍴¨5 4 j←⍒A←?10⍴100 A[j] A,0↑A[5]←-5 n←(0,⍳10)!10 f←n⍪?n ⊂f ⊖f ⊖⊂f 1 2 3○○÷6 1 4 ○÷¯1 ¯2 ¯3○⎕←1 2 3○○÷6 1 4 (∘1)⍕∘1 §32+⍳94 ⍟¯1,0○1.4 0 1∘.∨0 1 0 1∘.∧0 1 0 1∘.⍱0 1 0 1∘.⍲0 1 10|(⍳9)∘.+⍳9 'raw'⍕10|(⍳9)∘.+⍳9 '%d'⍕10⊥10|(⍳9)∘.+⍳9 10 10⊤10|(⍳9)∘.+⍳9 10|(⍳9)∘.×⍳9 10|(⍳9)∘.-⍳9 10|(⍳9)∘.<⍳9 10|(⍳9)∘.≤⍳9 10|(⍳9)∘.=⍳9 10|(⍳9)∘.>⍳9 10|(⍳9)∘.≠⍳9 10|(⍳9)∘.⌈⍳9 10|(⍳9)∘.⌊⍳9 10|(⍳9)∘.|⍳9 ⌈(⍳9)∘.÷⍳9 ⌊(⍳9)∘.÷⍳9 1 2 3=1 3⍴1 2 3 1 2 3≡1 3⍴1 2 3 +/(⍳10)⋆2 ⌽+\(⍳10)⋆2 (⍳3)⌹3 4⍴⍳12 (⍳4)⌹⍉3 4⍴⍳12 ]] aplchars = [[! + , . / < = > ? \ § ¨ × ÷ ↑ ↓ ∇ ∊ − ∘ ∣ ∧ ∨ ∼ ≠ ≡ ≤ ≥ ⊂ ⊃ ⊖ ⊤ ⊥ ⋆ ⌈ ⌊ ⌹ ⌽ ⌿ ⍀ ⍉ ⍋ ⍎ ⍒ ⍕ ⍟ ⍪ ⍱ ⍲ ⍳ ⍴ ⎕ ○]] apl_tally = {} lua_tally = {} apl_omitted, lua_omitted = {},{} for k in aplchars:gmatch"%S+" do apl_omitted[k]=true end for k in pairs(apl) do lua_omitted[k]=true end function occurs(S,k) local c,j,i=-1,0 repeat i,j = S:find(k,j+1,true); c=c+1 until not j return c end print"" for S in tests[_APL_LEVEL]:gmatch"[^\n]+" do if S:match"%S" then f=apl(S) print(' '..S..' → '..lua(f)) local res=f() if res then print(tostring(res)) end for k in aplchars:gmatch"%S+" do local c=occurs(S,k) if c>0 then apl_tally[k] = (apl_tally[k] or 0) + c apl_omitted[k] = nil end end for k in pairs(apl) do c=occurs(lua(f),k) if c>0 and not (',.'):find(k) then lua_tally[k] = (lua_tally[k] or 0) + c lua_omitted[k] = nil end end end end t={} for k,v in pairs(apl) do if lua_tally[k] then t[k..":"..(lua_tally[k] or 0)]=true end end print "\nTally of Lua functions tested" help(t) print "\nThe following Lua functions are not represented" help(lua_omitted) t={} for k in aplchars:gmatch"%S+" do if apl_tally[k] then t[k..":"..(apl_tally[k] or 0)]=true end end print "\nTally of APL functions tested" help(t) print "\nThe following APL functions are not represented" help(apl_omitted)
local u = require("modules.utils.utils") local sorters = require("telescope.sorters") TelescopeMapArgs = TelescopeMapArgs or {} local map_tele = function(key, f, options, buffer) local map_key = vim.api.nvim_replace_termcodes(key .. f, true, true, true) TelescopeMapArgs[map_key] = options or {} local mode = "n" local rhs = string.format( "<cmd>lua require('modules.plugins.telescope.config')['%s'](TelescopeMapArgs['%s'])<CR>", f, map_key ) local map_options = { noremap = true, silent = true, } if not buffer then u.map(mode, key, rhs, map_options) else u.buf_map(mode, key, rhs, map_options) end end -- generic mappings --find * commands/mappings u.command("Files", "Telescope find_files theme=ivy") u.command("Rg", "Telescope live_grep theme=get_ivy") u.command("GrepStr", "Telescope grep_string theme=ivy") u.command("BLines", "Telescope current_buffer_fuzzy_find") u.command("History", "Telescope oldfiles") u.command("Buffers", "Telescope buffers") --git * commands u.command("BCommits", "Telescope git_bcommits") u.command("Commits", "Telescope git_commits") u.command("Branchs", "Telescope git_branches") u.command("GStatus", "Telescope git_status") --help commands u.command("HelpTags", "Telescope help_tags") u.command("ManPages", "Telescope man_pages") --- LSP Commands u.command("LspRef", "Telescope lsp_references") u.command("LspDef", "Telescope lsp_definitions") u.command("LspSym", "Telescope lsp_workspace_symbols") -- u.command("LspAct", "Telescope lsp_code_actions theme=cursor") u.command("LspAct", "lua vim.lsp.buf.code_action()") u.command("FixSuggestion", "lua vim.lsp.buf.range_code_action()") -- Telescope lsp_range_code_actions theme=cursor') -- local map = vim.api.nvim_set_keymap u.nmap("<Leader>T", ":Telescope<CR>") u.nmap("<C-p>", "<cmd>lua require'telescope'.extensions.project.project{display_type = 'full'}<cr>") -- u.nmap('<Leader>p', ":Telescope file_browser path='%:p:h'<cr>") --not working -- u.nmap('<Leader>e', '<cmd>lua require\'modules.plugins.telescope.config\'.project_files({theme=ivy})<cr>') map_tele("<space>e", "project_files", { theme = "ivy" }) map_tele("<space>p", "file_browser") map_tele("<space>fz", "search_only_certain_files") map_tele("<space>fd", "fd") map_tele("<space>dl", "Telescope diagnostics theme=ivy") map_tele("<space>gw", "grep_string", { short_path = true, word_match = "-w", only_sort_text = true, layout_strategy = "vertical", sorter = sorters.get_fzy_sorter(), }) u.nmap("<Leader>sp", "<cmd>Rg<CR>") u.nmap("<Leader>fs", "<cmd>GrepStr<CR>") u.nmap("<Leader>b", "<cmd>Buffers<CR>") u.nmap("<Leader>o", "<cmd>History<CR>") -- lsp mappings/commands u.map("n", "<Leader>r", "<cmd>LspRef<CR>") u.map("n", "<Leader>w", "<cmd>FixSuggestion<CR>") u.map("n", "<Leader>cc", "<cmd>LspAct<CR>") -- u.nmap('<Leader>t', ':Telescope treesitter<CR>') -- u.map('n', '<Leader>p', "<cmd>lua require 'telescope'.extensions.file_browser.file_browser({cwd = require'telescope.utils'.buffer_dir()})<CR>") -- u.map('n', '<Leader>H', ':HelpTags<CR>') -- u.map('n', '<leader>m', ':ManPages<CR>') -- u.nmap('<Leader>gc', '<cmd>Commits<CR>') -- u.nmap('<Leader>gp', '<cmd>BCommits<CR>') -- u.nmap('<Leader>gb', '<cmd>Branchs<CR>') -- u.nmap('<Leader>gs', '<cmd>GStatus<CR>')
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor. krayt_dragon_tissue_rare = { minimumLevel = 0, maximumLevel = -1, customObjectName = "", directObjectTemplate = "object/tangible/component/weapon/blaster_power_handler_enhancement_krayt.iff", craftingValues = { {"maxdamage",70,165,0}, {"mindamage",35,80,0}, {"attackspeed",0,-1.2,1}, {"useCount",1,13,0}, }, customizationStringNames = {}, customizationValues = {} } addLootItemTemplate("krayt_dragon_tissue_rare", krayt_dragon_tissue_rare)
-- Copyright (C) 2013 Piotr Gaertig -- SHA1 shortcut function handler for nginx-big-upload pipeline -- This is stateless handler, it saves .sha1 file with SHA1 context data. -- yarshure hack sha1 to md5 local ffi = require('ffi') local tonumber = tonumber local string = string local ngx = ngx local table = table local io = io local assert = assert local concat = table.concat local util = require('util') module(...) function validmd5hex(md5hex) return #md5hex <= 32 and string.match(md5hex, "^%x+$") end local crypto = ffi.load('crypto') -- extracted from https://github.com/openssl/openssl/blob/master/crypto/sha/sha.h ffi.cdef[[ typedef struct MD5state_st { unsigned int A,B,C,D; unsigned int Nl,Nh; unsigned int data[16]; unsigned int num; } MD5_CTX; int MD5_Init(MD5_CTX *c); int MD5_Update(MD5_CTX *c, const void *data, size_t len); int MD5_Final(unsigned char *md, MD5_CTX *c); ]] local function md5ctx_from_file(path) end local function md5ctx_to_file(file_path, md5ctx, offset) local out = assert(io.open(file_path..'.md5ctx', "wb")) local binctx = ffi.string(md5ctx, 92) -- 96? out:write(offset) out:write("\n") out:write(binctx) assert(out:close()) end local function md5ctx_from_file(file_path) local inp = io.open(file_path..'.md5ctx', "rb") if inp then file_size = tonumber(inp:read("*line")) file_data = inp:read("*all") assert(inp:close()) -- ffi.copy(file_data, shactx, 96) return file_size, ffi.cast("MD5_CTX*", file_data) end return end function handler(storage_path) return { on_body_start = function (self, ctx) self.md5_ctx = ffi.new("MD5_CTX") self.skip_bytes = 0 if not ctx.first_chunk then local file_path = concat({storage_path, ctx.id}, "/") -- file based backends not initialized yet self.real_size, self.sha1_ctx = md5ctx_from_file(file_path) --overlapping chunk upload, need to skip repeated data self.skip_bytes = self.real_size - ctx.range_from return end if crypto.MD5_Init(self.md5_ctx) == 0 then return string.format("md5 initialization failed") end ngx.log(ngx.DEBUG, "on_body_start") end, on_body = function (self, ctx, body) if self.skip_bytes > 0 then -- skip overlaping bytes if self.skip_bytes > #body then -- skip this entire body part self.skip_bytes = self.skip_bytes - #body return else body = body:sub(self.skip_bytes+1) self.skip_bytes = 0 end end ngx.log(ngx.DEBUG, "on_body") if body and #body > 0 then if crypto.MD5_Update(self.md5_ctx, body, #body) == 0 then return string.format("MD5 update failed") end end end, on_body_end = function (self, ctx) if self.skip_bytes == 0 then -- In overlapping chunk upload scenario. Save and return chunk's SHA-1 result only if there is no more bytes to skip, -- because we only know SHA-1 of farthest chunk uploaded and nothing in between. self.real_size = ctx.range_from + ctx.content_length md5ctx_to_file(ctx.file_path, self.md5_ctx, self.real_size) ngx.log(ngx.DEBUG, "on_body_end"..self.real_size) local md = ffi.new("char[?]", 16) --? if crypto.MD5_Final(md, self.md5_ctx) == 0 then return string.format("MD5 finalization failed") end ngx.log(ngx.DEBUG, "on_body_end") local hexresult = util.tohex(ffi.string(md, 16)) if ctx.md5 then -- already provided by client, let's check it if ctx.md5 ~= hexresult then return {400, string.format("Chunk MD5 mismatch client=[%s] server=[%s]", ctx.md5, hexresult)} end end ngx.log(ngx.DEBUG, "on_body_end") ctx.md5 = hexresult end if ctx.md5 then ngx.header['X-MD5'] = ctx.md5 end end } end
local iPN = ...; assert(iPN,"[Graphics/PaneDisplay text.lua] No PlayerNumber Provided."); local PaneItems = Def.ActorFrame{} local DanceGames = { ["dance"] = true, ["pump"] = true, ["techno"] = true, ["para"] = true, ["maniax"] = true, ["ds3ddx"] = true, ["ez2"] = true } local gm = GAMESTATE:GetCurrentGame():GetName() local function GetRadarData( pnPlayer, rcRadarCategory ) local tRadarValues; local StepsOrTrail; local fDesiredValue = 0; if GAMESTATE:GetCurrentSteps( pnPlayer ) then StepsOrTrail = GAMESTATE:GetCurrentSteps( pnPlayer ); fDesiredValue = StepsOrTrail:GetRadarValues( pnPlayer ):GetValue( rcRadarCategory ); elseif GAMESTATE:GetCurrentTrail( pnPlayer ) then StepsOrTrail = GAMESTATE:GetCurrentTrail( pnPlayer ); fDesiredValue = StepsOrTrail:GetRadarValues( pnPlayer ):GetValue( rcRadarCategory ); else StepsOrTrail = nil; end; return fDesiredValue; end; local function CreatePaneDisplayItem( _pnPlayer, _sLabel, _rcRadarCategory ) return Def.ActorFrame { Def.BitmapText { Font="_Bold"; Text=ToUpper(THEME:GetString("PaneDisplay",_sLabel) .. ":"); InitCommand=function(self) self:horizalign(left) end; OnCommand=function(self) self:zoom(0.9):diffuse(color("0.9,0.9,0.9")):shadowlength(1) end; }; Def.BitmapText { Font="_Medium"; Text=string.format("%04i", 0); InitCommand=function(self) self:x(130):horizalign(right) end; OnCommand=function(self) self:zoom(0.9):shadowlength(1) end; CurrentSongChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentStepsP1ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentStepsP2ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentTrailP1ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentTrailP2ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentCourseChangedMessageCommand=function(self) self:playcommand("Set") end; SetCommand=function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:settextf("%i", 0); else self:settextf("%i", GetRadarData( _pnPlayer, _rcRadarCategory ) ); end end; }; }; end; local function CreatePaneDisplayGraph( _pnPlayer, _sLabel, _rcRadarCategory ) return Def.ActorFrame { Def.BitmapText { Font="_Medium"; Text=_sLabel; InitCommand=function(self) self:horizalign(left) end; OnCommand=function(self) self:zoom(0.5):shadowlength(1) end; }; Def.Quad { InitCommand=function(self) self:x(12):zoomto(50,10):horizalign(left) end; OnCommand=function(self) self:diffuse(Color("Black")):shadowlength(1):diffusealpha(0.5) end; }; Def.Quad { InitCommand=function(self) self:x(12):zoomto(50,10):horizalign(left) end; OnCommand=function(self) self:shadowlength(0):diffuse(Color("Green")):diffusebottomedge(ColorLightTone(Color("Green"))) end; CurrentSongChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentStepsP1ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentStepsP2ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentTrailP1ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentTrailP2ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentCourseChangedMessageCommand=function(self) self:playcommand("Set") end; SetCommand=function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:stoptweening(); self:decelerate(0.2); self:zoomtowidth(0); else self:stoptweening(); self:decelerate(0.2); self:zoomtowidth( clamp(GetRadarData( _pnPlayer, _rcRadarCategory ) * 50,0,50) ); end end; }; Def.BitmapText { Font="_Medium"; InitCommand=function(self) self:x(14):zoom(0.5):halign(0) end; OnCommand=function(self) self:shadowlength(1):strokecolor(color("0.15,0.15,0.15,0.625")) end; CurrentSongChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentStepsP1ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentStepsP2ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentTrailP1ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentTrailP2ChangedMessageCommand=function(self) self:playcommand("Set") end; CurrentCourseChangedMessageCommand=function(self) self:playcommand("Set") end; SetCommand=function(self) local song = GAMESTATE:GetCurrentSong() local course = GAMESTATE:GetCurrentCourse() if not song and not course then self:settext("") else self:settext("%i%%", GetRadarData( _pnPlayer, _rcRadarCategory ) * 100 ); end end; }; }; end; --[[ Numbers ]] if DanceGames[gm] == true then PaneItems[#PaneItems+1] = Def.ActorFrame { -- Left CreatePaneDisplayItem( iPN, "Taps", 'RadarCategory_TapsAndHolds' ) .. { InitCommand=function(self) self:x(-128+16+8):y(-14) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.4):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Jumps", 'RadarCategory_Jumps' ) .. { InitCommand=function(self) self:x(-128+16+8):y(-14+24) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.5):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Holds", 'RadarCategory_Holds' ) .. { InitCommand=function(self) self:x(-128+16+8):y(-14+24*2) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.6):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Mines", 'RadarCategory_Mines' ) .. { InitCommand=function(self) self:x(-128+16+8):y(-14+24*3) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.7):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, -- Center CreatePaneDisplayItem( iPN, "Hands", 'RadarCategory_Hands' ) .. { InitCommand=function(self) self:x(50):y(-14) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.4):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Rolls", 'RadarCategory_Rolls' ) .. { InitCommand=function(self) self:x(50):y(-14+24) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.5):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Lifts", 'RadarCategory_Lifts' ) .. { InitCommand=function(self) self:x(50):y(-14+24*2) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.6):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Fakes", 'RadarCategory_Fakes' ) .. { InitCommand=function(self) self:x(50):y(-14+24*3) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.7):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; } } else PaneItems[#PaneItems+1] = Def.ActorFrame { CreatePaneDisplayItem( iPN, "Notes", 'RadarCategory_TapsAndHolds' ) .. { InitCommand=function(self) self:x(-128+16+8):y(-14) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.4):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; }, CreatePaneDisplayItem( iPN, "Holds", 'RadarCategory_Holds' ) .. { InitCommand=function(self) self:x(50):y(-14) end; OnCommand=function(self) self:zoomy(0.8):diffusealpha(0):sleep(0.6):linear(0.3):diffusealpha(1):zoomy(1) end; OffCommand=function(self) self:linear(0.1):diffusealpha(0):zoomy(0.8) end; } } end return Def.ActorFrame { PaneItems }
-- vsnip setup: https://github.com/hrsh7th/nvim-cmp/wiki/Example-mappings#vim-vsnip local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end local feedkey = function(key, mode) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) end -- Setup nvim-cmp. local cmp = require'cmp' cmp.setup({ snippet = { -- REQUIRED - you must specify a snippet engine expand = function(args) vim.fn["vsnip#anonymous"](args.body) -- For `vsnip` users. end, }, window = { -- completion = cmp.config.window.bordered(), documentation = cmp.config.window.bordered(), }, mapping = cmp.mapping.preset.insert({ ['<C-b>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.abort(), ['<CR>'] = cmp.mapping.confirm({ select = true }), -- Accept currently selected item. Set `select` to `false` to only confirm explicitly selected items. -- ... Your other mappings ... ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif vim.fn["vsnip#available"](1) == 1 then feedkey("<Plug>(vsnip-expand-or-jump)", "") elseif has_words_before() then cmp.complete() else fallback() -- The fallback function sends a already mapped key. In this case, it's probably `<Tab>`. end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() elseif vim.fn["vsnip#jumpable"](-1) == 1 then feedkey("<Plug>(vsnip-jump-prev)", "") end end, { "i", "s" }), }), sources = cmp.config.sources({ { name = 'vsnip' }, -- For vsnip users. { name = 'nvim_lsp' }, { name = 'nvim_lsp_signature_help' }, }, { { name = 'buffer' }, }) }) -- -- Set configuration for specific filetype. -- cmp.setup.filetype('gitcommit', { -- sources = cmp.config.sources({ -- { name = 'cmp_git' }, -- You can specify the `cmp_git` source if you were installed it. -- }, { -- { name = 'buffer' }, -- }) -- }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', { mapping = cmp.mapping.preset.cmdline(), sources = { { name = 'buffer' }, { name = 'nvim_lsp_document_symbol' } } }) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = 'path' }, }, { { name = 'cmdline' } }) }) -- HACK FIX, REMOVE local opts = { noremap=true, silent=true } -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end --Enable completion triggered by <c-x><c-o> buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- See `:help vim.lsp.*` for documentation on any of the below functions buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'gv', '<C-W>v<cmd>lua vim.lsp.buf.definition()<CR>', opts) -- I never use split anyways buf_set_keymap('n', 'gs', '<C-W>v<cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts) end -- Setup lspconfig. local capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) -- Replace <YOUR_LSP_SERVER> with each lsp server you've enabled. require('lspconfig')['intelephense'].setup { capabilities = capabilities, on_attach = on_attach } require('lspconfig')['gopls'].setup{ capabilities = capabilities, on_attach = on_attach, cmd = {"gopls", "serve"}, settings = { gopls = { analyses = { unusedparams = true, }, staticcheck = true, }, }, } require('lspconfig')['vuels'].setup { capabilities = capabilities, on_attach = on_attach } require('lspconfig')['denols'].setup { capabilities = capabilities, on_attach = on_attach }
require 'torch' require 'nn' require 'optim' opt = { dataset = 'folder', batchSize = 128, loadSize = 64, fineSize = 64, ngf = 96, -- # of gen filters in first conv layer ndf = 96, -- # of discrim filters in first conv layer nThreads = 4, -- # of data loading threads to use niter = 25, -- # of iter at starting learning rate lr = 0.0002, -- initial learning rate for adam beta1 = 0.5, -- momentum term of adam ntrain = math.huge, -- # of examples per epoch. math.huge for full dataset display = 1, -- display samples while training. 0 = false display_id = 10, -- display window id. gpu = 1, -- gpu = 0 is CPU mode. gpu=X is GPU mode on GPU X name = 'experiment1', noise = 'normal', -- uniform / normal optimizer = 'sgd', load_cp = 0, } -- one-line argument parser. parses enviroment variables to override the defaults for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end print(opt) if opt.display == 0 then opt.display = false end torch.setdefaulttensortype('torch.FloatTensor') paths.dofile('data.lua') smn = torch.sum(mn) ---------------------------------------------------------------------------- local function weights_init(m) local name = torch.type(m) if name:find('Convolution') then m.weight:normal(0.0, 0.02) m:noBias() elseif name:find('BatchNormalization') then if m.weight then m.weight:normal(1.0, 0.02) end if m.bias then m.bias:fill(0) end end end local nc = 3 local nz = opt.nz local ndf = opt.ndf local ngf = opt.ngf local real_label = 1 local fake_label = 0 local SpatialBatchNormalization = nn.SpatialBatchNormalization local SpatialConvolution = nn.SpatialConvolution local SpatialFullConvolution = nn.SpatialFullConvolution local netG = nn.Sequential() -- input is (nc) x 64 x 64 netG:add(SpatialConvolution(nc, ngf, 4, 4, 2, 2, 1, 1)) netG:add(nn.LeakyReLU(0.2, true)) -- state size: (ngf) x 32 x 32 netG:add(SpatialConvolution(ngf, ngf * 2, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ngf*2) x 16 x 16 netG:add(SpatialConvolution(ngf * 2, ngf * 4, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 4)):add(nn.LeakyReLU(0.2, true)) -- state size: (ngf*4) x 8 x 8 netG:add(SpatialConvolution(ngf * 4, ngf * 8, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 8)):add(nn.LeakyReLU(0.2, true)) -- state size: (ngf*8) x 4 x 4 -- netG:add(SpatialConvolution(ngf * 8, ngf * 16, 4, 4, 2, 2, 1, 1)) -- netG:add(SpatialBatchNormalization(ndf * 16)):add(nn.LeakyReLU(0.2, true)) -- state size: (ngf*16) x 2 x 2 -- netG:add(SpatialFullConvolution(ngf*16, ngf * 8, 4, 4)) -- netG:add(SpatialBatchNormalization(ngf * 8)):add(nn.ReLU(true)) -- state size: (ngf*8) x 4 x 4 netG:add(SpatialFullConvolution(ngf * 8, ngf * 4, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 4)):add(nn.ReLU(true)) -- state size: (ngf*4) x 8 x 8 netG:add(SpatialFullConvolution(ngf * 4, ngf * 2, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf * 2)):add(nn.ReLU(true)) -- state size: (ngf*2) x 16 x 16 netG:add(SpatialFullConvolution(ngf * 2, ngf, 4, 4, 2, 2, 1, 1)) netG:add(SpatialBatchNormalization(ngf)):add(nn.ReLU(true)) -- state size: (ngf) x 32 x 32 netG:add(SpatialFullConvolution(ngf, nc, 4, 4, 2, 2, 1, 1)) netG:add(nn.Tanh()) -- state size: (nc) x 64 x 64 netG:apply(weights_init) local netD = nn.Sequential() -- input is (nc) x 64 x 64 netD:add(SpatialConvolution(nc, ndf, 4, 4, 2, 2, 1, 1)) netD:add(nn.LeakyReLU(0.2, true)) -- state size: (ndf) x 32 x 32 netD:add(SpatialConvolution(ndf, ndf * 2, 4, 4, 2, 2, 1, 1)) netD:add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*2) x 16 x 16 netD:add(SpatialConvolution(ndf * 2, ndf * 4, 4, 4, 2, 2, 1, 1)) netD:add(SpatialBatchNormalization(ndf * 4)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*4) x 8 x 8 netD:add(SpatialConvolution(ndf * 4, ndf * 8, 4, 4, 2, 2, 1, 1)) netD:add(SpatialBatchNormalization(ndf * 8)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*8) x 4 x 4 netD:add(SpatialConvolution(ndf * 8, 1, 4, 4)) netD:add(nn.Sigmoid()) -- state size: 1 x 1 x 1 netD:add(nn.View(1):setNumInputDims(3)) -- state size: 1 netD:apply(weights_init) local netA = nn.Sequential() -- input is (nc*2) x 64 x 64 netA:add(SpatialConvolution(nc*2, ndf, 4, 4, 2, 2, 1, 1)) netA:add(nn.LeakyReLU(0.2, true)) -- state size: (ndf) x 32 x 32 netA:add(SpatialConvolution(ndf, ndf * 2, 4, 4, 2, 2, 1, 1)) netA:add(SpatialBatchNormalization(ndf * 2)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*2) x 16 x 16 netA:add(SpatialConvolution(ndf * 2, ndf * 4, 4, 4, 2, 2, 1, 1)) netA:add(SpatialBatchNormalization(ndf * 4)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*4) x 8 x 8 netA:add(SpatialConvolution(ndf * 4, ndf * 8, 4, 4, 2, 2, 1, 1)) netA:add(SpatialBatchNormalization(ndf * 8)):add(nn.LeakyReLU(0.2, true)) -- state size: (ndf*8) x 4 x 4 netA:add(SpatialConvolution(ndf * 8, 1, 4, 4)) netA:add(nn.Sigmoid()) -- state size: 1 x 1 x 1 netA:add(nn.View(1):setNumInputDims(3)) -- state size: 1 netA:apply(weights_init) local criterion = nn.BCECriterion() print('netG:',netG) print('netA:',netA) print('netD:',netD) if opt.load_cp > 0 then epoch = opt.load_cp require 'cunn' require 'cudnn' netG = torch.load('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_G.t7') netD = torch.load('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_D.t7') netA = torch.load('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_A.t7') end local epoch_tm = torch.Timer() local tm = torch.Timer() local data_tm = torch.Timer() local input_img = torch.Tensor(opt.batchSize, 3, opt.fineSize, opt.fineSize) local ass_label = torch.Tensor(opt.batchSize, 3, opt.fineSize, opt.fineSize) local noass_label = torch.Tensor(opt.batchSize, 3, opt.fineSize, opt.fineSize) local label = torch.Tensor(opt.batchSize, 1) if opt.gpu > 0 then require 'cunn' cutorch.setDevice(opt.gpu) input_img = input_img:cuda() ass_label = ass_label:cuda() noass_label = noass_label:cuda() label = label:cuda() if pcall(require, 'cudnn') then require 'cudnn' cudnn.benchmark = true cudnn.convert(netG, cudnn) cudnn.convert(netD, cudnn) cudnn.convert(netA, cudnn) end netD:cuda(); netG:cuda(); netA:cuda(); criterion:cuda(); end local parametersD, gradParametersD = netD:getParameters() local parametersA, gradParametersA = netA:getParameters() local parametersG, gradParametersG = netG:getParameters() local function load_data() data_tm:reset(); data_tm:resume() local batch = getbatch() input_img:copy(batch[{{},3}]) ass_label:copy(batch[{{},1}]) noass_label:copy(batch[{{},2}]) data_tm:stop() end -- create closure to evaluate f(X) and df/dX of discriminator local fDx = function(x) gradParametersD:zero() -- train with real label:fill(real_label) local output = netD:forward(ass_label) local errD_real1 = criterion:forward(output, label) local df_do = criterion:backward(output, label) netD:backward(ass_label, df_do) -- train with real (not associated) label:fill(real_label) local output = netD:forward(noass_label) local errD_real2 = criterion:forward(output, label) local df_do = criterion:backward(output, label) netD:backward(noass_label, df_do) -- train with fake local fake = netG:forward(input_img) label:fill(fake_label) local output = netD:forward(fake) local errD_fake = criterion:forward(output, label) local df_do = criterion:backward(output, label) netD:backward(fake, df_do) errD = (errD_real1 + errD_real2 + errD_fake)/3 return errD, gradParametersD:mul(1/3) end -- create closure to evaluate f(X) and df/dX of domain discriminator local fAx = function(x) gradParametersA:zero() local assd = torch.cat(input_img, ass_label, 2) local noassd = torch.cat(input_img, noass_label, 2) local fake = netG:forward(input_img) local faked = torch.cat(input_img, fake, 2) -- train with associated label:fill(real_label) local output = netA:forward(assd) local errA_real1 = criterion:forward(output, label) local df_do = criterion:backward(output, label) netA:backward(assd, df_do) -- train with not associated label:fill(fake_label) local output = netA:forward(noassd) local errA_real2 = criterion:forward(output, label) local df_do = criterion:backward(output, label) netA:backward(noassd, df_do) -- train with fake label:fill(fake_label) local output = netA:forward(faked) local errA_fake = criterion:forward(output, label) local df_do = criterion:backward(output, label) netA:backward(faked, df_do) errA = (errA_real1 + errA_real2 + errA_fake)/3 return errA, gradParametersA:mul(1/3) end -- create closure to evaluate f(X) and df/dX of generator local fGx = function(x) gradParametersG:zero() --[[ the three lines below were already executed in fDx, so save computation local fake = netG:forward(noise) input:copy(fake) ]]-- local fake = netG:forward(input_img) local output = netD:forward(fake) label:fill(real_label) -- fake labels are real for generator cost errGD = criterion:forward(output, label) local df_do = criterion:backward(output, label) local df_dg = netD:updateGradInput(fake, df_do) netG:backward(input_img, df_dg) local faked = torch.cat(input_img, fake, 2) local output = netA:forward(faked) label:fill(real_label) -- fake labels are real for generator cost errGA = criterion:forward(output, label) local df_do = criterion:backward(output, label) local df_dg2 = netA:updateGradInput(faked, df_do) -- print(df_dg2:size()) local df_dg = df_dg2[{{},{4,6}}] -- print(df_dg:size()) netG:backward(input_img, df_dg) errG = (errGA + errGD)/2 return errG, gradParametersG:mul(1/2) end if opt.display then disp = require 'display' end if opt.optimizer == 'adam' then optimizer = optim.adam else optimizer = optim.sgd end result = {} local disp_config = { title = "error over time", labels = {"samples", "errD", "errG", "errA"}, ylabel = "error", win=opt.display_id*2, } -- train for epoch = opt.load_cp + 1, opt.load_cp + opt.niter do epoch_tm:reset() local counter = 0 for i = 1, smn, opt.batchSize do tm:reset() load_data() -- (0) Update D network optimizer(fDx, parametersD, optimStateD) -- (1) Update A network optimizer(fAx, parametersA, optimStateA) -- (2) Update G network optimizer(fGx, parametersG, optimStateG) -- display counter = counter + 1 if counter % 20 == 0 and opt.display then local fake = netG:forward(input_img) local real = ass_label disp.image(torch.cat(fake,real,3):cat(input_img,3), {win=opt.display_id, title=opt.name}) end -- logging if ((i-1) / opt.batchSize) % 10 == 0 then print(('Epoch: [%d][%8d / %8d]\t Time: %.3f DataTime: %.3f ' .. ' Err_G: %.4f Err_D: %.4f Err_A: %.4f'):format( epoch, ((i-1) / opt.batchSize), math.floor(smn / opt.batchSize), tm:time().real, data_tm:time().real, errG and errG or -1, errD and errD or -1, errA and errA or -1)) table.insert(result, {i + smn*(epoch-1), errD, errG, errA}) disp.plot(result, disp_config) end end paths.mkdir('checkpoints') parametersD, gradParametersD = nil, nil -- nil them to avoid spiking memory parametersA, gradParametersA = nil, nil -- nil them to avoid spiking memory parametersG, gradParametersG = nil, nil torch.save('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_G.t7', netG:clearState()) torch.save('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_D.t7', netD:clearState()) torch.save('checkpoints/' .. opt.name .. '_' .. epoch .. '_net_A.t7', netA:clearState()) parametersD, gradParametersD = netD:getParameters() -- reflatten the params and get them parametersA, gradParametersA = netA:getParameters() parametersG, gradParametersG = netG:getParameters() print(('End of epoch %d / %d \t Time Taken: %.3f'):format( epoch, opt.niter, epoch_tm:time().real)) end
local has_cmp, cmp = pcall(require, 'cmp') local utils = require '_.utils' local M = {} local check_back_space = function() local col = vim.fn.col('.') - 1 if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then return true else return false end end -- Use (s-)tab to: --- move to prev/next item in completion menuone --- jump to prev/next snippet's placeholder _G._.tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-n>' elseif vim.fn.call('vsnip#available', {1}) == 1 then return utils.t '<Plug>(vsnip-expand-or-jump)' elseif check_back_space() then return utils.t '<Tab>' else return vim.fn['compe#complete']() end end _G._.s_tab_complete = function() if vim.fn.pumvisible() == 1 then return utils.t '<C-p>' elseif vim.fn.call('vsnip#jumpable', {-1}) == 1 then return utils.t '<Plug>(vsnip-jump-prev)' else return utils.t '<S-Tab>' end end M.setup = function() if has_cmp then cmp.setup({ snippet={ -- REQUIRED - you must specify a snippet engine expand=function(args) vim.fn['vsnip#anonymous'](args.body) -- For `vsnip` users. end }, mapping={ ['<C-b>']=cmp.mapping(cmp.mapping.scroll_docs(-4), {'i', 'c'}), ['<C-f>']=cmp.mapping(cmp.mapping.scroll_docs(4), {'i', 'c'}), ['<C-Space>']=cmp.mapping(cmp.mapping.complete(), {'i', 'c'}), ['<C-y>']=cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>']=cmp.mapping({i=cmp.mapping.abort(), c=cmp.mapping.close()}), ['<CR>']=cmp.mapping.confirm({select=true}) }, sources=cmp.config.sources({ {name='nvim_lsp'}, {name='vsnip'}, {name='tmux'}, {name='path'} }, {{name='buffer'}}) }) -- Use buffer source for `/` (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline('/', {sources={{name='buffer'}}}) -- Use cmdline & path source for ':' (if you enabled `native_menu`, this won't work anymore). cmp.setup.cmdline(':', { sources=cmp.config.sources({{name='path'}}, {{name='cmdline'}}) }) end end return M
local function input(event) local top = SCREENMAN:GetTopScreen() if event.DeviceInput.button == "DeviceButton_left mouse button" then if event.type == "InputEventType_Release" then if not SCREENMAN:get_input_redirected(PLAYER_1) then if isOver(top:GetChild("Overlay"):GetChild("PlayerAvatar"):GetChild("Avatar" .. PLAYER_1):GetChild("Image")) then SCREENMAN:AddNewScreenToTop("ScreenAvatarSwitch") end end end end if event.DeviceInput.button == "DeviceButton_left mouse button" and event.type == "InputEventType_Release" then MESSAGEMAN:Broadcast("MouseLeftClick") elseif event.DeviceInput.button == "DeviceButton_right mouse button" and event.type == "InputEventType_Release" then MESSAGEMAN:Broadcast("MouseRightClick") end return false end local t = Def.ActorFrame { BeginCommand = function(self) local s = SCREENMAN:GetTopScreen() s:AddInputCallback(input) if s:GetName() == "ScreenNetSelectMusic" then s:UsersVisible(false) end end } t[#t + 1] = Def.Actor { CodeMessageCommand = function(self, params) if params.Name == "AvatarShow" and getTabIndex() == 0 and not SCREENMAN:get_input_redirected(PLAYER_1) then SCREENMAN:AddNewScreenToTop("ScreenAvatarSwitch") end end } t[#t + 1] = LoadActor("../_frame") t[#t + 1] = LoadActor("../_PlayerInfo") t[#t + 1] = LoadActor("currentsort") t[#t + 1] = LoadFont("Common Large") .. { InitCommand = function(self) self:xy(5, 32):halign(0):valign(1):zoom(0.55):diffuse(getMainColor("positive")):settext("Select Music:") end } t[#t + 1] = LoadActor("../_cursor") t[#t + 1] = LoadActor("../_halppls") t[#t + 1] = LoadActor("currenttime") GAMESTATE:UpdateDiscordMenu( GetPlayerOrMachineProfile(PLAYER_1):GetDisplayName() .. ": " .. string.format("%5.2f", GetPlayerOrMachineProfile(PLAYER_1):GetPlayerRating()) ) return t
male_roba = Creature:new { objectName = "@mob/creature_names:roba_male", socialGroup = "roba", faction = "", level = 15, chanceHit = 0.31, damageMin = 160, damageMax = 170, baseXp = 831, baseHAM = 2400, baseHAMmax = 3000, armor = 0, resists = {5,5,5,5,5,5,5,-1,-1}, meatType = "meat_carnivore", meatAmount = 11, hideType = "hide_leathery", hideAmount = 17, boneType = "bone_mammal", boneAmount = 12, milk = 0, tamingChance = 0.25, ferocity = 2, pvpBitmask = ATTACKABLE, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = CARNIVORE, templates = {"object/mobile/roba_hue.iff"}, hues = { 8, 9, 10, 11, 12, 13, 14, 15 }, controlDeviceTemplate = "object/intangible/pet/roba_hue.iff", scale = 0.9, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"",""}, {"dizzyattack",""} } } CreatureTemplates:addCreatureTemplate(male_roba, "male_roba")
require("util") local main = {} local function find_resources(surface, position, range, resource_category) local resource_category = resource_category or 'basic-solid' local top_left = {x = position.x - range, y = position.y - range} local bottom_right = {x = position.x + range, y = position.y + range} local resources = surface.find_entities_filtered{area={top_left, bottom_right}, type='resource'} local categorized = {} for _, resource in pairs(resources) do if resource.prototype.resource_category == resource_category then table.insert(categorized, resource) end end return categorized end local function find_all_entities(entity_type) local surface = game.surfaces['nauvis'] local entities = {} for chunk in surface.get_chunks() do local chunk_area = {lefttop = {x = chunk.x*32, y = chunk.y*32}, rightbottom = {x = chunk.x*32+32, y = chunk.y*32+32}} local chunk_entities = surface.find_entities_filtered({area = chunk_area, type = entity_type}) for i = 1, #chunk_entities do entities[#entities + 1] = chunk_entities[i] end end return entities end local function find_target(entity) if entity.drop_target then return entity.drop_target else local entities = entity.surface.find_entities_filtered{position=entity.drop_position} return entities[1] end end local function find_targeting(entity) local range = global.max_radius local position = entity.position local top_left = {x = position.x - range, y = position.y - range} local bottom_right = {x = position.x + range, y = position.y + range} local surface = entity.surface local entities = {} local targeting = {} local entities = surface.find_entities_filtered{area={top_left, bottom_right}, type='mining-drill'} for i = 1, #entities do if find_target(entities[i]) == entity then targeting[#targeting + 1] = entities[i] end end local entities = surface.find_entities_filtered{area={top_left, bottom_right}, type='inserter'} for i = 1, #entities do if find_target(entities[i]) == entity then targeting[#targeting + 1] = entities[i] end end return targeting end local function order_deconstruction(drill) if drill.to_be_deconstructed(drill.force) then return end if drill.fluidbox and #drill.fluidbox > 0 then return end if next(drill.circuit_connected_entities.red) ~= nil or next(drill.circuit_connected_entities.green) ~= nil then return end if not drill.minable then return end if not drill.prototype.selectable_in_game then return end if drill.has_flag("not-deconstructable") then return end drill.order_deconstruction(drill.force, drill.last_user) local target = find_target(drill) if target ~= nil and target.minable and target.prototype.selectable_in_game then if target.type == "logistic-container" or target.type == "container" then local targeting = find_targeting(target) if targeting ~= nil then for i = 1, #targeting do if not targeting[i].to_be_deconstructed(targeting[i].force) then return end end if target.to_be_deconstructed(target.force) then target.cancel_deconstruction(target.force) end target.order_deconstruction(target.force, target.last_user) end end end end function check_drill(drill) if drill.mining_target ~= nil and drill.mining_target.valid then if drill.mining_target.amount > 0 then return end end local mining_drill_radius = drill.prototype.mining_drill_radius if mining_drill_radius > global.max_radius then global.max_radius = mining_drill_radius end if mining_drill_radius == nil then return end local resources = find_resources(drill.surface, drill.position, mining_drill_radius, 'basic-solid') for i = 1, #resources do if resources[i].amount > 0 then return end end order_deconstruction(drill) end local function find_drills(entity) local position = entity.position local surface = entity.surface local top_left = {x = position.x - global.max_radius, y = position.y - global.max_radius} local bottom_right = {x = position.x + global.max_radius, y = position.y + global.max_radius} local entities = {} local targeting = {} local entities = surface.find_entities_filtered{area={top_left, bottom_right}, type='mining-drill'} for i = 1, #entities do local x_distance = math.abs(entities[i].position.x - position.x) local y_distance = math.abs(entities[i].position.y - position.y) local radius = entities[i].prototype.mining_drill_radius if x_distance < radius and y_distance < radius then check_drill(entities[i]) end end end function main.init() global.max_radius = 0.99 for _, drill in pairs(find_all_entities('mining-drill')) do check_drill(drill) end end function main.depleted(e) find_drills(e.entity) end function main.cancelled(e) if e.player_index ~= nil or e.entity.type ~= 'mining-drill' then return end check_drill(e.entity) end function main.built(e) if e.created_entity.type ~= 'mining-drill' then return end if e.created_entity.prototype.mining_drill_radius > global.max_radius then global.max_radius = e.created_entity.prototype.mining_drill_radius end end return { on_init = main.init, on_built_entity = main.built, on_robot_built_entity = main.built, on_resource_depleted = main.depleted, on_cancelled_deconstruction = main.cancelled, }
local frozen = true local loading = false Citizen.CreateThread(function() while true do Citizen.Wait(0) if frozen == true then SetEntityInvincible(GetPlayerPed(-1),true) SetEntityVisible(GetPlayerPed(-1),false) FreezeEntityPosition(GetPlayerPed(-1),true) end end end) AddEventHandler("playerSpawned",function() loading = true InitialSetup() Wait(15000) loading = false end) Citizen.CreateThread(function() while true do Citizen.Wait(1000) if loading then LoadInterior(137473) RefreshInterior(137473) end end end) function InitialSetups() SwitchOutPlayer(PlayerPedId(), 0, 1) MovePlayer() end function InitialSetup() SwitchOutPlayer(PlayerPedId(), 0, 1) end function MovePlayer() Wait(5000) SetPlayer() Wait(2000) frozen = false SetEntityInvincible(GetPlayerPed(-1), false) SetEntityVisible(GetPlayerPed(-1), true, false) FreezeEntityPosition(GetPlayerPed(-1),false) end function SetPlayer() SwitchInPlayer(PlayerPedId()) end RegisterNetEvent("movebitch") AddEventHandler("movebitch", function() InitialSetups() end)
local size = cc.Director:getInstance():getWinSize() local scheduler = cc.Director:getInstance():getScheduler() local BattleFieldScene = class("BattleFieldScene",function() return cc.Scene:create() end) ---------------------------------------- ----Sprite3DBasicTest ---------------------------------------- local Sprite3DBasicTest = {currentLayer = nil} Sprite3DBasicTest.__index = Sprite3DBasicTest function Sprite3DBasicTest.onTouchesEnd(touches, event) for i = 1,table.getn(touches) do local location = touches[i]:getLocation() Sprite3DBasicTest.addNewSpriteWithCoords(Sprite3DBasicTest.currentLayer, location.x, location.y ) end end function Sprite3DBasicTest.addNewSpriteWithCoords(parent,x,y) local sprite = cc.Sprite3D:create("Sprite3DTest/boss1.obj") sprite:setScale(3.0) sprite:setTexture("Sprite3DTest/boss.png") parent:addChild(sprite) sprite:setPosition(cc.p(x,y)) local random = math.random() local action = nil if random < 0.2 then action = cc.ScaleBy:create(3,2) elseif random < 0.4 then action = cc.RotateBy:create(3, 360) elseif random < 0.6 then action = cc.Blink:create(1, 3) elseif random < 0.8 then action = cc.TintBy:create(2, 0, -255, -255) else action = cc.FadeOut:create(2) end local action_back = action:reverse() local seq = cc.Sequence:create(action, action_back) sprite:runAction(cc.RepeatForever:create(seq)) end function Sprite3DBasicTest.create(layer) Sprite3DBasicTest.currentLayer = layer local listener = cc.EventListenerTouchAllAtOnce:create() listener:registerScriptHandler(Sprite3DBasicTest.onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED ) local eventDispatcher = layer:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) Sprite3DBasicTest.addNewSpriteWithCoords(layer, size.width / 2, size.height / 2) return layer end ---------------------------------------- ----Sprite3DWithSkinTest ---------------------------------------- local Sprite3DWithSkinTest = {currentLayer = nil} Sprite3DWithSkinTest.__index = Sprite3DWithSkinTest function Sprite3DWithSkinTest.onTouchesEnd(touches, event) for i = 1,table.getn(touches) do local location = touches[i]:getLocation() Sprite3DWithSkinTest.addNewSpriteWithCoords(Sprite3DWithSkinTest.currentLayer, location.x, location.y ) end end function Sprite3DWithSkinTest.addNewSpriteWithCoords(parent,x,y) local sprite = cc.Sprite3D:create("Sprite3DTest/orc.c3b") sprite:setScale(3) sprite:setRotation3D({x = 0, y = 180, z = 0}) sprite:setPosition(cc.p(x, y)) parent:addChild(sprite) local animation = cc.Animation3D:create("Sprite3DTest/orc.c3b") if nil ~= animation then local animate = cc.Animate3D:create(animation) local inverse = false if math.random() == 0 then inverse = true end local rand2 = math.random() local speed = 1.0 if rand2 < 1/3 then speed = animate:getSpeed() + math.random() elseif rand2 < 2/3 then speed = animate:getSpeed() - 0.5 * math.random() end if inverse then animate:setSpeed(-speed) else animate:setSpeed(speed) end sprite:runAction(cc.RepeatForever:create(animate)) end end function Sprite3DWithSkinTest.create(layer) Sprite3DWithSkinTest.currentLayer = layer local listener = cc.EventListenerTouchAllAtOnce:create() listener:registerScriptHandler(Sprite3DWithSkinTest.onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED ) local eventDispatcher = layer:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) Sprite3DWithSkinTest.addNewSpriteWithCoords(layer, size.width / 2, size.height / 2) return layer end ---------------------------------------- ----Animate3DTest ---------------------------------------- local State = { SWIMMING = 0, SWIMMING_TO_HURT = 1, HURT = 2, HURT_TO_SWIMMING = 3, } local Animate3DTest = {} Animate3DTest.__index = Animate3DTest function Animate3DTest.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, Animate3DTest) return target end function Animate3DTest:onEnter() self._hurt = nil self._swim = nil self._sprite = nil self._moveAction = nil self._transTime = 0.1 self._elapseTransTime = 0.0 local function renewCallBack() self._sprite:stopActionByTag(101) self._state = State.HURT_TO_SWIMMING end local function onTouchesEnd(touches, event ) for i = 1,table.getn(touches) do local location = touches[i]:getLocation() if self._sprite ~= nil then local len = cc.pGetLength(cc.pSub(cc.p(self._sprite:getPosition()), location)) if len < 40 then if self._state == State.SWIMMING then self._sprite:runAction(self._hurt) local delay = cc.DelayTime:create(self._hurt:getDuration() - 0.1) local seq = cc.Sequence:create(delay, cc.CallFunc:create(renewCallBack)) seq:setTag(101) self._sprite:runAction(seq) self._state = State.SWIMMING_TO_HURT end return end end end end self:addSprite3D() local listener = cc.EventListenerTouchAllAtOnce:create() listener:registerScriptHandler(onTouchesEnd,cc.Handler.EVENT_TOUCHES_ENDED ) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) local function update(dt) if self._state == State.HURT_TO_SWIMMING then self._elapseTransTime = self._elapseTransTime + dt local t = self._elapseTransTime / self._transTime if t >= 1.0 then t = 1.0 self._sprite:stopAction(self._hurt) self._state = State.SWIMMING end self._swim:setWeight(t) self._hurt:setWeight(1.0 - t) elseif self._state == State.SWIMMING_TO_HURT then self._elapseTransTime = self._elapseTransTime + dt local t = self._elapseTransTime / self._transTime if t >= 1.0 then t = 1.0 self._state = State.HURT end self._swim:setWeight(1.0 - t) self._hurt:setWeight(t) end end self:scheduleUpdateWithPriorityLua(update,0) end function Animate3DTest:onExit() self._moveAction:release() self._hurt:release() self._swim:release() self:unscheduleUpdate() end function Animate3DTest:addSprite3D() -- body local fileName = "Sprite3DTest/tortoise.c3b" local sprite = cc.Sprite3D:create(fileName) sprite:setScale(0.1) local winSize = cc.Director:getInstance():getWinSize() sprite:setPosition(cc.p(winSize.width * 4.0 / 5.0, winSize.height / 2.0)) self:addChild(sprite) self._sprite = sprite local animation = cc.Animation3D:create(fileName) if nil ~= animation then local animate = cc.Animate3D:create(animation, 0.0, 1.933) sprite:runAction(cc.RepeatForever:create(animate)) self._swim = animate self._swim:retain() self._hurt = cc.Animate3D:create(animation, 1.933, 2.8) self._hurt:retain() self._state = State.SWIMMING end self._moveAction = cc.MoveTo:create(4.0, cc.p(winSize.width / 5.0, winSize.height / 2.0)) self._moveAction:retain() local function reachEndCallBack() self._sprite:stopActionByTag(100) local inverse = self._moveAction:reverse() inverse:retain() self._moveAction:release() self._moveAction = inverse local rot = cc.RotateBy:create(1.0, { x = 0.0, y = 180.0, z = 0.0}) local seq = cc.Sequence:create(rot, self._moveAction, cc.CallFunc:create(reachEndCallBack)) seq:setTag(100) self._sprite:runAction(seq) end local seq = cc.Sequence:create(self._moveAction, cc.CallFunc:create(reachEndCallBack)) seq:setTag(100) sprite:runAction(seq) end function Animate3DTest.create(layer) --local layer = Animate3DTest.extend(layer) if nil ~= layer then local function onNodeEvent(event) if "enter" == event then layer:onEnter() elseif "exit" == event then layer:onExit() end end layer:registerScriptHandler(onNodeEvent) end return layer end -- create farm function BattleFieldScene:createLayerFarm(layer) local layerFarm = layer;--cc.Layer:create() -- add in farm background local bg = cc.Sprite:create("background.jpg") bg:setPosition(size.width / 2 + 80, size.height / 2) layerFarm:addChild(bg) -- handing touch events local touchBeginPoint = nil local function onTouchBegan(touch, event) local location = touch:getLocation() --cclog("onTouchBegan: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = {x = location.x, y = location.y} -- CCTOUCHBEGAN event must return true return true end local function onTouchMoved(touch, event) local location = touch:getLocation() --cclog("onTouchMoved: %0.2f, %0.2f", location.x, location.y) if touchBeginPoint then local cx, cy = layerFarm:getPosition() layerFarm:setPosition(cx + location.x - touchBeginPoint.x, cy + location.y - touchBeginPoint.y) touchBeginPoint = {x = location.x, y = location.y} end end local function onTouchEnded(touch, event) local location = touch:getLocation() --cclog("onTouchEnded: %0.2f, %0.2f", location.x, location.y) touchBeginPoint = nil end local listener = cc.EventListenerTouchOneByOne:create() listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED ) listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) local eventDispatcher = layerFarm:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layerFarm) local function onNodeEvent(event) if "exit" == event then cc.Director:getInstance():getScheduler():unscheduleScriptEntry(self.schedulerID) end end layerFarm:registerScriptHandler(onNodeEvent) return layerFarm end function BattleFieldScene.create() local scene = BattleFieldScene.new() local layer = cc.Layer:create() scene:addChild(layer) BattleFieldScene.createLayerFarm(self, layer) Sprite3DBasicTest.create(layer) Sprite3DWithSkinTest.create(layer) Animate3DTest.create(layer) --scene:addChild(Sprite3DBasicTest.create()) --scene:addChild(Sprite3DWithSkinTest.create()) --scene:addChild(Animate3DTest.create()) return scene end return BattleFieldScene
--------------------------------------------------- -- ___ _ -- -- | __| |___ _ __ _____ __ _____ _ _ -- -- | _|| / -_) '_ \/ _ \ V V / -_) '_| -- -- |___|_\___| .__/\___/\_/\_/\___|_| -- -- |_| -- -- _____ -- -- |_ _|__ _ __ ___ -- -- | |/ _ \ ' \/ -_) -- -- |_|\___/_|_|_\___| -- --------------------------------------------------- -- How to use/Help -- --------------------------------------------------- function eletome.how_use_page(name_value) -- Page to view how to use a node/getting started --"action:getting_started" --"elepower_machines:electrolyzer" = "" local t_split = string.split(name_value,":") local is_help = false if t_split[1] == "action" then is_help = true end -- get page heading and sub-heading local pg_heading local pg_subhead if is_help then pg_heading = string.gsub(t_split[2],"_", " ") -- change all 1st letters to upper - -- https://stackoverflow.com/questions/20284515/capitalize-first-letter-of-every-word-in-lua pg_heading = string.gsub(" "..pg_heading, "%W%l", string.upper):sub(2) pg_subhead = "Help" name_value = t_split[2] else pg_heading = minetest.registered_nodes[name_value].description pg_subhead = "How to use" end -- Assign Common styles to local vars local sty_h0s = eletome.common_styles.style_h0s local sty_h0e = eletome.common_styles.style_h0e local sty_h1s = eletome.common_styles.style_h1s local sty_h1e = eletome.common_styles.style_h1e local sty_h2s = eletome.common_styles.style_h2s local sty_h2e = eletome.common_styles.style_h2e local sty_h3s = eletome.common_styles.style_h3s local sty_h3e = eletome.common_styles.style_h3e local sty_h4s = eletome.common_styles.style_h4s local sty_h4e = eletome.common_styles.style_h4e -- Additional Info Table local add_info = eletome.ai.nodes --------------- -- left page -- --------------- local left_image = add_info[name_value].hu_img_1 or "elepower_tome_empty.png" local lp_offset = 0 if left_image == "elepower_tome_empty.png" then lp_offset = 3.75 end if type(left_image) == "table" then left_image = add_info[name_value].hu_img_1[1] else left_image = "image[2.25,6.6;5,3.75;"..left_image.."]" end local lp_heading = "hypertext[0.5,0.7;8.5,0.95;lp_heading;"..sty_h0s..pg_heading..sty_h0e.."]" local lp_sub_head = "hypertext[0.5,1.4;8.5,0.9;lp_sub_heading;"..sty_h1s..pg_subhead..sty_h1e.."]" local lp_image = left_image local lp_text = "hypertext[0.75,2.1;8.0,"..(4.5+lp_offset)..";use_txt;"..sty_h4s..(add_info[name_value].how_use_1 or "")..sty_h4e.."]" ---------------- -- Right page -- ---------------- local right_image = add_info[name_value].hu_img_2 or "elepower_tome_empty.png" local right_txt = add_info[name_value].how_use_2 or "" local rp_txt_offset = 0 local rp_img_offset = 0 if right_image == "elepower_tome_empty.png" then rp_txt_offset = 3.75 end if right_txt == "" or right_txt == nil then rp_img_offset = -6.1 end if type(right_image) == "table" then right_image = "container[9.25,"..(6.6+rp_img_offset).."]"..add_info[name_value].hu_img_2[1].."container_end[]" else right_image = "image[10.75,"..(6.6+rp_img_offset)..";5,3.75;"..right_image.."]" end local rp_text = "hypertext[9.25,1.4;8.0,"..(4.5+rp_txt_offset)..";use_txt;"..sty_h4s..right_txt..sty_h4e.."]" local rp_image = right_image local eletome_how_use = lp_heading..lp_sub_head..lp_image..lp_text..rp_text ..rp_image return eletome_how_use end
local tablex = require 'pl.tablex' local utils = require 'pl.utils' local copy = tablex.deepcopy local append = table.insert local coroutine = coroutine local resume = coroutine.resume local assert_arg = utils.assert_arg permute = {} local permgen permgen = function (a, n, fn) if n == 0 then fn(a) else for i=1,n do a[n], a[i] = a[i], a[n] permgen(a, n-1, fn) a[n], a[i] = a[i], a[n] end end end --- an iterator over all permutations of the elements of a list. ---- Please note that the same list is returned each time, so do not keep references! ---- @param a list-like table ---- @return an iterator which provides the next permutation as a list function permute.iter(a) assert_arg(1,a,'table') local n = #a local co = coroutine.create(function () permgen(a,n,coroutine.yield) end) return function () local code, res = resume(co) return res end end --- construct a table containing all the permutations of a list. ---- @param a list-like table ---- @return a table of tables ---- @usage permute.table {1,2,3} --> {{2,3,1},{3,2,1},{3,1,2},{1,3,2},{2,1,3},{1,2,3}} function permute.table(a) assert_arg(1,a,'table') local res = {} local n = #a permgen(a,n,function(t) append(res,copy(t)) end) return res end return permute
local M = {} local function send() local nodes_table = { vehicle_id = obj:getID(), nodes = {} } for k, node in pairs(v.data.nodes) do local position = obj:getNodePosition(node.cid) table.insert(nodes_table.nodes, {position.x, position.y, position.z}) end obj:queueGameEngineLua("network.send_messagepack(4, false, \'"..jsonEncode(nodes_table).."\')") end local function apply(nodes) local nodes = jsonDecode(nodes) for node, pos in pairs(nodes) do node = tonumber(node) obj:setNodePosition(node, float3(pos[1], pos[2], pos[3])) local beam = v.data.beams[node] local beamPrecompression = beam.beamPrecompression or 1 local deformLimit = type(beam.deformLimit) == 'number' and beam.deformLimit or math.huge obj:setBeam(-1, beam.id1, beam.id2, beam.beamStrength, beam.beamSpring, beam.beamDamp, type(beam.dampCutoffHz) == 'number' and beam.dampCutoffHz or 0, beam.beamDeform, deformLimit, type(beam.deformLimitExpansion) == 'number' and beam.deformLimitExpansion or deformLimit, beamPrecompression ) end end M.send = send M.apply = apply return M
UMF_REQUIRE "/" ---@class Location: Entity local location_meta = global_metatable( "location", "entity" ) --- Tests if the parameter is a location entity. --- ---@param e any ---@return boolean function IsLocation( e ) return IsEntity( e ) and e.type == "location" end --- Wraps the given handle with the location class. --- ---@param handle number ---@return Location? function Location( handle ) if handle > 0 then return setmetatable( { handle = handle, type = "location" }, location_meta ) end end --- Finds a location with the specified tag. --- `global` determines whether to only look in the script's hierarchy or the entire scene. --- ---@param tag string ---@param global boolean ---@return Location? function FindLocationByTag( tag, global ) return Location( FindLocation( tag, global ) ) end --- Finds all locations with the specified tag. --- `global` determines whether to only look in the script's hierarchy or the entire scene. --- ---@param tag string ---@param global boolean ---@return Location[] function FindLocationsByTag( tag, global ) local t = FindLocations( tag, global ) for i = 1, #t do t[i] = Location( t[i] ) end return t end ---@return string function location_meta:__tostring() return string.format( "Location[%d]", self.handle ) end --- Gets the transform of the location. --- ---@return Transformation function location_meta:GetTransform() assert( self:IsValid() ) return MakeTransformation( GetLocationTransform( self.handle ) ) end
--[[ MailSlurp API MailSlurp is an API for sending and receiving emails from dynamically allocated email addresses. It's designed for developers and QA teams to test applications, process inbound emails, send templated notifications, attachments, and more. ## Resources - [Homepage](https://www.mailslurp.com) - Get an [API KEY](https://app.mailslurp.com/sign-up/) - Generated [SDK Clients](https://www.mailslurp.com/docs/) - [Examples](https://github.com/mailslurp/examples) repository The version of the OpenAPI document: 6.5.2 Contact: contact@mailslurp.dev Generated by: https://openapi-generator.tech ]] -- alias_dto class local alias_dto = {} local alias_dto_mt = { __name = "alias_dto"; __index = alias_dto; } local function cast_alias_dto(t) return setmetatable(t, alias_dto_mt) end local function new_alias_dto(id, email_address, masked_email_address, user_id, inbox_id, name, use_threads, is_verified, created_at, updated_at) return cast_alias_dto({ ["id"] = id; ["emailAddress"] = email_address; ["maskedEmailAddress"] = masked_email_address; ["userId"] = user_id; ["inboxId"] = inbox_id; ["name"] = name; ["useThreads"] = use_threads; ["isVerified"] = is_verified; ["createdAt"] = created_at; ["updatedAt"] = updated_at; }) end return { cast = cast_alias_dto; new = new_alias_dto; }
local specialQuests = { --Choose one chest [2215] = Storage.AnnihilatorDone, [26300] = Storage.SvargrondArena.RewardGreenhorn, [27300] = Storage.SvargrondArena.RewardScrapper, [28300] = Storage.SvargrondArena.RewardWarlord } local questsExperience = { [2215] = 100000, --anni } local questLog = { --Various chests [2000] = Storage.DemonHelmetDone, [2001] = Storage.BehemothDone, [2002] = Storage.VampireShieldDone, [2003] = Storage.FireAxeDone, [2004] = Storage.MedusaShieldDone, [2005] = Storage.CrystalWandDone, [2006] = Storage.GriffinShieldDone, [2007] = Storage.NaginataQuestDone } function onUse(player, item, fromPosition, target, toPosition, isHotkey) local storage = specialQuests[item.actionid] if not storage then storage = item.uid if storage > 65535 then return false end end if player:getStorageValue(storage) > 0 then player:sendTextMessage(MESSAGE_EVENT_ADVANCE, 'The ' .. ItemType(item.itemid):getName() .. ' is empty.') return true end local items, reward = {} local size = item:isContainer() and item:getSize() or 0 if size == 0 then reward = item:clone() else local container = Container(item.uid) for i = 0, container:getSize() - 1 do items[#items + 1] = container:getItem(i):clone() end end size = #items if size == 1 then reward = items[1]:clone() end local result = '' if reward then local ret = ItemType(reward.itemid) if ret:isRune() then result = ret:getArticle() .. ' ' .. ret:getName() .. ' (' .. reward.type .. ' charges)' elseif ret:isStackable() and reward:getCount() > 1 then result = reward:getCount() .. ' ' .. ret:getPluralName() elseif ret:getArticle() ~= '' then result = ret:getArticle() .. ' ' .. ret:getName() else result = ret:getName() end else if size > 20 then reward = Game.createItem(item.itemid, 1) elseif size > 8 then reward = Game.createItem(1988, 1) else reward = Game.createItem(1987, 1) end for i = 1, size do local tmp = items[i] if reward:addItemEx(tmp) ~= RETURNVALUE_NOERROR then print('[Warning] QuestSystem:', 'Could not add quest reward to container') end end local ret = ItemType(reward.itemid) result = ret:getArticle() .. ' ' .. ret:getName() end if player:addItemEx(reward) ~= RETURNVALUE_NOERROR then local weight = reward:getWeight() if player:getFreeCapacity() < weight then player:sendCancelMessage(string.format('You have found %s weighing %.2f oz. You have no capacity.', result, (weight / 100))) else player:sendCancelMessage('You have found ' .. result .. ', but you have no room to take it.') end return true end if questsExperience[storage] then player:addExperience(questsExperience[storage], true) end if questLog[item.actionid] then if (player:getStorageValue(questLog[item.actionid]) ~= 1) then player:setStorageValue(questLog[item.actionid], 1) end end player:sendTextMessage(MESSAGE_EVENT_ADVANCE, 'You have found ' .. result .. '.') player:setStorageValue(storage, 1) return true end
--!strict -- Loader -- Stephen Leitnick -- January 10, 2021 --[[ Loads all ModuleScripts within the given parent. Loader.LoadChildren(parent: Instance): module[] Loader.LoadDescendants(parent: Instance): module[] --]] local Loader = {} type Module = {} type Modules = {Module} function Loader.LoadChildren(parent: Instance): Modules local modules: Modules = {} for _,child in ipairs(parent:GetChildren()) do if (child:IsA("ModuleScript")) then local m = require(child) table.insert(modules, m) end end return modules end function Loader.LoadDescendants(parent: Instance): Modules local modules: Modules = {} for _,descendant in ipairs(parent:GetDescendants()) do if (descendant:IsA("ModuleScript")) then local m = require(descendant) table.insert(modules, m) end end return modules end return Loader
object_tangible_terminal_crafting_assembly_terminal = object_tangible_terminal_shared_crafting_assembly_terminal:new { } ObjectTemplates:addTemplate(object_tangible_terminal_crafting_assembly_terminal, "object/tangible/terminal/crafting_assembly_terminal.iff")
local PANEL = Gvue.new_panel() PANEL.element_name = 'text' function PANEL:draw(w, h) draw.SimpleText( self.html.inner_html, self.context.attributes.font_family, 0, 0, self.context.attributes.color ) end function PANEL:rebuild() local text_wide, text_tall = util.text_size(self.html.inner_html, self.context.attributes.font_family) self:SetSize(text_wide, text_tall) end vgui.Register('_gvue_text', PANEL, 'gvue_basic_panel') Gvue.alias('text', '_gvue_text') Gvue.alias('text_node', '_gvue_text')
local nets = { "ResetHull", "SetBlind", "SetHull", "PlayFreezeCamSound", "PlayerSwitchDynamicLight", "DisableDynamicLight", "PH_ShowTutor", "CheckAdminFirst", "CheckAdminResult", "SvCommandReq", "SvCommandSliderReq", "SendTauntStateCmd", "CL2SV_PlayThisTaunt", "PH_ForceCloseTauntWindow", "PH_AllowTauntWindow", "PH_TeamWinning_Snd", "AutoTauntSpawn", "AutoTauntRoundEnd", "PHX.rotateState", "PHX.CenterPrint", "PHX.ChatPrint", "PHX.bubbleNotify", "PHX.ChatInfo", "PHXPickupCmdState", "SvCommandTextEntry", "SvCommandLang", "PHX.DeathNoticeDecoy", "PHX.UpdatePropbanInfo", "PHX.scan_ReqTaunts", "PHX.scan_SendTauntLists" } for _,init in pairs(nets) do util.AddNetworkString(init) end
local mono = libs.mono mono.subsets = { triple = { "Mono", "Clr.Native", "Libs.Native" }, libs = { "Clr", "Host", "Libs" } } function mono:getTriplesBuildCommand(arch, config) local tripleSubsets = "" for _, v in ipairs(mono.subsets.triple) do if tripleSubsets:len() > 0 then tripleSubsets = tripleSubsets .. "+" end tripleSubsets = tripleSubsets .. v end return tripleSubsets .. " -a " .. self:toMonoArch(arch) .. " -rf Mono -lc " .. config .. " -rc " .. config .. " -c " .. config end function mono:getNETBuildCommand() local libsSubsets = "" for _, v in ipairs(mono.subsets.libs) do if libsSubsets:len() > 0 then libsSubsets = libsSubsets .. "+" end libsSubsets = libsSubsets .. v end return libsSubsets .. " -a " .. self:toMonoArch(common.targetArchs[1]) .. " -rf Mono -lc Release -rc Release -c Release" end function mono:getBuildCommands(missingTriples, missingNETLibraries) local commands = {} local tripleSubsets = "" local libsSubsets = "" for _, v in ipairs(mono.subsets.triple) do if tripleSubsets:len() > 0 then tripleSubsets = tripleSubsets .. "+" end tripleSubsets = tripleSubsets .. v end for _, v in ipairs(mono.subsets.libs) do if libsSubsets:len() > 0 then libsSubsets = libsSubsets .. "+" end libsSubsets = libsSubsets .. v end for arch, configs in pairs(missingTriples) do for config, missing in pairs(configs) do table.insert(commands, tripleSubsets .. " -a " .. self:toMonoArch(arch) .. " -rf Mono -lc " .. config .. " -rc " .. config .. " -c " .. config) end end if not missingNETLibraries.hasFolder or #missingNETLibraries.missingLibs > 0 then table.insert(commands, libsSubsets .. " -a " .. self:toMonoArch(common.targetArchs[1]) .. " -rf Mono -lc Release -rc Release -c Release") end return commands end function mono:buildMono(repoDir, dotnetVersion, missingTriples, missingNETLibraries) local failed = false local failureMessage = "" local commandBase if common.target == "windows" then commandBase = "\"" .. repoDir .. "\\build.cmd\" " else commandBase = "'" .. repoDir .. "/build.sh' " end for arch, configs in pairs(missingTriples) do for config, missing in pairs(configs) do local monoTriple = nil local monoObjArtifact = nil local monoBinArtifact = nil local nativeBinArtifact = nil local monoBackend = nil local code, err = nil, nil local command = commandBase .. self:getTriplesBuildCommand(arch, config) if not os.execute(command) then goto failed end monoTriple = self:toMonoTriple(common.target, arch, config) monoObjArtifact = repoDir .. "/artifacts/obj/mono/" .. monoTriple .. "/out/" monoBinArtifact = repoDir .. "/artifacts/bin/mono/" .. monoTriple .. "/" nativeBinArtifact = repoDir .. "/artifacts/bin/native/" .. dotnetVersion .. "-" .. self:toMonoOS(common.target) .. "-" .. self:toMonoConfig(config) .. "-" .. self:toMonoArch(arch) .. "/" monoBackend = self.location .. "/Backends/" .. monoTriple .. "/" code, err = common:rmdir(monoBackend) if code < 0 then goto copyFailure end code, err = common:copyDir(monoObjArtifact .. "include/mono-2.0/", monoBackend .. "/include/") if code < 0 then goto copyFailure end code, err = common:copyFiles(monoObjArtifact .. "lib/", common:libName(self.requiredLibs.static), monoBackend .. "/lib/") if code < 0 then goto copyFailure end code, err = common:copyFiles(monoBinArtifact, { common:sharedLibName("coreclr"), "System.Private.CoreLib.dll", "System.Private.CoreLib.pdb" }, monoBackend .. "/bin/") if code < 0 then goto copyFailure end code, err = common:copyFiles(nativeBinArtifact, common:sharedLibName(self.requiredNativeLibs, true), monoBackend .. "/bin/") if code < 0 then goto copyFailure end goto continue ::failed:: failed = true failureMessage = failureMessage .. "\"" .. command .. "\" failed to build\n" goto continue ::copyFailure:: failed = true failureMessage = failureMessage .. "Copy failed with " .. code .. " '" .. err .. "'\n" ::continue:: end end if not missingNETLibraries.hasFolder or #missingNETLibraries.missingLibs > 0 then local monoRID = nil local code, err = nil, nil local command = commandBase .. self:getNETBuildCommand() if not os.execute(command) then goto failed end common:rmdir(self.location .. "/.NET/") monoRID = self:toMonoRID(common.target, common.targetArchs[1]) code, err = common:copyFiles(repoDir .. "/artifacts/bin/microsoft.netcore.app.runtime." .. monoRID .. "/Release/runtimes/" .. monoRID .. "/lib/" .. dotnetVersion .. "/", self:toMonoLibraries(self.requiredRuntimeLibs), self.location .. "/.NET/") if code < 0 then goto copyFailure end goto continue ::failed:: failed = true failureMessage = failureMessage .. "\"" .. command .. "\" failed to build\n" goto continue ::copyFailure:: failed = true failureMessage = failureMessage .. "Copy failed with " .. code .. " '" .. err .. "'\n" ::continue:: end if failed then term.pushColor(term.errorColor) print(failureMessage) term.popColor() end return not failed end
ITEM.name = "Кровать" ITEM.desc = "Деревянная кровать, хотя она по корману не каждому холопу" ITEM.model = "models/aoc_furniture/bed_01.mdl" ITEM.width = 4 ITEM.height = 2
local KUI, E, L, V, P, G = unpack(select(2, ...)) local KS = KUI:GetModule("KuiSkins") local S = E:GetModule("Skins") -- Cache global variables -- Lua functions local _G = _G local pairs, unpack = pairs, unpack -- WoW API / Variables local SpellBookFrame = _G["SpellBookFrame"] local SpellBookPageText = _G["SpellBookPageText"] local GetSpellAvailableLevel = GetSpellAvailableLevel local UnitLevel = UnitLevel -- GLOBALS: hooksecurefunc local function styleSpellBook() if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.spellbook ~= true or E.private.KlixUI.skins.blizzard.spellbook ~= true then return end local r, g, b = unpack(E["media"].rgbvaluecolor) local SpellBookFrame = _G["SpellBookFrame"] SpellBookFrame:Styling() if SpellBookFrame.pagebackdrop then SpellBookFrame.pagebackdrop:Hide() end for i = 1, SPELLS_PER_PAGE do local bu = _G["SpellButton"..i] local ic = _G["SpellButton"..i.."IconTexture"] _G["SpellButton"..i.."SlotFrame"]:SetAlpha(0) bu.EmptySlot:SetAlpha(0) bu.TextBackground:Hide() bu.TextBackground2:Hide() bu.UnlearnedFrame:SetAlpha(0) bu:SetCheckedTexture("") bu:SetPushedTexture("") ic:SetTexCoord(unpack(E.TexCoords)) ic.bg = KS:CreateBG(bu) end SpellBookPageText:SetTextColor(unpack(E.media.rgbvaluecolor)) hooksecurefunc("SpellButton_UpdateButton", function(self) if SpellBookFrame.bookType == BOOKTYPE_PROFESSION then return end local slot, slotType = SpellBook_GetSpellBookSlot(self) local isPassive = IsPassiveSpell(slot, SpellBookFrame.bookType) local name = self:GetName() local highlightTexture = _G[name.."Highlight"] if isPassive then highlightTexture:SetColorTexture(1, 1, 1, 0) else highlightTexture:SetColorTexture(1, 1, 1, .25) end local subSpellString = _G[name.."SubSpellName"] local isOffSpec = self.offSpecID ~= 0 and SpellBookFrame.bookType == BOOKTYPE_SPELL subSpellString:SetTextColor(1, 1, 1) if slotType == "FUTURESPELL" then local level = GetSpellAvailableLevel(slot, SpellBookFrame.bookType) if level and level > UnitLevel("player") then self.SpellName:SetTextColor(.7, .7, .7) subSpellString:SetTextColor(.7, .7, .7) end else if slotType == "SPELL" and isOffSpec then subSpellString:SetTextColor(.7, .7, .7) end end self.RequiredLevelString:SetTextColor(.7, .7, .7) local ic = _G[name.."IconTexture"] if ic.bg then ic.bg:SetShown(ic:IsShown()) end end) -- Professions local professions = {"PrimaryProfession1", "PrimaryProfession2", "SecondaryProfession1", "SecondaryProfession2", "SecondaryProfession3"} for _, button in pairs(professions) do local bu = _G[button] bu.professionName:SetTextColor(1, 1, 1) bu.missingHeader:SetTextColor(1, 1, 1) bu.missingText:SetTextColor(1, 1, 1) bu.statusBar:SetHeight(10) bu.statusBar.rankText:SetPoint("CENTER") local _, p = bu.statusBar:GetPoint() bu.statusBar:SetPoint("TOPLEFT", p, "BOTTOMLEFT", 1, -3) KS:CreateBDFrame(bu.statusBar, .25) end local professionbuttons = {"PrimaryProfession1SpellButtonTop", "PrimaryProfession1SpellButtonBottom", "PrimaryProfession2SpellButtonTop", "PrimaryProfession2SpellButtonBottom", "SecondaryProfession1SpellButtonLeft", "SecondaryProfession1SpellButtonRight", "SecondaryProfession2SpellButtonLeft", "SecondaryProfession2SpellButtonRight", "SecondaryProfession3SpellButtonLeft", "SecondaryProfession3SpellButtonRight"} for _, button in pairs(professionbuttons) do local icon = _G[button.."IconTexture"] local bu = _G[button] _G[button.."NameFrame"]:SetAlpha(0) bu:SetPushedTexture("") if icon then icon:SetTexCoord(unpack(E.TexCoords)) icon:ClearAllPoints() icon:SetPoint("TOPLEFT", 2, -2) icon:SetPoint("BOTTOMRIGHT", -2, 2) KS:CreateBG(icon) bu.highlightTexture:SetAllPoints(icon) end end for i = 1, 2 do local bu = _G["PrimaryProfession"..i] _G["PrimaryProfession"..i.."IconBorder"]:Hide() bu.professionName:ClearAllPoints() bu.professionName:SetPoint("TOPLEFT", 100, -4) bu.icon:SetAlpha(1) bu.icon:SetTexCoord(unpack(E.TexCoords)) bu.icon:SetDesaturated(false) KS:CreateBG(bu.icon) bu:CreateBackdrop("Transparent") bu.backdrop:SetOutside(bu, 5, 5) KS:CreateGradient(bu.backdrop) end hooksecurefunc("FormatProfession", function(frame, index) if index then local _, texture = GetProfessionInfo(index) if frame.icon and texture then frame.icon:SetTexture(texture) end end end) local function SecondaryProfession(button) button:CreateBackdrop("Transparent") button.backdrop:SetOutside(button, 5, 5) KS:CreateGradient(button.backdrop) button.statusBar:ClearAllPoints() button.statusBar:SetPoint("BOTTOMLEFT", 0, 0) button.rank:SetPoint("BOTTOMLEFT", button.statusBar, "TOPLEFT", 3, 4) end SpellBookPageText:SetTextColor(.8, .8, .8) SecondaryProfession(_G["SecondaryProfession1"]) SecondaryProfession(_G["SecondaryProfession2"]) SecondaryProfession(_G["SecondaryProfession3"]) hooksecurefunc("UpdateProfessionButton", function(self) local spellIndex = self:GetID() + self:GetParent().spellOffset local isPassive = IsPassiveSpell(spellIndex, SpellBookFrame.bookType) if isPassive then self.highlightTexture:SetColorTexture(1, 1, 1, 0) else self.highlightTexture:SetColorTexture(1, 1, 1, .25) end self.spellString:SetTextColor(1, 1, 1); self.subSpellString:SetTextColor(1, 1, 1) end) end S:AddCallback("KuiSpellbook", styleSpellBook)
local highlight = require('vgit.highlight') local it = it local describe = describe local eq = assert.are.same describe('highlight:', function() describe('setup', function() it( 'should override state highlights with highlights specified through the config', function() highlight.setup({ VGitSignAdd = { fg = 'red', bg = nil, }, }) eq(highlight.state.data.VGitSignAdd, { fg = 'red', bg = nil, }) end ) end) describe('create', function() it('should successfully create a highlight', function() local hl = 'VGitTestHighlight' highlight.create(hl, { bg = nil, fg = '#464b59', }) vim.cmd(string.format('hi %s', hl)) end) end) end)
-- varDecl x, y = 1, 2; -- label ::LBL_A:: -- whileStat gotoStat while 1 == 2 do goto LBL_A end -- doStat do print("something"); end -- repeatStat repeat x = 2 + 3 or 1 + 2 until y == 2 -- forStat for i = 1, 5, 2 do print(i) end for i = 1, 5 do print(i) end -- forInStat a = {"1", "2", "3"} for i, v in ipairs(a) do print(i, v) end -- localVarDecl local q, w, e = 1, 2, 3 local p, o; -- ifStat if x then print(x) elseif y == 2 then -- empty else -- do nothing end
--*********************************************************** --** THE INDIE STONE ** --*********************************************************** require "TimedActions/ISBaseTimedAction" ---@class ISDetachItemHotbar : ISBaseTimedAction ISDetachItemHotbar = ISBaseTimedAction:derive("ISDetachItemHotbar"); function ISDetachItemHotbar:isValid() return self.character:getInventory():contains(self.item); end function ISDetachItemHotbar:update() end function ISDetachItemHotbar:start() self:setActionAnim("DetachItem") self.character:reportEvent("EventAttachItem"); end function ISDetachItemHotbar:stop() ISBaseTimedAction.stop(self); end function ISDetachItemHotbar:perform() self.hotbar.chr:removeAttachedItem(self.item); self.item:setAttachedSlot(-1); self.item:setAttachedSlotType(nil); self.item:setAttachedToModel(nil); self.hotbar:reloadIcons(); ISInventoryPage.renderDirty = true -- needed to remove from queue / start next. ISBaseTimedAction.perform(self); end function ISDetachItemHotbar:animEvent(event, parameter) if event == 'detachConnect' then local hotbar = getPlayerHotbar(self.character:getPlayerNum()); hotbar.chr:removeAttachedItem(self.item); self:setOverrideHandModels(self.item, nil) end end function ISDetachItemHotbar:new(character, item) local o = {} setmetatable(o, self) self.__index = self o.character = character; o.item = item; o.stopOnWalk = false; o.stopOnRun = true; o.equipped = character:isEquipped(item); o.hotbar = getPlayerHotbar(o.character:getPlayerNum()); o.fromHotbar = true; o.useProgressBar = false; o.ignoreHandsWounds = true; o.maxTime = 25; if o.equipped then o.maxTime = 1; end if o.character:isTimedActionInstant() then o.maxTime = 1 end return o; end
Button = script.parent local BACKGROUNDIMAGE = script:GetCustomProperty("BackgroundImage"):WaitForObject() local IsEnabled = script:GetCustomProperty("IsEnabled") local Slot = script:GetCustomProperty("Slot") local Level = script:GetCustomProperty("Level") local LOCAL_PLAYER = Game.GetLocalPlayer() local CurrentSlot = 1 local HOVER_SOUND = script:GetCustomProperty("HOVER_SOUND") local DefaultFontsize = Button.fontSize function UpdateSelected() if(Slot == CurrentSlot) then BACKGROUNDIMAGE.visibility = Visibility.INHERIT else BACKGROUNDIMAGE.visibility = Visibility.FORCE_OFF end end function UpdateLevel() if not IsEnabled then Button.isInteractable = false Button.text = string.format( "LOADOUT INACTIVE") Button.fontSize = 8 return end if LOCAL_PLAYER:GetResource("Level") >= Level then Button.isInteractable = true Button.text = string.format( "LOADOUT %d", Slot) Button.fontSize = DefaultFontsize else Button.isInteractable = false Button.text = string.format("Level %d is required", Level ) Button.fontSize = 8 end end UpdateLevel() Button.releasedEvent:Connect(function() print(string.format( "Swapping to slot %d", Slot)) Events.BroadcastToServer("SetSlot", Slot) Events.Broadcast("SetSlot", Slot) if not LOCAL_PLAYER.isDead then Events.Broadcast("SwapPanelForceClose") end end) Button.hoveredEvent:Connect(function() Events.Broadcast("HoveredEquip", Slot) World.SpawnAsset(HOVER_SOUND) end) Button.unhoveredEvent:Connect(function() Events.Broadcast("ClearHover") end) Events.Connect("SetSlot",function(val) CurrentSlot = val UpdateSelected() end) LOCAL_PLAYER.resourceChangedEvent:Connect(function(_,propname) if(propname == "EquipSlot") then CurrentSlot = LOCAL_PLAYER:GetResource("EquipSlot") end if propname == "Level" then UpdateLevel() end UpdateSelected() end) function Updatethroughresource() CurrentSlot = LOCAL_PLAYER:GetResource("EquipSlot") UpdateSelected() end Task.Wait() Updatethroughresource()
-- Configure NVim Web Devicons -- require("nvim-web-devicons").setup({ -- Your personal icons can go here. override = {}, -- Globally enable default icons. default = true })
--[=[ Utility for Roblox character objects that involve promises. @class CharacterPromiseUtils ]=] local require = require(script.Parent.loader).load(script) local Maid = require("Maid") local Promise = require("Promise") local CharacterPromiseUtils = {} --[=[ Returns a promise that will resolve once a character exists. @param player Player @return Promise<Model> ]=] function CharacterPromiseUtils.promiseCharacter(player) assert(typeof(player) == "Instance", "Bad player") local promise = Promise.new() if player.Character then promise:Resolve(player.Character) return promise end local maid = Maid.new() maid:GiveTask(player.CharacterAdded:Connect(function(character) promise:Resolve(character) end)) promise:Finally(function() maid:DoCleaning() end) return promise end return CharacterPromiseUtils
--rewrite this lib (P.S: done) --P.S: air stands for Advanced Input Recognition, although technically it's not entirely advanced air = {} air.match_strings = function(string) local strings = {} string = string:gsub("\"(.-[^\\])\"",function(capt) string_id = string_id + 1 strings["%str"..string_id] = capt:gsub("\\\"","\"") return " %str"..string_id end) return string,strings end --this table will look up special types special_case = { ["voiceChannel"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local channel = guild:getChannel(id:match("(%d+)[^%d]*$")) if tostring(channel):match("^GuildVoiceChannel: ") then return true,channel else return false end end, ["textChannel"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local channel = guild:getChannel(id:match("(%d+)[^%d]*$")) if tostring(channel):match("^GuildTextChannel: ") then return true,channel else return false end end, ["messageLink"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local channelId,messageId = id:match("(%d+)/(%d+)[^%d]*$") channel = guild:getChannel(channelId) if tostring(channel):find("GuildTextChannel") then message = channel:getMessage(messageId) if message then return true,message end end return false end, ["role"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local role = guild:getRole(id:match("(%d+)[^%d]*$")) if role then return true,role else return false end end, ["member"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local member = guild:getMember(id:match("(%d+)[^%d]*$")) if member then return true,member else return false end end, ["emoji"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local emoji = guild:getEmoji(id:match("(%d+)[^%d]*$")) if emoji then return true,emoji else return false end end, ["ban"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local ban = guild:getBan(id:match("(%d+)[^%d]*$")) if ban then return true,ban else return false end end, ["channel"] = function(id,client,guild_id) local guild = client:getGuild(guild_id) local channel = guild:getChannel(id:match("(%d+)[^%d]*$")) if channel then return true,channel else return false end end, ["user"] = function(id,client,guild_id) local user = client:getUser(id:match("(%d+)[^%d]*$")) if user then return true,user end return false end, ["id"] = function(id) if tonumber(id:match("(%d+)[^%d]*$")) and tostring(id:match("(%d+)[^%d]*$")):len() > 10 then return true,id end return false end } air.parse = function(string,argmatch,client,guild_id) local args,opts = {},{} local string_id = 0 local strings = {} string = string:gsub("[%s\n]+\"(.-[^\\])\"",function(capt) string_id = string_id + 1 strings["%str"..string_id] = capt:gsub("\\\"","\"") return " %str"..string_id end) string = string:gsub("[%s\n]+%-%-(%w+)=\"(.-[^\\])\"",function(name,value) opts[name] = value:gsub("\\\"","\"") return "" end) string = string:gsub("[%s\n]+%-%-(%w+)=(%S+)",function(name,value) opts[name] = value return "" end) string = string:gsub("[%s\n]+%-%-(%w+)",function(name) opts[name] = true return "" end) string = string:gsub("[%s\n]+%-(%w+)",function(args) args:gsub(".",function(key) opts[key] = true end) return "" end) string:gsub("([^%s\n]+)",function(match) table.insert(args,match) end) for k,v in pairs(args) do if v:match("%%str%d+") then if strings[v] then args[k] = strings[v] end end end if argmatch and #argmatch > 0 then local match,err = false local new_args = {} for k,v in pairs(argmatch) do if not args[k] then match = false err = "Missing arguments: "..table.concat(argmatch,", ",k) break end if v == "number" and tonumber(args[k]) then match = true new_args[k] = tonumber(args[k]) elseif v == "string" then match = true new_args[k] = args[k] elseif special_case[v] then match,new_args[k] = special_case[v](args[k],client,guild_id) else match = false end if match == false then err = "Type mismatch for argument "..k..": "..argmatch[k].." expected." break end end for k,v in pairs(args) do if not new_args[k] then new_args[k] = v end end return match,new_args,opts,err else return true,args,opts end end return air
return { chongzhi_rank={ { opengame_day=7, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=7, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=7, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=7, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=7, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=7, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=7, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=14, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=14, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=14, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=14, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=14, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=14, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=14, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=21, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=21, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=21, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=21, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=21, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=21, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=21, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=28, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=28, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=28, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=28, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=28, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=28, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=28, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=35, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=35, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=35, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=35, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=35, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=35, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=35, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=42, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=42, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=42, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=42, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=42, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=42, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=42, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=49, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=49, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=49, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=49, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=49, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=49, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=49, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=999999, rank_index=0, reward_item={ item_id=30519, num=1, is_bind=1 }, limit_chongzhi=6888 }, { opengame_day=999999, rank_index=1, reward_item={ item_id=30520, num=1, is_bind=1 }, limit_chongzhi=5888 }, { opengame_day=999999, rank_index=2, reward_item={ item_id=30521, num=1, is_bind=1 }, limit_chongzhi=3888 }, { opengame_day=999999, rank_index=3, reward_item={ item_id=30522, num=1, is_bind=1 }, limit_chongzhi=1888 }, { opengame_day=999999, rank_index=4, reward_item={ item_id=30523, num=1, is_bind=1 }, limit_chongzhi=888 }, { opengame_day=999999, rank_index=5, reward_item={ item_id=30524, num=1, is_bind=1 }, limit_chongzhi=88 }, { opengame_day=999999, rank_index="6-9", reward_item={ item_id=30525, num=1, is_bind=1 }, limit_chongzhi=88 } }, rand_total_chongzhi={ { opengame_day=7, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=7, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=7, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=7, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=7, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=7, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=7, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=7, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=7, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=7, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=14, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=14, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=14, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=14, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=14, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=14, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=14, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=14, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=14, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=14, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=21, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=21, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=21, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=21, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=21, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=21, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=21, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=21, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=21, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=21, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=28, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=28, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=28, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=28, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=28, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=28, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=28, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=28, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=28, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=28, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=35, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=35, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=35, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=35, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=35, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=35, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=35, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=35, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=35, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=35, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=42, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=42, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=42, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=42, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=42, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=42, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=42, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=42, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=42, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=42, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=49, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=49, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=49, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=49, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=49, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=49, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=49, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=49, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=49, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=49, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } }, { opengame_day=999999, seq=0, need_chongzhi=500, reward_item={ [0]={ item_id=30390, num=1, is_bind=1 } } }, { opengame_day=999999, seq=1, need_chongzhi=1000, reward_item={ [0]={ item_id=30391, num=1, is_bind=1 } } }, { opengame_day=999999, seq=2, need_chongzhi=2000, reward_item={ [0]={ item_id=30392, num=1, is_bind=1 } } }, { opengame_day=999999, seq=3, need_chongzhi=3000, reward_item={ [0]={ item_id=30393, num=1, is_bind=1 } } }, { opengame_day=999999, seq=4, need_chongzhi=6000, reward_item={ [0]={ item_id=30394, num=1, is_bind=1 } } }, { opengame_day=999999, seq=5, need_chongzhi=12000, reward_item={ [0]={ item_id=30395, num=1, is_bind=1 } } }, { opengame_day=999999, seq=6, need_chongzhi=25000, reward_item={ [0]={ item_id=30396, num=1, is_bind=1 } } }, { opengame_day=999999, seq=7, need_chongzhi=50000, reward_item={ [0]={ item_id=30397, num=1, is_bind=1 } } }, { opengame_day=999999, seq=8, need_chongzhi=100000, reward_item={ [0]={ item_id=30398, num=1, is_bind=1 } } }, { opengame_day=999999, seq=9, need_chongzhi=200000, reward_item={ [0]={ item_id=30399, num=1, is_bind=1 } } } } }
-- vim: ft=lua ts=2 sw=2 et: --- Library Functions local lib={} --- Return a number that is not above or below `lo` or `hi`. -- If outside that range, return one of `lo` and `hi`. -- @number z -- @number lo -- @number hi -- @return number function lib.cap(z,lo,hi) if z < lo then return lo elseif z > hi then return hi else return z end end --- Return a deep copy of `obj` (avoiding infinite loops). -- @param obj -- @return the copy function lib.copy(obj) local old,new if type(obj) ~= 'table' then return obj end if old and old[obj] then return old[obj] end old, new = old or {}, {} old[obj] = new for k, v in pairs(obj) do new[lib.copy(k, old)]=lib.copy(v, old) end return setmetatable(new, getmetatable(obj)) end --- Return a real number within bounds `lo` and `hi`. -- @number lo -- @number hi -- @return float function lib.from(lo,hi) return lo+(hi-lo)*math.random() end --- Round a number to a positive integer. -- @number x -- @return int function lib.int(x) return (x+0.5)//1 end --- Iterator: returns the key/values of a `table`, -- sorted by they `key`. -- @tab t -- @return func function lib.keys(t) local i,u = 0,{} for k,_ in pairs(t) do u[#u+1] = k end table.sort(u) return function () if i < #u then i = i+1 return u[i], t[u[i]] end end end --- Print a table on one line -- @tab t : table to print -- @string pre : some text to prepend to the output (defaults to "") function lib.o(t,pre) local s, sep = "", "" for _,v in pairs(t or {}) do s = s..sep..tostring(v); sep=", " end print((pre or "") .. '{' .. s .. '}') end --- Recursively print a table `t`, with indentation. -- @tab t -- @string pre : what to write before the table -- @string indent : defaults to `""` then grows with recursion. function lib.oo(t,pre, indent) local pre = pre or "" local indent = indent or 0 if indent < 10 then for k, v in lib.keys(t or {}) do if not (type(k)=='string' and k:match("^_")) then if not (type(v)=='function') then local fmt = pre..string.rep("| ",indent)..tostring(k)..": " if type(v) == "table" then print(fmt) lib.oo(v, pre, indent+1) else print(fmt .. tostring(v)) end end end end end end --- Report height on a normal curve. If above -- or below mean plus-or-minus 4 standard deviations, -- then return 0. -- @number x -- @number mu -- @number sd -- @return number function lib.normpdf(x, mu, sd) mu = mu or 0 sd = sd or 1 if x < mu-4*sd then return 0 end if x > mu+4*sd then return 0 end return (1 / (sd * math.sqrt(2 * math.pi))) * math.exp(-(((x - mu) * (x - mu)) / (2 * sd^2))) end --- Report rogue locals function lib.rogues() local ignore= { the=true, tostring=true, tonumber=true, assert=true, rawlen=true, pairs=true, ipairs=true, pcall=true, type=true, print=true, rawequal=true, setmetatable=true, require=true, load=true, rawset=true, next=true, getmetatable=true, select=true, error=true, dofile=true, loadfile=true, jit=true, utf8=true, math=true, package=true, table=true, coroutine=true, bit=true, os=true, io=true, bit32=true, string=true, arg=true, debug=true, _VERSION=true, _G=true, collectgarbage=true, xpcall=true, rawget=true, } for k,v in pairs( _G ) do if not ignore[k] then if k:match("^[^A-Z]") then print("-- ROGUE ["..k.."]") end end end end function lib.round(num, places) local mult = 10^(places or 0) return math.floor(num * mult + 0.5) / mult end --- Polymorphic dispatching -- @fun klass : meta class -- @tab inits : `key`/`value` initializations function lib.uses(klass,has) local new = lib.copy(klass or {}) for k,v in pairs(has or {}) do new[k] = v end setmetatable(new, klass) klass.__index = klass return new end --- Return a real number `z` wrapped within `lo` and `hi`. -- @number z -- @number lo -- @number hi -- @return number function lib.within(z,lo,hi) return (z>=lo and z<=hi) and z or lo+z%(hi-lo) end return lib
local fio = require('fio') local t = require('luatest') local g = t.group() local h = require('test.helper') g.before_each(function() g.cluster = h.Cluster:new({ datadir = fio.tempdir(), server_command = h.entrypoint('srv_multisharding'), cookie = h.random_cookie(), replicasets = { { alias = 'router', roles = {}, servers = 1 }, { alias = 'storage-hot', roles = {}, servers = 1 }, { alias = 'storage-cold', roles = {}, servers = 1 }, }, }) g.cluster:start() g.storage_hot = g.cluster:server('storage-hot-1') g.storage_cold = g.cluster:server('storage-cold-1') end) g.after_each(function() g.cluster:stop() fio.rmtree(g.cluster.datadir) end) local function build_issue_msg(main, group) return { level = 'warning', topic = 'vshard', message = ([[Group "%s" wasn't bootstrapped: Sharding config is empty. ]] .. [[There may be no instances in this group.]]):format(group), instance_uuid = main.instance_uuid, replicaset_uuid = main.replicaset_uuid, } end g.test_bootstrap_vshard_by_group = function() local main = g.cluster.main_server -- try to bootsrap vshard without vshard-router t.assert_error_msg_contains('No remotes with role "vshard-router" available', g.cluster.bootstrap_vshard, g.cluster) -- setup vshard-router main:setup_replicaset({ roles = {'vshard-router'}, uuid = main.replicaset_uuid, }) -- bootstrap without storages g.cluster:bootstrap_vshard() t.assert_equals(h.list_cluster_issues(main), { build_issue_msg(main, 'cold'), build_issue_msg(main, 'hot'), }) -- setup storage-hot main:setup_replicaset({ roles = {'vshard-storage'}, vshard_group = 'hot', uuid = g.storage_hot.replicaset_uuid, weight = 1, }) -- bootstrap only hot group g.cluster:bootstrap_vshard() t.assert_equals(h.list_cluster_issues(main), { build_issue_msg(main, 'cold') }) -- setup server with cold group g.storage_cold:setup_replicaset({ roles = {'vshard-storage'}, vshard_group = 'cold', uuid = g.storage_cold.replicaset_uuid, weight = 1, }) -- bootstrap cold group g.cluster:bootstrap_vshard() t.assert_equals(h.list_cluster_issues(main), {}) -- try to bootstrap again t.assert_error_msg_contains('already bootstrapped', g.cluster.bootstrap_vshard, g.cluster) end
local utils = require("neo-tree.utils") local M = { FLAG = "<FLAG>", LIST = "<LIST>", PATH = "<PATH>", } -- For lists, the first value is the default value. local arguments = { action = { type = M.LIST, values = { "close", "focus", "show", }, }, position = { type = M.LIST, values = { "left", "right", --"top", --technically valid, but why show it if no one will use it? --"bottom", --technically valid, but why show it if no one will use it? "float", "current" } }, source = { type = M.LIST, values = { "filesystem", "buffers", "git_status", "migrations", } }, dir = { type = M.PATH, stat_type = "directory" }, reveal_file = { type = M.PATH, stat_type = "file" }, toggle = { type = M.FLAG }, reveal = { type = M.FLAG }, reveal_force_cwd = { type = M.FLAG }, } local arg_type_lookup = {} local list_args = {} local path_args = {} local flag_args = {} local reverse_lookup = {} for name, def in pairs(arguments) do arg_type_lookup[name] = def.type if def.type == M.LIST then table.insert(list_args, name) for _, vv in ipairs(def.values) do reverse_lookup[tostring(vv)] = name end elseif def.type == M.PATH then table.insert(path_args, name) elseif def.type == M.FLAG then table.insert(flag_args, name) reverse_lookup[name] = M.FLAG else error("Unknown type: " .. def.type) end end M.arguments = arguments M.list_args = list_args M.path_args = path_args M.flag_args = flag_args M.arg_type_lookup = arg_type_lookup M.reverse_lookup = reverse_lookup M.resolve_path = function(path, validate_type) local expanded = vim.fn.expand(path) local abs_path = vim.fn.fnamemodify(expanded, ":p") if validate_type then local stat = vim.loop.fs_stat(abs_path) if stat.type ~= validate_type then error("Invalid path: " .. path .. " is not a " .. validate_type) end end return abs_path end local parse_arg = function(result, arg) if type(arg) == "string" then local eq = arg:find("=") if eq then local key = arg:sub(1, eq - 1) local value = arg:sub(eq + 1) local def = arguments[key] if not def.type then error("Invalid argument: " .. arg) end if def.type == M.PATH then result[key] = M.resolve_path(value, def.stat_type) elseif def.type == M.FLAG then if value == "true" then result[key] = true elseif value == "false" then result[key] = false else error("Invalid value for " .. key .. ": " .. value) end else result[key] = value end else local value = arg local key = reverse_lookup[value] if key == nil then -- maybe it's a path local path = M.resolve_path(value) local stat = vim.loop.fs_stat(path) if stat then if stat.type == "directory" then result["dir"] = path elseif stat.type == "file" then result["reveal_file"] = path end else error("Invalid argument: " .. arg) end elseif key == M.FLAG then result[value] = true else result[key] = value end end end end M.parse = function(args, strict_checking) local result = {} if type(args) == "string" then args = utils.split(args, " ") end -- read args from user for _, arg in ipairs(args) do local success, err = pcall(parse_arg, result, arg) if strict_checking and not success then error(err) end end return result end return M
local wozy = { -- x,y,z,rx,ry,rz,model {-28.84,-273.45,5.5,0,0,180,407}, {-22.51,-273.4,5.5,0,0,180,407}, {-13.69,-273.4,5.5,0,0,180,407}, {-2.81,-291.60,5.59,0,0,90,544}, {-31.73,-290.24,5.45,0,0,270,400}, -- LV {1751.75,2070.74,11.07,0,0,180,407}, {1770.37,2072.38,11.07,0,0,180,407}, {1764.39,2069.11,11.37,0,0,180,544}, {1758.51,2068.71,11.36,0,0,180,544}, } for i,v in ipairs(wozy) do v.pojazd = createVehicle(v[7],v[1],v[2],v[3],v[4],v[5],v[6],"STRAZ") setElementData(v.pojazd,"straz:vehicle",true) setElementFrozen(v.pojazd,true) setVehicleDamageProof(v.pojazd,true) setVehicleColor(v.pojazd,255,0,0,255,255,255) addVehicleUpgrade(v.pojazd,1025) toggleVehicleRespawn(v.pojazd,true) end function enterVehicle(player,seat,jacked) if (getElementData(source,"straz:vehicle")) and (not getElementData(player,"duty:straz")) then cancelEvent() outputChatBox("Nie jesteś strażakiem - rozpocznij pracę w remizie.",player) else setElementFrozen(source,false) setVehicleDamageProof(source,false) end end addEventHandler("onVehicleStartEnter",getRootElement(),enterVehicle)
AddCSLuaFile() DEFINE_BASECLASS( "sent_tv_io_base" ) ENT.PrintName = "IO: Capacitor" ENT.Author = "raubana" ENT.Information = "" ENT.Category = "Tunnel Vision" ENT.Editable = true ENT.Spawnable = true ENT.AdminOnly = true ENT.RenderGroup = RENDERGROUP_OPAQUE ENT.NumInputs = 2 ENT.NumOutputs = 1 list.Add( "TV_IO_ents", "sent_tv_io_capacitor" ) function ENT:Initialize() self:SetModel( "models/tunnelvision/io_models/io_capacitor.mdl" ) self:DrawShadow( false ) if SERVER then self:PhysicsInit(SOLID_VPHYSICS) self:GetPhysicsObject():EnableMotion(false) self:IOInit() if self:GetThreshold() == 0 then self:SetThreshold( 60 ) end if self:GetMaximum() == 0 then self:SetMaximum( 90 ) end if self.start_state then self:SetState( self.start_state ) self:DeriveIOFromState() self.start_state = nil end if self.start_charge then self:SetCharge( self.start_charge ) self.start_charge = nil end end end function ENT:SetupDataTables() self:NetworkVar( "Int", 0, "State" ) self:NetworkVar( "Int", 1, "Charge", { KeyName = "charge", Edit = { type = "Int", min = 0, max = 600 } } ) self:NetworkVar( "Int", 2, "Threshold", { KeyName = "threshold", Edit = { type = "Int", min = 1, max = 600 } } ) self:NetworkVar( "Int", 3, "Maximum", { KeyName = "maximum", Edit = { type = "Int", min = 1, max = 600 } } ) end function ENT:GetInputPos( x ) local pos = self:GetPos() if x == 1 then pos = pos + (self:GetForward() * 0.5) + (self:GetRight()*2) + (self:GetUp() * 1.75) else pos = pos + (self:GetForward() * 0.5) + (self:GetRight()*2) - (self:GetUp() * 1.75) end return pos end function ENT:GetOutputPos( x ) local pos = self:GetPos() pos = pos + (self:GetForward()*0.5) - (self:GetRight()*2) return pos end if SERVER then function ENT:KeyValue(key, value) if key == "state" then self.start_state = tonumber( value ) elseif key == "charge" then self.start_charge = tonumber( value ) elseif key == "threshold" then self:SetThreshold( tonumber( value ) ) elseif key == "maximum" then self:SetMaximum( tonumber( value ) ) end end function ENT:Update() self:UpdateInputs() self:StoreCopyOfOutputs() local in1 = self:GetInputX(1) local in2 = self:GetInputX(2) local charge = self:GetCharge() if in2 then charge = 0 elseif in1 then charge = math.min( charge + 1, self:GetMaximum() ) else charge = math.max( charge - 1, 0 ) end self:SetOutputX(1, charge >= self:GetThreshold() ) if self:GetOutputX( 1 ) then if in1 then charge = self:GetMaximum() end else if not in1 then charge = 0 end end self:SetCharge( charge ) -- I need to check if I'm in a stable state. -- As long as I'm not stable I'll need to keep updating. local is_stable = (in1 and charge >= self:GetMaximum()) or ((not in1) and charge <= 0 ) if not is_stable then hook.Call( "TV_IO_MarkEntityToBeUpdated", nil, self ) end self:UpdateIOState() self:MarkChangedOutputs() end function ENT:Pickle( ent_list, cable_list ) local data = {} data.threshold = self:GetThreshold() data.maximum = self:GetMaximum() data.charge = self:GetCharge() data.class = self:GetClass() data.pos = self:GetPos() data.angles = self:GetAngles() data.state = self:GetState() return util.TableToJSON( data ) end function ENT:UnPickle( data, ent_list ) self:SetPos( data.pos ) self:SetAngles( data.angles ) self:SetState( data.state ) self:DeriveIOFromState() self:SetThreshold( data.threshold ) self:SetMaximum( data.maximum ) self:SetCharge( data.charge ) end end if CLIENT then local DEBUGMODE = GetConVar("tv_io_debug") local SCALE = 0.1 local WIDTH = 2/SCALE local HEIGHT = 4.6/SCALE function ENT:Draw() if DEBUGMODE and DEBUGMODE:GetBool() then for x = 1, self.NumInputs do self:DrawConnection( self:GetInputPos(x), self:GetIOState( x ) ) end for x = 1, self.NumOutputs do self:DrawConnection( self:GetOutputPos(x), self:GetIOState( self.NumInputs + x ) ) end end self:DrawModel() local charge = self:GetCharge() local threshold = self:GetThreshold() local maximum = self:GetMaximum() local my_pos = self:GetPos() local my_ang = self:GetAngles() local new_ang = 1.0 * my_ang new_ang:RotateAroundAxis( new_ang:Right(), -90 ) new_ang:RotateAroundAxis( new_ang:Up(), 90 ) local offset = Vector( 1.1, -1, 2.3 ) offset:Rotate( my_ang ) cam.Start3D2D( my_pos + offset, new_ang, SCALE ) surface.SetDrawColor( color_black ) surface.DrawRect( 1, Lerp( charge/maximum, HEIGHT-1, 1 ), WIDTH-2-(WIDTH*0.33), 1 ) local y = Lerp( threshold/maximum, HEIGHT-1, 1 ) surface.DrawRect( WIDTH*0.66, 1, WIDTH*0.33-0, y ) cam.End3D2D() end end