content
stringlengths
5
1.05M
local KUI, E, L, V, P, G = unpack(select(2, ...)) if G["KlixUI"] == nil then G["KlixUI"] = {} end G["KlixUI"] = { -- General ["gameMenu"] = true, ["speedyLoot"] = true, ["easyDelete"] = true, ["cinematic"] = { ["kill"] = false, ["enableSound"] = true, ["talkingheadSound"] = true, }, }
local MAJOR_VERSION = "Threat-2.0" local MINOR_VERSION = 90000 + tonumber(("$Revision: 7 $"):match("%d+")) if MINOR_VERSION > _G.ThreatLib_MINOR_VERSION then _G.ThreatLib_MINOR_VERSION = MINOR_VERSION end if select(2, _G.UnitClass("player")) ~= "WARRIOR" then return end ThreatLib_funcs[#ThreatLib_funcs+1] = function() local _G = _G local max = _G.max local tonumber = _G.tonumber local type = _G.type local select = _G.select local GetTalentInfo = _G.GetTalentInfo local GetShapeshiftForm = _G.GetShapeshiftForm local GetSpellInfo = _G.GetSpellInfo local pairs, ipairs = _G.pairs, _G.ipairs local GetTime = _G.GetTime local UnitDebuff = _G.UnitDebuff local UnitLevel = _G.UnitLevel local ThreatLib = _G.ThreatLib local Warrior = ThreatLib:GetOrCreateModule("Player") local MSBTTalentMod = 1.0 local MSBTMod = 1.0 local zerkerStanceMod = 0 local sunderFactor = 301 / 67 local shieldBashFactor = 230 / 64 local revengeFactor = 201 / 70 local heroicStrikeFactor = 220 / 70 local shieldSlamFactor = 307 / 70 local cleaveFactor = 130 / 68 local hamstringFactor = 181 / 67 local mockingBlowFactor = 290 / 65 local battleShoutFactor = 1 local demoShoutFactor = 56 / 70 local sunderName = GetSpellInfo(7386) local threatValues = { sunder = { [7386] = sunderFactor * 10, [7405] = sunderFactor * 22, [8380] = sunderFactor * 34, [11596] = sunderFactor * 46, [11597] = sunderFactor * 58, [25225] = 301 }, shieldBash = { [72] = shieldBashFactor * 12, [1671] = shieldBashFactor * 32, [1672] = shieldBashFactor * 52, [29704] = 230 }, revenge = { [6572] = revengeFactor * 14, [6574] = revengeFactor * 24, [7379] = revengeFactor * 34, [11600] = revengeFactor * 44, [11601] = revengeFactor * 54, [25288] = revengeFactor * 60, [25269] = revengeFactor * 63, [30357] = 201 }, heroicStrike = { [78] = heroicStrikeFactor * 1, [284] = heroicStrikeFactor * 8, [285] = heroicStrikeFactor * 16, [1608] = heroicStrikeFactor * 24, [11564] = heroicStrikeFactor * 32, [11565] = heroicStrikeFactor * 40, [11566] = heroicStrikeFactor * 48, [11567] = 145, [25286] = 173, [29707] = 196, [30324] = 220 }, shieldSlam = { [23922] = shieldSlamFactor * 40, [23923] = shieldSlamFactor * 48, [23924] = shieldSlamFactor * 54, [23925] = 250, [25258] = 286, [30356] = 307 }, cleave = { [845] = cleaveFactor * 20, [7369] = cleaveFactor * 30, [11608] = cleaveFactor * 40, [11609] = cleaveFactor * 50, [20569] = 100, [25231] = 130 }, hamstring = { [1715] = hamstringFactor * 8, [7372] = hamstringFactor * 32, [7373] = hamstringFactor * 54, [25212] = 181 }, mockingBlow = { [694] = mockingBlowFactor * 16, [7400] = mockingBlowFactor * 26, [7402] = mockingBlowFactor * 36, [20559] = mockingBlowFactor * 46, [20560] = mockingBlowFactor * 56, [25266] = 290 }, battleShout = { [6673] = battleShoutFactor * 1, [5242] = battleShoutFactor * 12, [6192] = battleShoutFactor * 22, [11549] = battleShoutFactor * 32, [11550] = battleShoutFactor * 42, [11551] = battleShoutFactor * 52, [25289] = battleShoutFactor * 60, [2048] = 69 }, demoShout = { [1160] = demoShoutFactor * 14, [6190] = demoShoutFactor * 24, [11554] = demoShoutFactor * 34, [11555] = demoShoutFactor * 44, [11556] = demoShoutFactor * 54, [25202] = demoShoutFactor * 62, [25203] = 56 }, commandingShout = { [469] = 58 }, thunderclap = { [6343] = true, [8198] = true, [8204] = true, [8205] = true, [11580] = true, [11581] = true, [25264] = true, }, execute = { [5308] = true, [20658] = true, [20660] = true, [20661] = true, [20662] = true, [25234] = true, [25236] = true, }, disarm = { [676] = 104 }, devastate = { [20243] = true, [30016] = true, [30022] = true } } local msbtIDs = { -- Mortal Strike 12294, 21551, 21552, 21553, 25248, 30330, -- Bloodthirst 23881, 23892, 23893, 23894, 25251, 30335 } local playerLevel = UnitLevel("player") local function init(self, t, f) local func = function(self, spellID, target) self:AddTargetThreat(target, f(self, spellID)) end for k, v in pairs(t) do self.CastLandedHandlers[k] = func end end function Warrior:ClassInit() -- Taunt self.CastLandedHandlers[355] = self.Taunt -- Non-transactional abilities init(self, threatValues.heroicStrike, self.HeroicStrike) init(self, threatValues.shieldBash, self.ShieldBash) init(self, threatValues.shieldSlam, self.ShieldSlam) init(self, threatValues.revenge, self.Revenge) init(self, threatValues.mockingBlow, self.MockingBlow) init(self, threatValues.hamstring, self.Hamstring) init(self, threatValues.disarm, self.Disarm) init(self, threatValues.devastate, self.Devastate) -- Transactional stuff -- Sunder Armor local func = function(self, spellID, target) self:AddTargetThreatTransactional(target, spellID, self:SunderArmor(spellID)) end for k, v in pairs(threatValues.sunder) do self.CastHandlers[k] = func self.MobDebuffHandlers[k] = self.GetDevastateSunder end -- Ability damage modifiers for k, v in pairs(threatValues.thunderclap) do self.AbilityHandlers[v] = self.Thunderclap end for k, v in pairs(threatValues.execute) do self.AbilityHandlers[v] = self.Execute end for _, k in ipairs(msbtIDs) do self.AbilityHandlers[k] = self.MSBT end msbtIDs = nil -- Shouts -- Commanding Shout --[[ for _, k in ipairs(threatValues.commandingShout) do self.CastHandlers[k] = function(spellID) self:AddThreat(68 * self:threatMods()) end end ]]-- -- self.CastHandlers[BS["Battle Shout"]] = function(self, rank) self:AddThreat(self:BattleShout(rank)) end -- self.CastHandlers[BS["Demoralizing Shout"]] = function(self, rank) self:AddTargetThreat(self:DemoShoutThreat(rank)) end -- self.CastMissHandlers[BS["Demoralizing Shout"]] = self.DemoShoutMiss -- Set names don't need to be localized. self.itemSets = { ["Might"] = { 16866, 16867, 16868, 16862, 16864, 16861, 16865, 16863 } } self.lastDevastateTime = 0 end function Warrior:ClassEnable() self:GetStanceThreatMod() self:RegisterEvent("UPDATE_SHAPESHIFT_FORM", "GetStanceThreatMod" ) end function Warrior:ScanTalents() local rank = _G.select(5, GetTalentInfo(3, 9)) self.defianceMod = 1 + (0.05 * rank) -- Tactical mastery local rank = _G.select(5, GetTalentInfo(3, 2)) MSBTTalentMod = 1 + (0.21 * rank) -- Improved berserker stance local rank = _G.select(5, GetTalentInfo(2, 20)) zerkerStanceMod = 0.02 * rank -- We need to watch debuffs if we're devastate, unfortunately. if _G.select(5, GetTalentInfo(3, 22)) > 0 then self:RegisterEvent("CHAT_MSG_SPELL_PERIODIC_CREATURE_DAMAGE", "GetDevastateSunder") end end function Warrior:GetStanceThreatMod() self.isTanking = false if GetShapeshiftForm() == 2 then self.passiveThreatModifiers = 1.3 * self.defianceMod MSBTMod = MSBTTalentMod self.isTanking = true elseif GetShapeshiftForm() == 3 then -- Currently assuming that the zerker change is multiplicative self.passiveThreatModifiers = 0.8 * (1 - zerkerStanceMod) -- Change to this if it tests out to additive -- self.passiveThreatModifiers = 0.8 - zerkerStanceMod MSBTMod = 1.0 else self.passiveThreatModifiers = 0.8 MSBTMod = 1.0 end self.totalThreatMods = nil -- Needed to recalc total mods end function Warrior:SunderArmor(spellID) local sunderMod = 1.0 if self:getWornSetPieces("Might") >= 8 then sunderMod = 1.15; end local threat = threatValues.sunder[spellID] return threat * sunderMod * self:threatMods() end function Warrior:Taunt(spellID, target) local targetThreat = ThreatLib:GetThreat(UnitGUID("targettarget"), target) local myThreat = ThreatLib:GetThreat(UnitGUID("player"), target) if targetThreat > 0 and targetThreat > myThreat then pendingTauntTarget = target pendingTauntOffset = targetThreat-myThreat elseif targetThreat == 0 then local maxThreat = ThreatLib:GetMaxThreatOnTarget(target) pendingTauntTarget = target pendingTauntOffset = maxThreat-myThreat end self.nextEventHook = self.TauntNextHook end function Warrior:TauntNextHook(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, spellID) if pendingTauntTarget and (eventtype ~= 'SPELL_MISSED' or spellID ~= 355) then self:AddTargetThreat(pendingTauntTarget, pendingTauntOffset) ThreatLib:PublishThreat() end pendingTauntTarget = nil pendingTauntOffset = nil end function Warrior:HeroicStrike(spellID) return threatValues.heroicStrike[spellID] * self:threatMods() end function Warrior:ShieldBash(spellID) return threatValues.shieldBash[spellID] * self:threatMods() end function Warrior:ShieldSlam(spellID) return threatValues.shieldSlam[spellID] * self:threatMods() end function Warrior:Revenge(spellID) return threatValues.revenge[spellID] * self:threatMods() end function Warrior:MockingBlow(spellID) return threatValues.mockingBlow[spellID] * self:threatMods() end function Warrior:Hamstring(spellID) return threatValues.hamstring[spellID] * self:threatMods() end function Warrior:Thunderclap(amount) return amount * 1.75 end function Warrior:Execute(amount) return amount * 1.25 end function Warrior:MSBT(amt) return amt * MSBTMod end function Warrior:Disarm(spellID) return threatValues.disarm[spellID] * self:threatMods() end local devastateThreat = {119, 134, 147, 162, 176, 176} function Warrior:Devastate(spellID) local threat = devastateThreat[1] for i = 1, 40 do local name, rank, texture, count, debuffType, duration, timeLeft = UnitDebuff("target", i) if not name then break end if timeLeft and name == sunderName then threat = devastateThreat[count] break end end self.lastDevastateTime = GetTime() return threat * self:threatMods() end -- This is an incredibly ugly hack, but will hopefully tide us over until 2.4. function Warrior:GetDevastateSunder(spellID, target) if GetTime() - self.lastDevastateTime < 2 then self:AddTargetThreat(target, self:SunderArmor(spellID)) end end end
package.path = "../?.lua;"..package.path local ps_common = require("lj2ps.ps_common") local TokenType = ps_common.TokenType local PSVM = require("lj2ps.ps_vm") local Scanner = require("lj2ps.ps_scanner") local octetstream = require("lj2ps.octetstream") local function test_tokens() local vm = PSVM() local bs = octetstream([[ % comment 123 (This is a string) (These \ two strings \ are the same.) (These two strings are the same.) (This string has a newline at the end of it ) (So does this one\n) ]]) local scnr = Scanner(vm, bs) for _, token in scnr:tokens(bs) do print(token) end end local function test_token_type() print("TokenType, size: ", #TokenType) for k,v in pairs(TokenType) do print(k,v) end end local function test_name() local bs = octetstream([[ abc Offset $$ 23A 13-456 a.b $MyDict @pattern /Absolute ]]) for _, token in ps_scanner(bs) do print(token) end end local function test_array() local bs = octetstream([[ [123 /abc (xyz)] ]]) for _, token in ps_scanner(bs) do print(token) end end local function test_procedure() local bs = octetstream([[ {add 2 div} ]]) for _, token in ps_scanner(bs) do print(token) end end test_tokens() --test_token_type() --test_name() --test_array() --test_procedure()
-- schema.lua local typedefs = require "kong.db.schema.typedefs" return { name = "caesar-hello", fields = { { config = { type = "record", fields = { { environment = { type = "string", required = true, one_of = { "production", "development", }, }, }, { server = { type = "record", fields = { { host = typedefs.host { default = "example.com", }, }, { port = { type = "number", default = 80, between = { 0, 65534 }, }, }, }, }, }, }, }, }, }, }
local g_Strings = {} local g_Patterns = {} local g_Mui = {} local g_Lang addEvent ( "onClientLangChange", true ) addEvent ( "onClientLangChanged" ) local function MuiLoadInternal ( path ) local strings = {} local patterns = {} local node = xmlLoadFile ( path ) if ( node ) then local i = 0 while ( true ) do local subnode = xmlFindChild ( node, "msg", i ) if ( not subnode ) then break end i = i + 1 local id = xmlNodeGetAttribute ( subnode, "id" ) local value = xmlNodeGetValue ( subnode ) if ( id and value ) then strings[id] = value end local pattern = xmlNodeGetAttribute ( subnode, "pattern" ) if ( pattern and value ) then patterns[pattern] = value end end xmlUnloadFile ( node ) end return { strings, patterns } end local function MuiLoad ( path ) local lang = MuiLoadInternal ( path ) g_Strings = lang[1] g_Patterns = lang[2] end function MuiGetMsg ( text ) if ( g_Strings[text] ) then return g_Strings[text] end for pattern, repl in pairs ( g_Patterns ) do text = string.gsub ( text, pattern, repl ) end return text end local _guiSetText = guiSetText function guiSetText ( guiElement, text ) if ( g_Mui[guiElement] ) then g_Mui[guiElement] = text text = MuiGetMsg ( text ) end return _guiSetText ( guiElement, text ) end local _guiCreateWindow = guiCreateWindow function guiCreateWindow ( x, y, width, height, titleBarText, ... ) local wnd = _guiCreateWindow ( x, y, width, height, MuiGetMsg ( titleBarText ), ... ) g_Mui[wnd] = titleBarText return wnd end local _guiCreateTab = guiCreateTab function guiCreateTab ( text, parent ) local tab = _guiCreateTab ( MuiGetMsg ( text ), parent ) g_Mui[tab] = text return tab end local _guiCreateButton = guiCreateButton function guiCreateButton ( x, y, width, height, text, ... ) local btn = _guiCreateButton ( x, y, width, height, MuiGetMsg ( text), ... ) g_Mui[btn] = text return btn end local _guiCreateCheckBox = guiCreateCheckBox function guiCreateCheckBox ( x, y, width, height, text, ... ) local checkbox = _guiCreateCheckBox ( x, y, width, height, MuiGetMsg ( text ), ... ) g_Mui[checkbox] = text return checkbox end local _guiCreateLabel = guiCreateLabel function guiCreateLabel ( x, y, width, height, text, ... ) local label = _guiCreateLabel ( x, y, width, height, MuiGetMsg ( text ), ... ) g_Mui[label] = text return label end local _guiGridListAddColumn = guiGridListAddColumn function guiGridListAddColumn ( gridList, title, ... ) return _guiGridListAddColumn ( gridList, MuiGetMsg ( title ), ... ) end local _guiGridListSetItemText = guiGridListSetItemText function guiGridListSetItemText ( gridList, rowIndex, columnIndex, text, ... ) return _guiGridListSetItemText ( gridList, rowIndex, columnIndex, MuiGetMsg ( text ), ... ) end local _outputChatBox = outputChatBox function outputChatBox ( text, ... ) return _outputChatBox ( MuiGetMsg ( text ), ... ) end local _dxDrawText = dxDrawText function dxDrawText ( text, ... ) return _dxDrawText ( MuiGetMsg ( text ), ... ) end local function MuiUpdate () for el, text in pairs ( g_Mui ) do _guiSetText ( el, MuiGetMsg ( text ) ) end end function MuiSetLang ( lang ) assert(lang) if(lang ~= g_Lang) then MuiLoad("lang/"..tostring ( lang ).."_c.xml") MuiUpdate() triggerEvent("onClientLangChanged", getResourceRootElement()) g_Lang = lang end end local function MuiOnElementDestroy() if(source) then -- wtf? g_Mui[source] = nil end end addEventHandler("onClientLangChange", getResourceRootElement(), MuiSetLang) addEventHandler("onClientElementDestroy", getResourceRootElement(), MuiOnElementDestroy)
local CONSTANTS_API = require(script:GetCustomProperty("MetaAbilityProgressionConstants_API")) local mainManagerServer = script:GetCustomProperty("MainManagerServer"):WaitForObject() local tankGarage = script:GetCustomProperty("TANK_VP_TankGarage"):WaitForObject() local tankCount = script:GetCustomProperty("TankCount") local tankTemplates = script.parent local equippedTank = {} local resetOverride = false function GetEquippedTankTemplate(player, id) --print("Checking for tank with id: " .. id) if tonumber(id) <= tankCount and tonumber(id) > 0 then --print("Tank with given id found") return tankTemplates:GetCustomProperty(id) else --print("Returning default") return tankTemplates:GetCustomProperty("Default") end end function GetPlayer(playerId) local playerList = Game.GetPlayers() for _, player in pairs(playerList) do if player.id == playerId then return player end end return nil end function ChangeEquippedTank(player, id) player:SetResource(CONSTANTS_API.GetEquippedTankResource(), tonumber(id)) RemovePlayerEquipment(player) GivePlayerEquipment(player) end function ResetAllVehicles() local playerList = Game.GetPlayers() --resetOverride = true for _, player in pairs(playerList) do --RemovePlayerEquipment(player) player:Spawn() --GivePlayerEquipment(player) end --resetOverride = false end function OnPlayerRespawned(player, playerStart) player:DisableRagdoll() --player.isVisible = false Task.Wait(0.5) if resetOverride then return end RemovePlayerEquipment(player) local currentState = mainManagerServer:GetCustomProperty("GameState") if currentState ~= "VICTORY_STATE" and currentState ~= "CARD_STATE" then GivePlayerEquipment(player, playerStart) else player.isVisible = true player.animationStance = "unarmed_stance" player.isCollidable = true end end -- nil GivePlayerEquipment(Player) -- Gives the referenced equipment to the player function GivePlayerEquipment(player, playerStart) local resourceID = player:GetResource(CONSTANTS_API.GetEquippedTankResource()) local id = tostring(resourceID) if resourceID < 10 then id = "0" .. tostring(resourceID) end local playerPosition = player:GetWorldPosition() local playerRotation = player:GetWorldRotation() equippedTank[player] = World.SpawnAsset(GetEquippedTankTemplate(player, id), {parent = tankGarage, position = playerPosition, rotation = playerRotation}) Task.Wait(0.1) equippedTank[player].context.AssignDriver(player, playerStart) end -- nil RemovePlayerEquipment(Player) -- Removes the referenced requipment if that player has it function RemovePlayerEquipment(player) if equippedTank[player] and equippedTank[player]:IsValid() then equippedTank[player]:Destroy() equippedTank[player] = nil end end -- nil OnPlayerJoined(Player) -- Gives original equipment function OnPlayerJoined(player) player.spawnedEvent:Connect(OnPlayerRespawned) end -- nil OnPlayerLeft(Player) -- Removes equipment function OnPlayerLeft(player) RemovePlayerEquipment(player) end Game.playerJoinedEvent:Connect(OnPlayerJoined) Game.playerLeftEvent:Connect(OnPlayerLeft) Events.Connect("RESET_TANKS", ResetAllVehicles) Events.ConnectForPlayer("CHANGE_EQUIPPED_TANK", ChangeEquippedTank) Events.Connect("SET_EQUIPPED_TANK", ChangeEquippedTank)
print('lua example') print("lua example") print([[lua example #%$#%!!@#\n\t\r]]) str = [[ this is a\r\n test ]] print(str)
-- TODO(ZyX-I): Create compatibility layer. --{{{1 package.path updater function -- Last inserted paths. Used to clear out items from package.[c]path when they -- are no longer in &runtimepath. local last_nvim_paths = {} local function _update_package_paths() local cur_nvim_paths = {} local rtps = vim.api.nvim_list_runtime_paths() local sep = package.config:sub(1, 1) for _, key in ipairs({'path', 'cpath'}) do local orig_str = package[key] .. ';' local pathtrails_ordered = {} local orig = {} -- Note: ignores trailing item without trailing `;`. Not using something -- simpler in order to preserve empty items (stand for default path). for s in orig_str:gmatch('[^;]*;') do s = s:sub(1, -2) -- Strip trailing semicolon orig[#orig + 1] = s end if key == 'path' then -- /?.lua and /?/init.lua pathtrails_ordered = {sep .. '?.lua', sep .. '?' .. sep .. 'init.lua'} else local pathtrails = {} for _, s in ipairs(orig) do -- Find out path patterns. pathtrail should contain something like -- /?.so, \?.dll. This allows not to bother determining what correct -- suffixes are. local pathtrail = s:match('[/\\][^/\\]*%?.*$') if pathtrail and not pathtrails[pathtrail] then pathtrails[pathtrail] = true pathtrails_ordered[#pathtrails_ordered + 1] = pathtrail end end end local new = {} for _, rtp in ipairs(rtps) do if not rtp:match(';') then for _, pathtrail in pairs(pathtrails_ordered) do local new_path = rtp .. sep .. 'lua' .. pathtrail -- Always keep paths from &runtimepath at the start: -- append them here disregarding orig possibly containing one of them. new[#new + 1] = new_path cur_nvim_paths[new_path] = true end end end for _, orig_path in ipairs(orig) do -- Handle removing obsolete paths originating from &runtimepath: such -- paths either belong to cur_nvim_paths and were already added above or -- to last_nvim_paths and should not be added at all if corresponding -- entry was removed from &runtimepath list. if not (cur_nvim_paths[orig_path] or last_nvim_paths[orig_path]) then new[#new + 1] = orig_path end end package[key] = table.concat(new, ';') end last_nvim_paths = cur_nvim_paths end --{{{1 Module definition return { _update_package_paths = _update_package_paths, }
local configs = require 'lspconfig/configs' local util = require 'lspconfig/util' local server_name = "fsautocomplete" configs[server_name] = { default_config = { cmd = {'dotnet', 'fsautocomplete', '--background-service-enabled'}; root_dir = util.root_pattern('*.sln', '*.fsproj', '.git'); filetypes = {'fsharp'}; init_options = { AutomaticWorkspaceInit = true; }; }; docs = { description = [[ https://github.com/fsharp/FsAutoComplete Language Server for F# provided by FsAutoComplete (FSAC). FsAutoComplete requires the [dotnet-sdk](https://dotnet.microsoft.com/download) to be installed. The prefered way to install FsAutoComplete is with `dotnet tool install --global fsautocomplete`. Instructions to compile from source are found on the main [repository](https://github.com/fsharp/FsAutoComplete). You may also need to configure the filetype as Vim defaults to Forth for `*.fs` files: `autocmd BufNewFile,BufRead *.fs,*.fsx,*.fsi set filetype=fsharp` This is automatically done by plugins such as [PhilT/vim-fsharp](https://github.com/PhilT/vim-fsharp), [fsharp/vim-fsharp](https://github.com/fsharp/vim-fsharp), and [adelarsq/neofsharp.vim](https://github.com/adelarsq/neofsharp.vim). ]]; }; } -- vim:et ts=2 sw=2
---@diagnostic disable: lowercase-global local function trim(s) return s:gsub("^%s*(.-)%s*$", "%1") end -- custom field for description and in-game constants _src_url = "https://github.com/gyroplast/mod-dont-starve-chat-announcements" name = "Chat Announcements" author = "Gyroplast" version = "1.2.3" forumthread = "" api_version = 10 dont_starve_compatible = false reign_of_giants_compatible = false dst_compatible = true icon_atlas = "modicon.xml" icon = "modicon.tex" all_clients_require_mod = false server_filter_tags = {"discord", "chat announcements"} description = trim [[ Version __VERSION__, Workshop ID 2594707725 Announce (boss) monster and player deaths on a server and/or Discord. Highly configurable. Player deaths are credited to most recent attacker within the last 5 seconds, even if dying by fire, cold, over-aging, etc. No, PvP assists or "most damage dealt" is not implemented. Yet. :) Setup Discord Webhook once with CASetDiscordURL("<URL>") in remote console on each shard (i. e. all running overworlds and caves), use CATest() to test, CAStatus() to view current settings. Check your server logfile in case of problems, and refer to the source link below for detailed instructions, bug reports, and further development. Sources: __SRC_URL__ ]]:gsub("__VERSION__", version):gsub("__SRC_URL__", _src_url) -- refer to AnnounceChannelEnum in lib/const.lua for config value meanings configuration_options = { { name = "", label = "General Defaults", hover = "", options = { {description = "", data = ""} }, default = "" }, { -- only define the name to load the option from disk, but not show in config screen name = "discord_webhook_url", }, { name = "death_player", label = "Announce Player Deaths", hover = "Announce player deaths on the selected channels.", options = { {description = "Disabled", data = 1}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 12 }, { name = "announce_death", label = "Announce Monster Death", hover = "Announce monster deaths, as a default, on the selected channels. Override below as needed.", options = { {description = "Disabled", data = 1}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 12 }, { name = "include_day", label = "Append Day", hover = "Append current in-world day to all announcements.", options = { {description = "Disabled", data = false}, {description = "Enabled", data = true} }, default = true }, { name = "include_death_location", label = "Append Location", hover = "Append location of death (Caves or Overworld) to all announcements.", options = { {description = "Disabled", data = false}, {description = "Enabled", data = true} }, default = true }, { name = "log_level", label = "Log Level", hover = "Write log messages to file with selected or higher severity. Trace may contain sensitive data and/or be very chatty!", options = { { description = "Trace", data = "TRACE" }, { description = "Debug", data = "DEBUG" }, { description = "Info", data = "INFO" }, { description = "Warning", data = "WARNING" }, { description = "Error", data = "ERROR" } }, default = "INFO" }, { name = "", label = "Death Announcements", hover = "", options = { {description = "", data = ""} }, default = "" }, { name = "death_minotaur", label = "Death Ancient Guardian", hover = "Announce death of Ancient Guardian.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_antlion", label = "Death Antlion", hover = "Announce death of Antlion.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_bearger", label = "Death Bearger", hover = "Announce death of Bearger.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_beequeen", label = "Death Bee Queen", hover = "Announce death of Bee Queen.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_alterguardian", label = "Death Celestial Champion", hover = "Announce death of Celestial Champion.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_crabking", label = "Death Crab King", hover = "Announce death of Crab King.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_deerclops", label = "Death Deerclops", hover = "Announce death of Deerclops.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_dragonfly", label = "Death Dragonfly", hover = "Announce death of Dragonfly.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_spat", label = "Death Ewecus", hover = "Announce death of Ewecus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_eyeofterror", label = "Death Eye of Terror", hover = "Announce death of Eye of Terror", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_klaus", label = "Death Klaus", hover = "Announce death of Klaus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_koalefant", label = "Death Koalefant", hover = "Announce death of winter/summer koalefant.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_krampus", label = "Death Krampus", hover = "Announce death of Krampus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_lordfruitfly", label = "Death Lord Fruit Fly", hover = "Announce death of the Lord of the Fruit Flies.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_twinofterror1", label = "Death Retinazor", hover = "Announce death of Retinazor", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_twinofterror2", label = "Death Spazmatism", hover = "Announce death of Spazmatism", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_walrus", label = "Death MacTusk", hover = "Announce death of MacTusk.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_malbatross", label = "Death Malbatross", hover = "Announce death of Malbatross.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_moose", label = "Death Moose Goose", hover = "Announce death of Moose Goose.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_shadowchesspieces", label = "Death Shadow Chess Pieces", hover = "Announce death of Shadow Rook, Bishop, and Knight.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_spiderqueen", label = "Death Spider Queen", hover = "Announce death of Spider Queen.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_stalker", label = "Death Stalker", hover = "Announce death of reanimated skeleton/stalker/ancient fuelweaver.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_toadstool", label = "Death Toadstool", hover = "Announce death of (Misery) Toadstool.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_treeguard", label = "Death Treeguard", hover = "Announce death of Treeguards and poison birchnut trees.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "death_warg", label = "Death Warg", hover = "Announce death of Warg.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 } --[[ @todo: implement monster spawn and despawn announcements { name = "announce_despawn", label = "Announce Despawn", hover = "Announce when monsters despawn and vanish instead of dieing.", options = { {description = "Disabled", data = 1}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 4 }, { name = "announce_spawn", label = "Announce Spawn", hover = "Announce when monsters spawn.", options = { {description = "Disabled", data = 1}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 4 }, { name = "title_spawning", label = "Spawn Announcements", hover = "", options = {{description = "", data = false}}, default = false }, { name = "spawn_minotaur", label = "Spawn Ancient Guardian", hover = "Announce spawning of Ancient Guardian.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_antlion", label = "Spawn Antlion", hover = "Announce spawning of Antlion.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_bearger", label = "Spawn Bearger", hover = "Announce spawning of Bearger.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_beequeen", label = "Spawn Bee Queen", hover = "Announce spawning of Bee Queen.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_alterguardian", label = "Spawn Celestial Champion", hover = "Announce spawning of Celestial Champion.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_crabking", label = "Spawn Crab King", hover = "Announce spawning of Crab King.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_deerclops", label = "Spawn Deerclops", hover = "Announce spawning of Deerclops.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_dragonfly", label = "Spawn Dragonfly", hover = "Announce spawning of Dragonfly.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_spat", label = "Spawn Ewecus", hover = "Announce spawning of Ewecus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_klaus", label = "Spawn Klaus", hover = "Announce spawning of Klaus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_koalefant", label = "Spawn Koalefant", hover = "Announce spawning of winter/summer koalefant.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_krampus", label = "Spawn Krampus", hover = "Announce spawning of Krampus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_lordfruitfly", label = "Spawn Lord Fruit Fly", hover = "Announce spawning of the Lord of the Fruit Flies.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_walrus", label = "Spawn MacTusk", hover = "Announce spawning of MacTusk.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_malbatross", label = "Spawn Malbatross", hover = "Announce spawning of Malbatross.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_moose", label = "Spawn Moose Goose", hover = "Announce spawning of Moose Goose.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_shadowchesspieces", label = "Spawn Shadow Chess Pieces", hover = "Announce spawning of Shadow Rook, Bishop, and Knight.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_spiderqueen", label = "Spawn Spider Queen", hover = "Announce spawning of Spider Queen.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_stalker", label = "Spawn Stalker", hover = "Announce spawning of reanimated skeleton/stalker/ancient fuelweaver.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_toadstool", label = "Spawn Toadstool", hover = "Announce spawning of (Misery) Toadstool.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_treeguard", label = "Spawn Treeguard", hover = "Announce spawning of Treeguards and poison birchnut trees.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "spawn_warg", label = "Spawn Warg", hover = "Announce spawning of Warg.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "title_despawn", label = "Despawn Announcements", hover = "", options = {{description = "", data = false}}, default = false }, { name = "despawn_minotaur", label = "Despawn Ancient Guardian", hover = "Announce despawn of Ancient Guardian.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_antlion", label = "Despawn Antlion", hover = "Announce despawn of Antlion.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_bearger", label = "Despawn Bearger", hover = "Announce despawn of Bearger.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_beequeen", label = "Despawn Bee Queen", hover = "Announce despawn of Bee Queen.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_alterguardian", label = "Despawn Celestial Champion", hover = "Announce despawn of Celestial Champion.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_crabking", label = "Despawn Crab King", hover = "Announce despawn of Crab King.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_deerclops", label = "Despawn Deerclops", hover = "Announce despawn of Deerclops.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_dragonfly", label = "Despawn Dragonfly", hover = "Announce despawn of Dragonfly.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_spat", label = "Despawn Ewecus", hover = "Announce despawn of Ewecus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_klaus", label = "Despawn Klaus", hover = "Announce despawn of Klaus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_koalefant", label = "Despawn Koalefant", hover = "Announce despawn of winter/summer koalefant.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_krampus", label = "Despawn Krampus", hover = "Announce despawn of Krampus.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_lordfruitfly", label = "Despawn Lord Fruit Fly", hover = "Announce despawn of the Lord of the Fruit Flies.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_walrus", label = "Despawn MacTusk", hover = "Announce despawn of MacTusk.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_malbatross", label = "Despawn Malbatross", hover = "Announce despawn of Malbatross.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_moose", label = "Despawn Moose Goose", hover = "Announce despawn of Moose Goose.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_shadowchesspieces", label = "Despawn Shadow Chess Pieces", hover = "Announce despawn of Shadow Rook, Bishop, and Knight.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_spiderqueen", label = "Despawn Spider Queen", hover = "Announce despawn of Spider Queen.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_stalker", label = "Despawn Stalker", hover = "Announce despawn of reanimated skeleton/stalker/ancient fuelweaver.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_toadstool", label = "Despawn Toadstool", hover = "Announce despawn of (Misery) Toadstool.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_treeguard", label = "Despawn Treeguard", hover = "Announce despawn of Treeguards and poison birchnut trees.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 }, { name = "despawn_warg", label = "Despawn Warg", hover = "Announce despawn of Warg.", options = { {description = "Disabled", data = 1}, {description = "Default", data = 2}, {description = "Server Only", data = 4}, {description = "Discord Only", data = 8}, {description = "Discord & Server", data = 4 + 8} }, default = 2 } ]] }
-- @docclass math local U8 = 2^8 local U16 = 2^16 local U32 = 2^32 local U64 = 2^64 function math.round(num, idp) local mult = 10^(idp or 0) if num >= 0 then return math.floor(num * mult + 0.5) / mult else return math.ceil(num * mult - 0.5) / mult end end function math.isu8(num) return math.isinteger(num) and num >= 0 and num < U8 end function math.isu16(num) return math.isinteger(num) and num >= U8 and num < U16 end function math.isu32(num) return math.isinteger(num) and num >= U16 and num < U32 end function math.isu64(num) return math.isinteger(num) and num >= U32 and num < U64 end function math.isinteger(num) return ((type(num) == 'number') and (num == math.floor(num))) end
-- plugins.lua local fn = vim.fn -- Install packer if not already installed local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim' if fn.empty(fn.glob(install_path)) > 0 then fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path}) vim.api.nvim_command('packadd packer.nvim') end return require('packer').startup(function(use) -- Packer can manage itself use 'wbthomason/packer.nvim' use { "npxbr/gruvbox.nvim", requires = {"rktjmp/lush.nvim"}, config = function() require('plugins.gruvbox-config') end } use { 'nvim-treesitter/nvim-treesitter', branch = '0.5-compat', run = ':TSUpdate', config = function() require('plugins.treesitter-config') end } use { 'nvim-treesitter/nvim-treesitter-textobjects', branch = '0.5-compat', requires = {'nvim-treesitter/nvim-treesitter'}, config = function() require('plugins.treesitter-textobjects-config') end } -- use 'luochen1990/rainbow' -- Color matching brackets. use { 'p00f/nvim-ts-rainbow', requires = {'nvim-treesitter/nvim-treesitter'}, config = function() require('plugins.rainbow-config') end } use { 'nvim-telescope/telescope.nvim', requires = { {'nvim-lua/popup.nvim'}, {'nvim-lua/plenary.nvim'}, }, config = function() require('plugins.telescope-config') require('plugins.telescope-config.mappings') end, } use 'tpope/vim-surround' -- Add, delete, change surroundings such as brackets. use 'tpope/vim-repeat' -- Allows repeating '.' for many plugins. use 'tpope/vim-commentary' -- Easily un/comment text. use 'tpope/vim-fugitive' -- Useful git commands. use 'tpope/vim-unimpaired' -- Adds common bracket mappings. -- use { -- 'universal-ctags/ctags', -- run = './autogen.sh;./configure --prefix=$HOME/.local;make install' -- } use 'junegunn/vim-easy-align' -- Align text. use 'junegunn/vim-peekaboo' -- Show register contents in sidebar. use { -- Highlights unique letters to help with 'f' 'unblevable/quick-scope', config = function() vim.cmd([[ augroup qs_colors autocmd! autocmd ColorScheme * highlight QuickScopePrimary guifg='#afff5f' gui=underline ctermfg=155 cterm=underline autocmd ColorScheme * highlight QuickScopeSecondary guifg='#5fffff' gui=underline ctermfg=81 cterm=underline augroup END ]]) end } use 'ludovicchabant/vim-gutentags' -- Manage tag files. use 'majutsushi/tagbar' -- Shows list of tags in a sidebar. use 'AndrewRadev/splitjoin.vim' -- Split single lines or join multiple lines. use { 'lewis6991/gitsigns.nvim', requires = { 'nvim-lua/plenary.nvim' }, config = function() require('plugins.gitsigns-config') end } use { -- show indent lines 'lukas-reineke/indent-blankline.nvim', config = function() require('plugins.indent-blankline-config') require('plugins.indent-blankline-config.highlights') end } use { 'dhruvasagar/vim-table-mode', ft = 'markdown', cmd = 'TableModeToggle', config = function() vim.g.table_mode_corner = '|' end } use 'MarcWeber/vim-addon-mw-utils' use 'tomtom/tlib_vim' -- use 'garbas/vim-snipmate' -- use 'honza/vim-snippets' use { -- Switch true to false, yes to no etc. 'AndrewRadev/switch.vim', config = function() vim.g.switch_custom_definitions = { vim.fn["switch#NormalizedCase(['yes','no'])"] } end } use { 'mcchrish/nnn.vim', config = function() require('nnn').setup{ command = 'nnn -HR -T e', layout = { left = '20%' }, } end } use { 'vimwiki/vimwiki', setup = function() require('plugins.vimwiki-config') require('plugins.vimwiki-config.mappings') require('plugins.vimwiki-config.highlights') end } -- use { -- 'autozimu/LanguageClient-neovim', -- branch = 'next', -- run = 'bash install.sh' -- } use { 'norcalli/nvim-colorizer.lua', config = function() require('plugins.colorizer-config') end } -- Text Object Plugins use 'wellle/targets.vim' -- Expands on vim text objects and adds a few new ones. use 'michaeljsmith/vim-indent-object' -- Adds indent text object. use 'chaoren/vim-wordmotion' -- Vim recognizes camel case and more as words. use { -- Text object to target text after char. 'junegunn/vim-after-object', config = function() vim.cmd([[autocmd VimEnter * call after_object#enable('=', ':', ';', '-', '+', '#', '_', '$')]]) end } -- use 'kana/vim-textobj-user' use 'coderifous/textobj-word-column.vim' -- Add column text object. -- Filetype Specific plugins use { 'fatih/vim-go', ft = {'go'}, run = ':GoUpdateBinaries' } use { 'tmux-plugins/vim-tmux', ft = {'tmux'} } use { 'baskerville/vim-sxhkdrc', ft = {'sxhkdrc'} } use { 'fourjay/vim-password-store', ft = {'pass'} } use { 'tmhedberg/SimpylFold', ft = {'python'} } use { 'tridactyl/vim-tridactyl', ft = {'trydactyl'} } use { 'neomutt/neomutt.vim', ft = {'muttrc'} } use { 'pangloss/vim-javascript', ft = {'javascript'} } use { 'leafgarland/typescript-vim', ft = {'typescript'} } use { 'jamessan/vim-gnupg', config = function() vim.g.GPGFilePattern = [[*.\(gpg\|asc\|pgp\)\(.*\)\=]] vim.g.GPGPreferArmor=1 vim.g.GPGDefaultRecipients={"pass@pass"} end } end)
local events = {}; local insert = table.insert; local remove = table.remove; local this = {}; function this.make(name,func) local funcs = events[name]; if not funcs then funcs = {}; events[name] = funcs; end insert(funcs,func); end; function this.mount(discordiaEvents) for name,funcs in pairs(events) do discordiaEvents[name] = function (data,client) for _,func in pairs(funcs) do local result = {func(data,client)}; local passed = remove(result,1); if passed then return result; end end end; end end; return this;
allIpls = { -- METH LAB { names = {"bkr_biker_interior_placement_interior_2_biker_dlc_int_ware01_milo"}, interiorsProps = { --"meth_lab_basic", --"meth_lab_empty", "meth_lab_production", --"meth_lab_security_high", "meth_lab_setup", "meth_lab_upgrade", }, coords={{1009.5, -3196.6, -38.99682}} }, -- WEED LAB { interiorsProps = { "weed_drying", "weed_production", --"weed_set_up", --"weed_standard_equip", "weed_upgrade_equip", --"weed_growtha_stage1", --"weed_growtha_stage2", "weed_growtha_stage3", --"weed_growthb_stage1", --"weed_growthb_stage2", --"weed_growthb_stage3", "weed_growthc_stage1", --"weed_growthc_stage2", --"weed_growthc_stage3", "weed_growthd_stage1", --"weed_growthd_stage2", --"weed_growthd_stage3", --"weed_growthe_stage1", "weed_growthe_stage2", --"weed_growthe_stage3", --"weed_growthf_stage1", "weed_growthf_stage2", --"weed_growthf_stage3", "weed_growthg_stage1", --"weed_growthg_stage2", --"weed_growthg_stage3", --"weed_growthh_stage1", --"weed_growthh_stage2", "weed_growthh_stage3", --"weed_growthi_stage1", "weed_growthi_stage2", --"weed_growthi_stage3", "weed_hosea", "weed_hoseb", "weed_hosec", "weed_hosed", "weed_hosee", "weed_hosef", "weed_hoseg", "weed_hoseh", "weed_hosei", --"light_growtha_stage23_standard", --"light_growthb_stage23_standard", --"light_growthc_stage23_standard", --"light_growthd_stage23_standard", --"light_growthe_stage23_standard", --"light_growthf_stage23_standard", --"light_growthg_stage23_standard", --"light_growthh_stage23_standard", --"light_growthi_stage23_standard", "light_growtha_stage23_upgrade", "light_growthb_stage23_upgrade", "light_growthc_stage23_upgrade", "light_growthc_stage23_upgrade", "light_growthd_stage23_upgrade", "light_growthe_stage23_upgrade", "light_growthf_stage23_upgrade", "light_growthg_stage23_upgrade", "light_growthh_stage23_upgrade", "light_growthi_stage23_upgrade", --"weed_low_security", "weed_security_upgrade", "weed_chairs" }, coords={{1051.491, -3196.536, -39.14842}} }, -- Cocaine LAB { interiorsProps = { --"security_low", "security_high", --"equipment_basic", "equipment_upgrade", "set_up", --"production_basic", "production_upgrade", --"table_equipment", "table_equipment_upgrade", --"coke_press_basic", "coke_press_upgrade", "coke_cut_01", "coke_cut_02", "coke_cut_03", "coke_cut_04", "coke_cut_05" }, coords={{1093.6, -3196.6, -38.99841}} }, -- BUNKERS { interiorsProps = { --"Bunker_Style_A", --"Bunker_Style_B", "Bunker_Style_C", --"standard_bunker_set", "upgrade_bunker_set", --"standard_security_set", "security_upgrade", --"Office_blocker_set", "Office_Upgrade_set", --"gun_range_blocker_set", "gun_wall_blocker", "gun_range_lights", "gun_locker_upgrade", "Gun_schematic_set" }, coords={{899.5518,-3246.038, -98.04907}} }, -- FIB Lobby { interiorsProps = { "V_FIB03_door_light", "V_FIB02_set_AH3b", "V_FIB03_set_AH3b", "V_FIB04_set_AH3b" }, coords={{110.4, -744.2, 45.7496}} }, -- Counterfeit Cash Factory { interiorsProps = { --"counterfeit_cashpile10a", --"counterfeit_cashpile10b", --"counterfeit_cashpile10c", "counterfeit_cashpile10d", --"counterfeit_cashpile20a", --"counterfeit_cashpile20b", --"counterfeit_cashpile20c", "counterfeit_cashpile20d", --"counterfeit_cashpile100a", --"counterfeit_cashpile100b", --"counterfeit_cashpile100c", "counterfeit_cashpile100d", --"counterfeit_low_security", "counterfeit_security", --"counterfeit_setup", --"counterfeit_standard_equip", --"counterfeit_standard_equip_no_prod", "counterfeit_upgrade_equip", --"counterfeit_upgrade_equip_no_prod", "money_cutter", "special_chairs", --"dryera_off", "dryera_on", "dryera_open", --"dryerb_off", "dryerb_on", "dryerb_open", --"dryerc_off", "dryerc_on", "dryerc_open", --"dryerd_off", "dryerd_on", "dryerd_open" }, coords={{1121.897, -3195.338, -40.4025}} }, -- CLUBHOUSE 1 { interiorsProps = { "cash_stash1", "cash_stash2", "cash_stash3", "coke_stash1", "coke_stash2", "coke_stash3", "counterfeit_stash1", "counterfeit_stash2", "counterfeit_stash3", "weed_stash1", "weed_stash2", "weed_stash3", "id_stash1", "id_stash2", "id_stash3", "meth_stash1", "meth_stash2", "meth_stash3", --"decorative_01", "decorative_02", --"furnishings_01", "furnishings_02", --"walls_01", "walls_02", --"mural_01", --"mural_02", --"mural_03", --"mural_04", --"mural_05", --"mural_06", --"mural_07", --"mural_08", "mural_09", "gun_locker", "mod_booth", --"no_gun_locker", --"no_mod_booth" }, coords={{1107.04, -3157.399, -37.51859}} }, -- CLUBHOUSE 2 { interiorsProps = { "cash_large", --"cash_medium", --"cash_small", "coke_large", --"coke_medium", --"coke_small", "counterfeit_large", --"counterfeit_medium", --"counterfeit_small", "id_large", --"id_medium", --"id_small", "meth_large", --"meth_medium", --"meth_small", "weed_large", --"weed_medium", --"weed_small", --"decorative_01", "decorative_02", --"furnishings_01", "furnishings_02", --"walls_01", "walls_02", "lower_walls_default", "gun_locker", "mod_booth", --"no_gun_locker", --"no_mod_booth" }, coords={{998.4809, -3164.711, -38.90733}} }, -- IMPORT / EXPORT GARAGES { interiorsProps = { "garage_decor_01", "garage_decor_02", "garage_decor_03", "garage_decor_04", "lighting_option01", "lighting_option02", "lighting_option03", "lighting_option04", "lighting_option05", "lighting_option06", "lighting_option07", "lighting_option08", "lighting_option09", --"numbering_style01_n1", --"numbering_style01_n2", "numbering_style01_n3", --"numbering_style02_n1", --"numbering_style02_n2", "numbering_style02_n3", --"numbering_style03_n1", --"numbering_style03_n2", "numbering_style03_n3", --"numbering_style04_n1", --"numbering_style04_n2", "numbering_style04_n3", --"numbering_style05_n1", --"numbering_style05_n2", "numbering_style05_n3", --"numbering_style06_n1", --"numbering_style06_n2", "numbering_style06_n3", --"numbering_style07_n1", --"numbering_style07_n2", "numbering_style07_n3", --"numbering_style08_n1", --"numbering_style08_n2", "numbering_style08_n3", --"numbering_style09_n1", --"numbering_style09_n2", "numbering_style09_n3", "floor_vinyl_01", "floor_vinyl_02", "floor_vinyl_03", "floor_vinyl_04", "floor_vinyl_05", "floor_vinyl_06", "floor_vinyl_07", "floor_vinyl_08", "floor_vinyl_09", "floor_vinyl_10", "floor_vinyl_11", "floor_vinyl_12", "floor_vinyl_13", "floor_vinyl_14", "floor_vinyl_15", "floor_vinyl_16", "floor_vinyl_17", "floor_vinyl_18", "floor_vinyl_19", --"basic_style_set", --"branded_style_set", "urban_style_set", "car_floor_hatch", "door_blocker" }, coords={{994.5925, -3002.594, -39.64699}} }, -- CEO OFFICES { interiorsProps = { --"cash_set_01", --"cash_set_02", --"cash_set_03", --"cash_set_04", --"cash_set_05", --"cash_set_06", --"cash_set_07", --"cash_set_08", --"cash_set_09", --"cash_set_10", --"cash_set_11", --"cash_set_12", --"cash_set_13", --"cash_set_14", --"cash_set_15", --"cash_set_16", --"cash_set_17", --"cash_set_18", --"cash_set_19", --"cash_set_20", --"cash_set_21", --"cash_set_22", --"cash_set_23", --"cash_set_24", --"office_booze", "office_chairs", --"swag_art", --"swag_art2", "swag_art3", --"swag_booze_cigs", --"swag_booze_cigs2", --"swag_booze_cigs3", --"swag_counterfeit", --"swag_counterfeit2", "swag_counterfeit3", --"swag_drugbags", --"swag_drugbags2", --"swag_drugbags3", --"swag_drugstatue", --"swag_drugstatue2", --"swag_drugstatue3", --"swag_electronic", --"swag_electronic2", --"swag_electronic3", --"swag_furcoats", --"swag_furcoats2", --"swag_furcoats3", --"swag_gems", --"swag_gems2", --"swag_gems3", --"swag_guns", --"swag_guns2", --"swag_guns3", --"swag_ivory", --"swag_ivory2", --"swag_ivory3", --"swag_jewelwatch", "swag_jewelwatch2", --"swag_jewelwatch3", --"swag_med", --"swag_med2", --"swag_med3", --"swag_pills", --"swag_pills2", --"swag_pills3", --"swag_silver", --"swag_silver2", --"swag_silver3" }, coords={{-141.1987, -620.913, 168.8205}, {-141.5429, -620.9524, 168.8204}, {-141.2896, -620.9618, 168.8204}, {-141.4966, -620.8292, 168.8204}, {-141.3997, -620.9006, 168.8204}, {-141.5361, -620.9186, 168.8204}, {-141.392, -621.0451, 168.8204}, {-141.1945, -620.8729, 168.8204}, {-141.4924, -621.0035, 168.8205}, {-75.8466, -826.9893, 243.3859}, {-75.49945, -827.05, 243.386}, {-75.49827, -827.1889, 243.386}, {-75.44054, -827.1487, 243.3859}, {-75.63942, -827.1022, 243.3859}, {-75.47446, -827.2621, 243.386}, {-75.56978, -827.1152, 243.3859}, {-75.51953, -827.0786, 243.3859}, {-75.41915, -827.1118, 243.3858}, {-1579.756, -565.0661, 108.523}, {-1579.678, -565.0034, 108.5229}, {-1579.583, -565.0399, 108.5229}, {-1579.702, -565.0366, 108.5229}, {-1579.643, -564.9685, 108.5229}, {-1579.681, -565.0003, 108.523}, {-1579.677, -565.0689, 108.5229}, {-1579.708, -564.9634, 108.5229}, {-1579.693, -564.8981, 108.5229}, {-1392.667, -480.4736, 72.04217}, {-1392.542, -480.4011, 72.04211}, {-1392.626, -480.4856, 72.04212}, {-1392.617, -480.6363, 72.04208}, {-1392.532, -480.7649, 72.04207}, {-1392.611, -480.5562, 72.04214}, {-1392.563, -480.549, 72.0421}, {-1392.528, -480.475, 72.04206}, {-1392.416, -480.7485, 72.04207}} }, -- CEO GARAGES { interiorsProps = { --"garage_decor_01", --"garage_decor_02", --"garage_decor_03", "garage_decor_04", --"lighting_option01", --"lighting_option02", --"lighting_option03", --"lighting_option04", --"lighting_option05", --"lighting_option06", --"lighting_option07", --"lighting_option08", "lighting_option09", "numbering_style01_n1", --"numbering_style01_n2", --"numbering_style01_n3", "numbering_style02_n1", --"numbering_style02_n2", --"numbering_style02_n3", "numbering_style03_n1", --"numbering_style03_n2", --"numbering_style03_n3", "numbering_style04_n1", --"numbering_style04_n2", --"numbering_style04_n3", "numbering_style05_n1", --"numbering_style05_n2", --"numbering_style05_n3", "numbering_style06_n1", --"numbering_style06_n2", --"numbering_style06_n3", "numbering_style07_n1", --"numbering_style07_n2", --"numbering_style07_n3", "numbering_style08_n1", --"numbering_style08_n2", --"numbering_style08_n3", "numbering_style09_n1", --"numbering_style09_n2", --"numbering_style09_n3", "basic_style_set" }, coords={{795.75439453125, -2997.3317871094, -22.960731506348}} }, -- CEO VEHICLES SHOPS { interiorsProps = { --"floor_vinyl_01", --"floor_vinyl_02", "floor_vinyl_03", --"floor_vinyl_04", --"floor_vinyl_05", --"floor_vinyl_06", --"floor_vinyl_07", --"floor_vinyl_08", --"floor_vinyl_09", --"floor_vinyl_10", --"floor_vinyl_11", --"floor_vinyl_12", --"floor_vinyl_13", --"floor_vinyl_14", --"floor_vinyl_15", --"floor_vinyl_16", --"floor_vinyl_17", --"floor_vinyl_18", --"floor_vinyl_19" }, coords={{730.63916015625, -2993.2373046875, -38.999904632568}} }, -- BIKERS Document Forgery Office { interiorsProps = { "chair01", "chair02", "chair03", "chair04", "chair05", "chair06", "chair07", "clutter", --"equipment_basic", "equipment_upgrade", --"interior_basic", "interior_upgrade", "production", "security_high", --"security_low", "set_up" }, coords={{1163.842,-3195.7,-39.008}} }, -- Doomsday Facility { interiorsProps = { "set_int_02_decal_01", "set_int_02_lounge1", "set_int_02_cannon", "set_int_02_clutter1", "set_int_02_crewemblem", "set_int_02_shell", "set_int_02_security", "set_int_02_sleep", "set_int_02_trophy1", "set_int_02_paramedic_complete", "set_Int_02_outfit_paramedic", "set_Int_02_outfit_serverfarm" }, interiorsPropColors = { { "set_int_02_decal_01", 1 }, { "set_int_02_lounge1", 1 }, { "set_int_02_cannon", 1 }, { "set_int_02_clutter1", 1 }, { "set_int_02_shell", 1 }, { "set_int_02_security", 1 }, { "set_int_02_sleep", 1 }, { "set_int_02_trophy1", 1 }, { "set_int_02_paramedic_complete", 1 }, { "set_Int_02_outfit_paramedic", 1 }, { "set_Int_02_outfit_serverfarm", 1 } }, coords={{483.2, 4810.5, -58.9}} }, -- Smugglers Run Hangar { interiorsProps = { "set_lighting_hangar_a", "set_tint_shell", "set_bedroom_tint", "set_crane_tint", "set_modarea", "set_lighting_tint_props", "set_floor_1", "set_floor_decal_1", "set_bedroom_modern", "set_office_modern", "set_bedroom_blinds_open", "set_lighting_wall_tint01" }, interiorsPropColors = { { "set_tint_shell", 1 }, { "set_bedroom_tint", 1 }, { "set_crane_tint", 1 }, { "set_modarea", 1 }, { "set_lighting_tint_props", 1 }, { "set_floor_decal_1", 1 } }, coords={{-1266.0, -3014.0, -47.0}} } }
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] return { Stream = require('./stream_core').Stream, Writable = require('./stream_writable').Writable, Transform = require('./stream_transform').Transform, Readable = require('./stream_readable').Readable, PassThrough = require('./stream_passthrough').PassThrough, Observable = require('./stream_observable').Observable, Duplex = require('./stream_duplex').Duplex, }
return require("packer").startup(function() -- Packer can manage itself use("wbthomason/packer.nvim") -- Speed up the startup time use("lewis6991/impatient.nvim") -- Filetype plugin, 175x faster than original use({ "nathom/filetype.nvim" }) use("dracula/vim") use("preservim/vim-colors-pencil") use({ "nvim-lualine/lualine.nvim", requires = { "kyazdani42/nvim-web-devicons", opt = true }, }) use({ "nvim-treesitter/nvim-treesitter", run = ":TSUpdate" }) use("neovim/nvim-lspconfig") -- Collection of configurations for the built-in LSP client use("nvim-lua/lsp-status.nvim") -- LSP functions for the status line (e.g. lualine) use("arkav/lualine-lsp-progress") -- And yet another plugin for the lualine use("mhartington/formatter.nvim") -- Snippets use("L3MON4D3/LuaSnip") use("rafamadriz/friendly-snippets") -- Completion use("hrsh7th/cmp-nvim-lsp") use("hrsh7th/cmp-buffer") use("hrsh7th/cmp-path") use("hrsh7th/cmp-cmdline") use({ "hrsh7th/nvim-cmp", config = function() require("cmp").setup({ snippet = { expand = function(args) require("luasnip").lsp_expand(args.body) end, }, sources = { { name = "luasnip" }, -- more sources }, }) end, }) use("saadparwaiz1/cmp_luasnip") -- Dim unused variables use({ "narutoxy/dim.lua", requires = { "nvim-treesitter/nvim-treesitter", "neovim/nvim-lspconfig" }, config = function() require("dim").setup({}) end, }) -- Detect indentation automatically use({ "nmac427/guess-indent.nvim", config = function() require("guess-indent").setup({}) end, }) -- Annotations (comments for functions) use({ "danymat/neogen", config = function() require("neogen").setup({}) end, requires = "nvim-treesitter/nvim-treesitter", -- Uncomment next line if you want to follow only stable versions -- tag = "*" }) -- Comments use({ "numToStr/Comment.nvim", config = function() require("Comment").setup() end, }) -- 2-letter movement use("ggandor/lightspeed.nvim") -- Stabilyze buffer position when opening a new window use({ "luukvbaal/stabilize.nvim", config = function() require("stabilize").setup({ force = true, -- stabilize window even when current cursor position will be hidden behind new window forcemark = nil, -- set context mark to register on force event which can be jumped to with '<forcemark> ignore = { -- do not manage windows matching these file/buftypes filetype = { "help", "list", "Trouble" }, buftype = { "terminal", "quickfix", "loclist" }, }, nested = nil, -- comma-separated list of autocmds that wil trigger the plugins window restore function }) end, }) -- Scrollbar use("petertriho/nvim-scrollbar") -- Telescope use("nvim-lua/plenary.nvim") use({ "nvim-telescope/telescope-fzf-native.nvim", run = "make" }) use("kyazdani42/nvim-web-devicons") use({ "nvim-telescope/telescope.nvim", requires = { { "nvim-lua/plenary.nvim" } }, }) -- VIM Cheatsheet with Telescope use({ "sudormrfbin/cheatsheet.nvim", requires = { { "nvim-telescope/telescope.nvim" }, { "nvim-lua/popup.nvim" }, { "nvim-lua/plenary.nvim" }, }, }) -- Writer plugins use("junegunn/goyo.vim") use("preservim/vim-markdown") use({ "ojroques/vim-oscyank", branch = "main" }) end)
LinkLuaModifier("ogre_tank_boss_jump_smash", "abilities/siltbreaker/npc_dota_creature_ogre_tank_boss/ogre_tank_boss_jump_smash.lua", LUA_MODIFIER_MOTION_NONE) LinkLuaModifier("ogre_tank_boss_melee_smash", "abilities/siltbreaker/npc_dota_creature_ogre_tank_boss/ogre_tank_boss_melee_smash.lua", LUA_MODIFIER_MOTION_NONE) function Spawn( entityKeyValues ) if not IsServer() then return end if thisEntity == nil then return end thisEntity.SmashAbility = thisEntity:FindAbilityByName( "ogre_tank_boss_melee_smash" ) thisEntity.JumpAbility = thisEntity:FindAbilityByName( "ogre_tank_boss_jump_smash" ) thisEntity.OgreSummonSeers = { } thisEntity:SetContextThink( "OgreTankBossThink", OgreTankBossThink, 1 ) end function FrendlyHasAgro() for i, hSummonedUnit in ipairs( thisEntity.OgreSummonSeers ) do if ( IsValidEntity(hSummonedUnit) and hSummonedUnit:IsAlive() and hSummonedUnit.bHasAgro) then local fHpPercent = (hSummonedUnit:GetHealth() / hSummonedUnit:GetMaxHealth()) * 100 if fHpPercent < 100 then return true end end end return false end function OgreTankBossThink() if ( not IsValidEntity(thisEntity) or not thisEntity:IsAlive() ) then return -1 end if GameRules:IsGamePaused() == true then return 1 end if not thisEntity.bInitialized then thisEntity.vInitialSpawnPos = thisEntity:GetOrigin() thisEntity.bInitialized = true thisEntity.bHasAgro = false SpawnAllies() end local enemies = FindUnitsInRadius( thisEntity:GetTeamNumber(), thisEntity:GetOrigin(), nil, thisEntity:GetCurrentVisionRange(), DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO, DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES , FIND_CLOSEST, false ) local fHpPercent = (thisEntity:GetHealth() / thisEntity:GetMaxHealth()) * 100 local fDistanceToOrigin = ( thisEntity:GetOrigin() - thisEntity.vInitialSpawnPos ):Length2D() --Agro if (fDistanceToOrigin < 10 and thisEntity.bHasAgro and #enemies == 0) then DebugPrint("Ogre Boss Deagro") thisEntity.bHasAgro = false return 2 elseif (fHpPercent < 100 and #enemies > 0) or FrendlyHasAgro() then if not thisEntity.bHasAgro then DebugPrint("Ogre Boss Agro") thisEntity.bHasAgro = true end end -- Leash if not thisEntity.bHasAgro or #enemies==0 or fDistanceToOrigin > 2000 then if fDistanceToOrigin > 10 then return RetreatHome() end return 1 end local nCloseEnemies = 0 for i = 1, #enemies do local enemy = enemies[i] if enemy ~= nil then local flDist = ( enemy:GetOrigin() - thisEntity:GetOrigin() ):Length2D() if flDist < 300 then nCloseEnemies = nCloseEnemies + 1 table.remove( enemies, i ) end end end if thisEntity.JumpAbility ~= nil and thisEntity.JumpAbility:IsFullyCastable() and nCloseEnemies > 0 then return Jump() end if thisEntity.SmashAbility ~= nil and thisEntity.SmashAbility:IsFullyCastable() then return Smash( enemies[ 1 ] ) end return 0.5 end function SpawnAllies() local posTopLeft = thisEntity:GetAbsOrigin() posTopLeft.y = posTopLeft.y + 400 posTopLeft.x = posTopLeft.x - 400 local posTopRight = thisEntity:GetAbsOrigin() posTopRight.y = posTopRight.y + 400 posTopRight.x = posTopRight.x + 400 local ally1 = CreateUnitByName("npc_dota_creature_ogre_seer", posTopLeft, true, nil, nil, DOTA_TEAM_NEUTRALS) local ally2 = CreateUnitByName("npc_dota_creature_ogre_seer", posTopRight, true, nil, nil, DOTA_TEAM_NEUTRALS) table.insert(thisEntity.OgreSummonSeers, ally1) table.insert(thisEntity.OgreSummonSeers, ally2) ally2:AddItem(CreateItem("item_heart", ally2, ally2)) ally1:AddItem(CreateItem("item_heart", ally1, ally1)) end function Jump() ExecuteOrderFromTable({ UnitIndex = thisEntity:entindex(), OrderType = DOTA_UNIT_ORDER_CAST_NO_TARGET, AbilityIndex = thisEntity.JumpAbility:entindex(), Queue = false, }) return 3 end function Smash( enemy ) if enemy == nil then return 0.5 end if ( not thisEntity:HasModifier( "modifier_provide_vision" ) ) then --print( "If player can't see me, provide brief vision to his team as I start my Smash" ) thisEntity:AddNewModifier( thisEntity, nil, "modifier_provide_vision", { duration = 1.5 } ) end ExecuteOrderFromTable({ UnitIndex = thisEntity:entindex(), OrderType = DOTA_UNIT_ORDER_CAST_POSITION, AbilityIndex = thisEntity.SmashAbility:entindex(), Position = enemy:GetOrigin(), Queue = false, }) return thisEntity.SmashAbility:GetPlaybackRateOverride() end function RetreatHome() ExecuteOrderFromTable({ UnitIndex = thisEntity:entindex(), OrderType = DOTA_UNIT_ORDER_MOVE_TO_POSITION, Position = thisEntity.vInitialSpawnPos, Queue = false, }) return 2 end
local typedefs = require "kong.db.schema.typedefs" return { name = "moleculer-bridge", fields = { { -- Plugin will only be applied to Service/Route consumer = typedefs.no_consumer }, { protocols = typedefs.protocols_http }, { config = { type = "record", fields = {}, }, }, }, entity_checks = {}, }
------------------------------------------------------------------------------- -- Wire library. ------------------------------------------------------------------------------- if not WireLib then return end --- Wire library. Handles wire inputs/outputs, wirelinks, etc. local wire_library = SF.RegisterLibrary("wire") SF.AddHook("initialize", function(instance) local ent = instance.data.entity if ent.Inputs == nil then WireLib.CreateInputs(ent, {}) end if ent.Outputs == nil then WireLib.CreateOutputs(ent, {}) end function ent:TriggerInput (key, value) if self.instance then self.instance:runScriptHook("input", key, SF.Wire.InputConverters[self.Inputs[key].Type](value)) end end function ent:ReadCell (address) if self.instance then local tbl = self.instance:runScriptHookForResult("readcell", address) if tbl[1] then return tonumber(tbl[2]) or 0 end end return 0 end function ent:WriteCell (address, data) if self.instance then local tbl = self.instance:runScriptHookForResult("writecell", address, data) if tbl[1] then return tbl[2]==nil or tbl[2]==true end end return false end end) SF.Wire = {} SF.Wire.Library = wire_library -- Register privileges do local P = SF.Permissions P.registerPrivilege("wire.setOutputs", "Set outputs", "Allows the user to specify the set of outputs") P.registerPrivilege("wire.setInputs", "Set inputs", "Allows the user to specify the set of inputs") P.registerPrivilege("wire.output", "Output", "Allows the user to set the value of an output") P.registerPrivilege("wire.input", "Input", "Allows the user to read the value of an input") P.registerPrivilege("wire.wirelink", "Wirelink", "Allows the user to create a wirelink", { entities = {} }) P.registerPrivilege("wire.wirelink.read", "Wirelink Read", "Allows the user to read from wirelink") P.registerPrivilege("wire.wirelink.write", "Wirelink Write", "Allows the user to write to wirelink") P.registerPrivilege("wire.createWire", "Create Wire", "Allows the user to create a wire between two entities", { entities = {} }) P.registerPrivilege("wire.deleteWire", "Delete Wire", "Allows the user to delete a wire between two entities", { entities = {} }) P.registerPrivilege("wire.getInputs", "Get Inputs", "Allows the user to get Inputs of an entity") P.registerPrivilege("wire.getOutputs", "Get Outputs", "Allows the user to get Outputs of an entity") end --- Wirelink type -- @server local wirelink_methods, wirelink_metatable = SF.RegisterType("Wirelink") local wlwrap, wlunwrap = SF.CreateWrapper(wirelink_metatable, true, true) local vwrap, awrap local vunwrap, aunwrap local ewrap, eunwrap local checktype = SF.CheckType local checkluatype = SF.CheckLuaType local checkpermission = SF.Permissions.check local COLOR_WHITE = Color(255, 255, 255) SF.Wire.WlMetatable = wirelink_metatable SF.Wire.WlMethods = wirelink_methods SF.Wire.WlWrap = wlwrap SF.Wire.WlUnwrap = wlunwrap local typeToE2Type local inputConverters local outputConverters SF.AddHook("postload", function() vwrap, awrap = SF.Vectors.Wrap, SF.Angles.Wrap vunwrap, aunwrap = SF.Vectors.Unwrap, SF.Angles.Unwrap ewrap, eunwrap = SF.WrapObject, SF.Entities.Unwrap --- Returns an entities wirelink -- @name Entity.getWirelink -- @class function -- @return Wirelink of the entity SF.Entities.Methods.getWirelink = wire_library.getWirelink local function identity(data) return data end typeToE2Type = { [TYPE_NUMBER] = {identity, "n"}, [TYPE_STRING] = {identity, "s"}, [TYPE_VECTOR] = {function(x) return {x.x, x.y, x.z} end, "v"}, [TYPE_ANGLE] = {function(x) return {x.p, x.y, x.r} end, "a"}, [TYPE_ENTITY] = {identity, "e"} } inputConverters = { NORMAL = identity, STRING = identity, VECTOR = vwrap, ANGLE = awrap, WIRELINK = wlwrap, ENTITY = ewrap, TABLE = function(data) local completed_tables = {} local function recursiveConvert(tbl) if not tbl.s or not tbl.stypes or not tbl.n or not tbl.ntypes or not tbl.size then return {} end if tbl.size == 0 then return {} end local conv = {} completed_tables[tbl] = conv -- Key-numeric part of table for key, typ in pairs(tbl.ntypes) do local val = tbl.n[key] if typ=="t" then conv[key] = completed_tables[val] or recursiveConvert(val) else conv[key] = SF.Wire.InputConverters[typ] and SF.Wire.InputConverters[typ](val) end end -- Key-string part of table for key, typ in pairs(tbl.stypes) do local val = tbl.s[key] if typ=="t" then conv[key] = completed_tables[val] or recursiveConvert(val) else conv[key] = SF.Wire.InputConverters[typ] and SF.Wire.InputConverters[typ](val) end end return conv end return recursiveConvert(data) end, ARRAY = function(tbl) local ret = {} for i, v in ipairs(tbl) do ret[i] = SF.WrapObject(v) end return ret end } inputConverters.n = inputConverters.NORMAL inputConverters.s = inputConverters.STRING inputConverters.v = inputConverters.VECTOR inputConverters.a = inputConverters.ANGLE inputConverters.xwl = inputConverters.WIRELINK inputConverters.e = inputConverters.ENTITY inputConverters.t = inputConverters.TABLE inputConverters.r = inputConverters.ARRAY outputConverters = { NORMAL = function(data) checkluatype(data, TYPE_NUMBER, 2) return data end, STRING = function(data) checkluatype(data, TYPE_STRING, 2) return data end, VECTOR = function(data) checktype(data, SF.Types["Vector"], 2) return vunwrap(data) end, ANGLE = function(data) checktype(data, SF.Types["Angle"], 2) return aunwrap(data) end, ENTITY = function(data) checktype(data, SF.Types["Entity"], 2) return eunwrap(data) end, TABLE = function(data) checkluatype(data, TYPE_TABLE, 2) local completed_tables = {} local function recursiveConvert(tbl) local ret = { istable = true, size = 0, n = {}, ntypes = {}, s = {}, stypes = {} } completed_tables[tbl] = ret for key, value in pairs(tbl) do local ktyp = TypeID(key) local valueList, typeList if ktyp == TYPE_NUMBER then valueList, typeList = ret.n, ret.ntypes elseif ktyp == TYPE_STRING then valueList, typeList = ret.s, ret.stypes else continue end value = SF.UnwrapObject(value) or value local vtyp = TypeID(value) local convert = typeToE2Type[vtyp] if convert then valueList[key] = convert[1](value) typeList[key] = convert[2] ret.size = ret.size + 1 elseif vtyp == TYPE_TABLE then valueList[key] = completed_tables[value] or recursiveConvert(value) typeList[key] = "t" ret.size = ret.size + 1 end end return ret end return recursiveConvert(data) end, ARRAY = function(data) local ret = {} for i, v in ipairs(data) do local obj = SF.UnwrapObject(v) if obj then local typ = typeToE2Type[TypeID(obj)] ret[i] = typ and typ[1](obj) end end return ret end } SF.Wire.InputConverters = inputConverters SF.Wire.OutputConverters = outputConverters end) --- Adds an input type -- @param name Input type name. Case insensitive. -- @param converter The function used to convert the wire data to SF data (eg, wrapping) function SF.Wire.AddInputType(name, converter) inputConverters[name:upper()] = converter end --- Adds an output type -- @param name Output type name. Case insensitive. -- @param deconverter The function used to check for the appropriate type and convert the SF data to wire data (eg, unwrapping) function SF.Wire.AddOutputType(name, deconverter) outputConverters[name:upper()] = deconverter end -- ------------------------- Basic Wire Functions ------------------------- -- local sfTypeToWireTypeTable = { N = "NORMAL", S = "STRING", V = "VECTOR", A = "ANGLE", XWL = "WIRELINK", E = "ENTITY", T = "TABLE", NUMBER = "NORMAL" } --- Creates/Modifies wire inputs. All wire ports must begin with an uppercase -- letter and contain only alphabetical characters. -- @param names An array of input names. May be modified by the function. -- @param types An array of input types. Can be shortcuts. May be modified by the function. function wire_library.adjustInputs (names, types) checkpermission(SF.instance, nil, "wire.setInputs") checkluatype(names, TYPE_TABLE) checkluatype(types, TYPE_TABLE) local ent = SF.instance.data.entity if not ent then SF.Throw("No entity to create inputs on", 2) end if #names ~= #types then SF.Throw("Table lengths not equal", 2) end for i = 1, #names do local newname = names[i] local newtype = types[i] if type(newname) ~= "string" then SF.Throw("Non-string input name: " .. newname, 2) end if type(newtype) ~= "string" then SF.Throw("Non-string input type: " .. newtype, 2) end newtype = newtype:upper() newtype = sfTypeToWireTypeTable[newtype] or newtype if not newname:match("^[%u][%a%d_]*$") then SF.Throw("Invalid input name: " .. newname, 2) end if not inputConverters[newtype] then SF.Throw("Invalid/unsupported input type: " .. newtype, 2) end names[i] = newname types[i] = newtype end ent._inputs = { names, types } WireLib.AdjustSpecialInputs(ent, names, types) end --- Creates/Modifies wire outputs. All wire ports must begin with an uppercase -- letter and contain only alphabetical characters. -- @param names An array of output names. May be modified by the function. -- @param types An array of output types. Can be shortcuts. May be modified by the function. function wire_library.adjustOutputs (names, types) checkpermission(SF.instance, nil, "wire.setOutputs") checkluatype(names, TYPE_TABLE) checkluatype(types, TYPE_TABLE) local ent = SF.instance.data.entity if not ent then SF.Throw("No entity to create outputs on", 2) end if #names ~= #types then SF.Throw("Table lengths not equal", 2) end for i = 1, #names do local newname = names[i] local newtype = types[i] if type(newname) ~= "string" then SF.Throw("Non-string output name: " .. newname, 2) end if type(newtype) ~= "string" then SF.Throw("Non-string output type: " .. newtype, 2) end newtype = newtype:upper() newtype = sfTypeToWireTypeTable[newtype] or newtype if not newname:match("^[%u][%a%d_]*$") then SF.Throw("Invalid output name: " .. newname, 2) end if not outputConverters[newtype] then SF.Throw("Invalid/unsupported output type: " .. newtype, 2) end names[i] = newname types[i] = newtype end ent._outputs = { names, types } WireLib.AdjustSpecialOutputs(ent, names, types) end --- Returns the wirelink representing this entity. function wire_library.self() local ent = SF.instance.data.entity if not ent then SF.Throw("No entity", 2) end return wlwrap(ent) end --- Returns the server's UUID. -- @return UUID as string function wire_library.serverUUID() return WireLib.GetServerUUID() end local ValidWireMat = { ["cable/rope"] = true, ["cable/cable2"] = true, ["cable/xbeam"] = true, ["cable/redlaser"] = true, ["cable/blue_elec"] = true, ["cable/physbeam"] = true, ["cable/hydra"] = true, ["arrowire/arrowire"] = true, ["arrowire/arrowire2"] = true } --- Wires two entities together -- @param entI Entity with input -- @param entO Entity with output -- @param inputname Input to be wired -- @param outputname Output to be wired -- @param width Width of the wire(optional) -- @param color Color of the wire(optional) -- @param material Material of the wire(optional), Valid materials are cable/rope, cable/cable2, cable/xbeam, cable/redlaser, cable/blue_elec, cable/physbeam, cable/hydra, arrowire/arrowire, arrowire/arrowire2 function wire_library.create (entI, entO, inputname, outputname, width, color, material) checktype(entI, SF.Types["Entity"]) checktype(entO, SF.Types["Entity"]) checkluatype(inputname, TYPE_STRING) checkluatype(outputname, TYPE_STRING) if width == nil then width = 0 else checkluatype (width, TYPE_NUMBER) width = math.Clamp(width, 0, 5) end if color ~= nil then checktype(color, SF.Types['Color']) else color = COLOR_WHITE end material = ValidWireMat[material] and material or "cable/rope" local entI = eunwrap(entI) local entO = eunwrap(entO) if not IsValid(entI) then SF.Throw("Invalid source") end if not IsValid(entO) then SF.Throw("Invalid target") end checkpermission(SF.instance, entI, "wire.createWire") checkpermission(SF.instance, entO, "wire.createWire") if not entI.Inputs then SF.Throw("Source has no valid inputs") end if not entO.Outputs then if outputname == "entity" then WireLib.CreateEntityOutput( nil, entO, {true} ) else SF.Throw("Target has no valid outputs") end end if inputname == "" then SF.Throw("Invalid input name") end if outputname == "" then SF.Throw("Invalid output name") end if not entI.Inputs[inputname] then SF.Throw("Invalid source input: " .. inputname) end if not entO.Outputs[outputname] then SF.Throw("Invalid source output: " .. outputname) end if entI.Inputs[inputname].Src then local CheckInput = entI.Inputs[inputname] if CheckInput.SrcId == outputname and CheckInput.Src == entO then SF.Throw("Source \"" .. inputname .. "\" is already wired to target \"" .. outputname .. "\"") end end WireLib.Link_Start(SF.instance.player:UniqueID(), entI, entI:WorldToLocal(entI:GetPos()), inputname, material, color, width) WireLib.Link_End(SF.instance.player:UniqueID(), entO, entO:WorldToLocal(entO:GetPos()), outputname, SF.instance.player) end --- Unwires an entity's input -- @param entI Entity with input -- @param inputname Input to be un-wired function wire_library.delete (entI, inputname) checktype(entI, SF.Types["Entity"]) checkluatype(inputname, TYPE_STRING) local entI = eunwrap(entI) if not IsValid(entI) then SF.Throw("Invalid source") end checkpermission(SF.instance, entI, "wire.deleteWire") if not entI.Inputs or not entI.Inputs[inputname] then SF.Throw("Entity does not have input: " .. inputname) end if not entI.Inputs[inputname].Src then SF.Throw("Input \"" .. inputname .. "\" is not wired") end WireLib.Link_Clear(entI, inputname) end local function parseEntity(ent, io) if ent then checktype(ent, SF.Types["Entity"]) ent = eunwrap(ent) checkpermission(SF.instance, ent, "wire.get" .. io) else ent = SF.instance.data.entity or nil end if not IsValid(ent) then SF.Throw("Invalid source") end local ret = {} for k, v in pairs(ent[io]) do if k ~= "" then table.insert(ret, k) end end return ret end --- Returns a table of entity's inputs -- @param entI Entity with input(s) -- @return Table of entity's inputs function wire_library.getInputs (entI) return parseEntity(entI, "Inputs") end --- Returns a table of entity's outputs -- @param entO Entity with output(s) -- @return Table of entity's outputs function wire_library.getOutputs (entO) return parseEntity(entO, "Outputs") end --- Returns a wirelink to a wire entity -- @param ent Wire entity -- @return Wirelink of the entity function wire_library.getWirelink (ent) checktype(ent, SF.Types["Entity"]) ent = eunwrap(ent) if not ent:IsValid() then return end checkpermission(SF.instance, ent, "wire.wirelink") if not ent.extended then WireLib.CreateWirelinkOutput(SF.instance.player, ent, { true }) end return wlwrap(ent) end -- ------------------------- Wirelink ------------------------- -- --- Retrieves an output. Returns nil if the output doesn't exist. wirelink_metatable.__index = function(self, k) checkpermission(SF.instance, nil, "wire.wirelink.read") checktype(self, wirelink_metatable) if wirelink_methods[k] then return wirelink_methods[k] else local wl = wlunwrap(self) if not wl or not wl:IsValid() or not wl.extended then return end -- TODO: What is wl.extended? if type(k) == "number" then return wl.ReadCell and wl:ReadCell(k) or nil else local output = wl.Outputs and wl.Outputs[k] if not output or not inputConverters[output.Type] then return end return inputConverters[output.Type](output.Value) end end end --- Writes to an input. wirelink_metatable.__newindex = function(self, k, v) checkpermission(SF.instance, nil, "wire.wirelink.write") checktype(self, wirelink_metatable) local wl = wlunwrap(self) if not wl or not wl:IsValid() or not wl.extended then return end -- TODO: What is wl.extended? if type(k) == "number" then checkluatype(v, TYPE_NUMBER) if not wl.WriteCell then return else wl:WriteCell(k, v) end else local input = wl.Inputs and wl.Inputs[k] if not input or not outputConverters[input.Type] then return end WireLib.TriggerInput(wl, k, outputConverters[input.Type](v)) end end --- Checks if a wirelink is valid. (ie. doesn't point to an invalid entity) function wirelink_methods:isValid() checktype(self, wirelink_metatable) return wlunwrap(self) and true or false end --- Returns the type of input name, or nil if it doesn't exist function wirelink_methods:inputType(name) checktype(self, wirelink_metatable) local wl = wlunwrap(self) if not wl then return end local input = wl.Inputs[name] return input and input.Type end --- Returns the type of output name, or nil if it doesn't exist function wirelink_methods:outputType(name) checktype(self, wirelink_metatable) local wl = wlunwrap(self) if not wl then return end local output = wl.Outputs[name] return output and output.Type end --- Returns the entity that the wirelink represents function wirelink_methods:entity() checktype(self, wirelink_metatable) return ewrap(wlunwrap(self)) end --- Returns a table of all of the wirelink's inputs function wirelink_methods:inputs() checktype(self, wirelink_metatable) local wl = wlunwrap(self) if not wl then return nil end local Inputs = wl.Inputs if not Inputs then return {} end local inputNames = {} for _, port in pairs(Inputs) do inputNames[#inputNames + 1] = port.Name end local function portsSorter(a, b) return Inputs[a].Num < Inputs[b].Num end table.sort(inputNames, portsSorter) return inputNames end --- Returns a table of all of the wirelink's outputs function wirelink_methods:outputs() checktype(self, wirelink_metatable) local wl = wlunwrap(self) if not wl then return nil end local Outputs = wl.Outputs if not Outputs then return {} end local outputNames = {} for _, port in pairs(Outputs) do outputNames[#outputNames + 1] = port.Name end local function portsSorter(a, b) return Outputs[a].Num < Outputs[b].Num end table.sort(outputNames, portsSorter) return outputNames end --- Checks if an input is wired. -- @param name Name of the input to check function wirelink_methods:isWired(name) checktype(self, wirelink_metatable) checkluatype(name, TYPE_STRING) local wl = wlunwrap(self) if not wl then return nil end local input = wl.Inputs[name] if input and input.Src and input.Src:IsValid() then return true else return false end end --- Returns what an input of the wirelink is wired to. -- @param name Name of the input -- @return The entity the wirelink is wired to function wirelink_methods:getWiredTo(name) checktype(self, wirelink_metatable) checkluatype(name, TYPE_STRING) local wl = wlunwrap(self) if not wl then return nil end local input = wl.Inputs[name] if input and input.Src and input.Src:IsValid() then return ewrap(input.Src) end end --- Returns the name of the output an input of the wirelink is wired to. -- @param name Name of the input of the wirelink. -- @return String name of the output that the input is wired to. function wirelink_methods:getWiredToName(name) checktype(self, wirelink_metatable) checkluatype(name, TYPE_STRING) local wl = wlunwrap(self) if not wl then return nil end local input = wl.Inputs[name] if input and input.Src and input.Src:IsValid() then return input.SrcId end end -- ------------------------- Ports Metatable ------------------------- -- local wire_ports_methods, wire_ports_metamethods = SF.RegisterType("Ports") function wire_ports_metamethods:__index (name) checkpermission(SF.instance, nil, "wire.input") checkluatype(name, TYPE_STRING) local input = SF.instance.data.entity.Inputs[name] if input and input.Src and input.Src:IsValid() then return inputConverters[input.Type](input.Value) end end function wire_ports_metamethods:__newindex (name, value) checkpermission(SF.instance, nil, "wire.output") checkluatype(name, TYPE_STRING) local ent = SF.instance.data.entity local output = ent.Outputs[name] if output then Wire_TriggerOutput(ent, name, outputConverters[output.Type](value)) end end --- Ports table. Reads from this table will read from the wire input -- of the same name. Writes will write to the wire output of the same name. -- @class table -- @name wire_library.ports wire_library.ports = setmetatable({}, wire_ports_metamethods) -- ------------------------- Hook Documentation ------------------------- -- --- Called when an input on a wired SF chip is written to -- @name input -- @class hook -- @param input The input name -- @param value The value of the input --- Called when a high speed device reads from a wired SF chip -- @name readcell -- @class hook -- @server -- @param address The address requested -- @return The value read --- Called when a high speed device writes to a wired SF chip -- @name writecell -- @class hook -- @param address The address written to -- @param data The data being written
--[[ key 1 -> rdb:job:name:jobs key 2 -> rdb:job:name:waiting key 3 -> rdb:job:name:stats arg 1 -> job data arg 2 -> should be unique? arg 3 -> customId ]] -- if unique enabled if ARGV[2] == "true" then local exists = redis.call("hsetnx", KEYS[1], ARGV[3], ARGV[1]) if exists == 1 then redis.call("lpush", KEYS[2], ARGV[3]) redis.call("hincrby", KEYS[3], 'created', 1) return ARGV[3] end return 0 else -- if not unique enabled redis.call("hset", KEYS[1], ARGV[3], ARGV[1]) redis.call("lpush", KEYS[2], ARGV[3]) redis.call("hincrby", KEYS[3], 'created', 1) return ARGV[3] end
local L --------------------------- -- Garothi Worldbreaker -- --------------------------- L= DBM:GetModLocalization(1992) L:SetTimerLocalization({ }) L:SetOptionLocalization({ }) L:SetMiscLocalization({ }) --------------------------- -- Hounds of Sargeras -- --------------------------- L= DBM:GetModLocalization(1987) L:SetOptionLocalization({ SequenceTimers = "Squence the cooldown timers on heroic/mythic difficulty off previous ability casts instead of current ability cast to reduce timer clutter at expense of minor timer accuracy (1-2sec early)" }) --------------------------- -- War Council -- --------------------------- L= DBM:GetModLocalization(1997) --------------------------- -- Eonar, the Lifebinder -- --------------------------- L= DBM:GetModLocalization(2025) L:SetTimerLocalization({ timerObfuscator = "Next Obfuscator (%s)", timerDestructor = "Next Destructor (%s)", timerPurifier = "Next Purifier (%s)", timerBats = "Next Bats (%s)" }) L:SetOptionLocalization({ timerObfuscator = DBM_CORE_AUTO_TIMER_OPTIONS["cdcount"]:format("ej16501"), timerDestructor = DBM_CORE_AUTO_TIMER_OPTIONS["cdcount"]:format("ej16502"), timerPurifier = DBM_CORE_AUTO_TIMER_OPTIONS["cdcount"]:format("ej16500"), timerBats = DBM_CORE_AUTO_TIMER_OPTIONS["cdcount"]:format("ej17039") }) L:SetMiscLocalization({ Obfuscators = "Obfuscator", Destructors = "Destructor", Purifiers = "Purifier", Bats = "Bats", EonarHealth = "Eonar Health", EonarPower = "Eonar Power", NextLoc = "Next:" }) --------------------------- -- Portal Keeper Hasabel -- --------------------------- L= DBM:GetModLocalization(1985) L:SetOptionLocalization({ ShowAllPlatforms = "Show all announces regardless of player platform location" }) --------------------------- -- Imonar the Soulhunter -- --------------------------- L= DBM:GetModLocalization(2009) L:SetMiscLocalization({ DispelMe = "Dispel Me!" }) --------------------------- -- Kin'garoth -- --------------------------- L= DBM:GetModLocalization(2004) L:SetOptionLocalization({ InfoFrame = "Show InfoFrame for fight overview", UseAddTime = "Always show timers for what's coming next when boss leaves initialisation phase instead of hiding them. (If disabled, correct timers will resume when boss becomes active again, but may leave little warning if any cooldowns only had 1-2 seconds left)" }) --------------------------- -- Varimathras -- --------------------------- L= DBM:GetModLocalization(1983) --------------------------- -- The Coven of Shivarra -- --------------------------- L= DBM:GetModLocalization(1986) L:SetTimerLocalization({ timerBossIncoming = DBM_INCOMING }) L:SetOptionLocalization({ timerBossIncoming = "Show timer for next boss swap", TauntBehavior = "Set taunt behavior for tank swaps", TwoMythicThreeNon = "Swap at 2 stacks on mythic, 3 stacks on other difficulties",--Default TwoAlways = "Always swap at 2 stacks regardless of difficulty", ThreeAlways = "Always swap at 3 stacks regardless of difficulty", SetLighting = "Automatically turn lighting setting to low when coven is engaged and restore on combat end (Not supported in mac client since mac client doesn't support low lighting)", InterruptBehavior = "Set interrupt behavior for raid (Requires raid leader)", Three = "3 person rotation ",--Default Four = "4 person rotation ", Five = "5 person rotation ", IgnoreFirstKick = "With this option, very first interrupt is excluded in rotation (Requires raid leader)" }) --------------------------- -- Aggramar -- --------------------------- L= DBM:GetModLocalization(1984) L:SetOptionLocalization({ ignoreThreeTank = "Filter Rend/Foe Taunt special warnings when using 3 or more tanks (since DBM can't determine exact tanking rotation in this setup). If any tanks die and it drops to 2, filter auto disables" }) L:SetMiscLocalization({ Foe = "Foe", Rend = "Rend", Tempest = "Tempest", Current = "Current:" }) --------------------------- -- Argus the Unmaker -- --------------------------- L= DBM:GetModLocalization(2031) L:SetTimerLocalization({ timerSargSentenceCD = "Sentence CD (%s)" }) L:SetOptionLocalization({ timerSargSentenceCD = DBM_CORE_AUTO_TIMER_OPTIONS["cdcount"]:format(257966) }) L:SetMiscLocalization({ SeaText = "{rt6} Haste/Vers", SkyText = "{rt5} Crit/Mast", Blight = "Blight", Burst = "Burst", Sentence = "Sentence", Bomb = "Bomb" }) ------------- -- Trash -- ------------- L = DBM:GetModLocalization("AntorusTrash") L:SetGeneralLocalization({ name = "Antorus Trash" })
local _M = {} local function contains(t, target) for i=1, #t do if t[i] == target then return true end end return false end _M.contains = contains return _M
--[[-------------------------------------------------------------------------- LGI testsuite, GI Regress-based testsuite. Copyright (c) 2010, 2011 Pavel Holejsovsky Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php --]]-------------------------------------------------------------------------- local lgi = require 'lgi' local bytes = require 'bytes' local fail = testsuite.fail local check = testsuite.check local checkv = testsuite.checkv local gireg = testsuite.group.new('gireg') function gireg.type_boolean() local R = lgi.Regress checkv(R.test_boolean(true), true, 'boolean') checkv(R.test_boolean(false), false, 'boolean') check(select('#', R.test_boolean(true)) == 1) check(select('#', R.test_boolean(false)) == 1) checkv(R.test_boolean(), false, 'boolean') checkv(R.test_boolean(nil), false, 'boolean') checkv(R.test_boolean(0), true, 'boolean') checkv(R.test_boolean(1), true, 'boolean') checkv(R.test_boolean('string'), true, 'boolean') checkv(R.test_boolean({}), true, 'boolean') checkv(R.test_boolean(function() end), true, 'boolean') end function gireg.type_int8() local R = lgi.Regress checkv(R.test_int8(0), 0, 'number') checkv(R.test_int8(1), 1, 'number') checkv(R.test_int8(-1), -1, 'number') checkv(R.test_int8(1.1), 1, 'number') checkv(R.test_int8(-1.1), -1, 'number') checkv(R.test_int8(0x7f), 0x7f, 'number') checkv(R.test_int8(-0x80), -0x80, 'number') check(not pcall(R.test_int8, 0x80)) check(not pcall(R.test_int8, -0x81)) check(not pcall(R.test_int8)) check(not pcall(R.test_int8, nil)) check(not pcall(R.test_int8, 'string')) check(not pcall(R.test_int8, true)) check(not pcall(R.test_int8, {})) check(not pcall(R.test_int8, function() end)) end function gireg.type_uint8() local R = lgi.Regress checkv(R.test_uint8(0), 0, 'number') checkv(R.test_uint8(1), 1, 'number') checkv(R.test_uint8(1.1), 1, 'number') checkv(R.test_uint8(0xff), 0xff, 'number') check(not pcall(R.test_uint8, 0x100)) check(not pcall(R.test_uint8, -1)) check(not pcall(R.test_uint8)) check(not pcall(R.test_uint8, nil)) check(not pcall(R.test_uint8, 'string')) check(not pcall(R.test_uint8, true)) check(not pcall(R.test_uint8, {})) check(not pcall(R.test_uint8, function() end)) end function gireg.type_int16() local R = lgi.Regress checkv(R.test_int16(0), 0, 'number') checkv(R.test_int16(1), 1, 'number') checkv(R.test_int16(-1), -1, 'number') checkv(R.test_int16(1.1), 1, 'number') checkv(R.test_int16(-1.1), -1, 'number') checkv(R.test_int16(0x7fff), 0x7fff, 'number') checkv(R.test_int16(-0x8000), -0x8000, 'number') check(not pcall(R.test_int16, 0x8000)) check(not pcall(R.test_int16, -0x8001)) check(not pcall(R.test_int16)) check(not pcall(R.test_int16, nil)) check(not pcall(R.test_int16, 'string')) check(not pcall(R.test_int16, true)) check(not pcall(R.test_int16, {})) check(not pcall(R.test_int16, function() end)) end function gireg.type_uint16() local R = lgi.Regress checkv(R.test_uint16(0), 0, 'number') checkv(R.test_uint16(1), 1, 'number') checkv(R.test_uint16(1.1), 1, 'number') checkv(R.test_uint16(0xffff), 0xffff, 'number') check(not pcall(R.test_uint16, 0x10000)) check(not pcall(R.test_uint16, -1)) check(not pcall(R.test_uint16)) check(not pcall(R.test_uint16, nil)) check(not pcall(R.test_uint16, 'string')) check(not pcall(R.test_uint16, true)) check(not pcall(R.test_uint16, {})) check(not pcall(R.test_uint16, function() end)) end function gireg.type_int32() local R = lgi.Regress checkv(R.test_int32(0), 0, 'number') checkv(R.test_int32(1), 1, 'number') checkv(R.test_int32(-1), -1, 'number') checkv(R.test_int32(1.1), 1, 'number') checkv(R.test_int32(-1.1), -1, 'number') checkv(R.test_int32(0x7fffffff), 0x7fffffff, 'number') checkv(R.test_int32(-0x80000000), -0x80000000, 'number') check(not pcall(R.test_int32, 0x80000000)) check(not pcall(R.test_int32, -0x80000001)) check(not pcall(R.test_int32)) check(not pcall(R.test_int32, nil)) check(not pcall(R.test_int32, 'string')) check(not pcall(R.test_int32, true)) check(not pcall(R.test_int32, {})) check(not pcall(R.test_int32, function() end)) end function gireg.type_uint32() local R = lgi.Regress checkv(R.test_uint32(0), 0, 'number') checkv(R.test_uint32(1), 1, 'number') checkv(R.test_uint32(1.1), 1, 'number') checkv(R.test_uint32(0xffffffff), 0xffffffff, 'number') check(not pcall(R.test_uint32, 0x100000000)) check(not pcall(R.test_uint32, -1)) check(not pcall(R.test_uint32)) check(not pcall(R.test_uint32, nil)) check(not pcall(R.test_uint32, 'string')) check(not pcall(R.test_uint32, true)) check(not pcall(R.test_uint32, {})) check(not pcall(R.test_uint32, function() end)) end function gireg.type_int64() local R = lgi.Regress checkv(R.test_int64(0), 0, 'number') checkv(R.test_int64(1), 1, 'number') checkv(R.test_int64(-1), -1, 'number') checkv(R.test_int64(1.1), 1, 'number') checkv(R.test_int64(-1.1), -1, 'number') check(not pcall(R.test_int64)) check(not pcall(R.test_int64, nil)) check(not pcall(R.test_int64, 'string')) check(not pcall(R.test_int64, true)) check(not pcall(R.test_int64, {})) check(not pcall(R.test_int64, function() end)) -- Following tests fail because Lua's internal number representation -- is always 'double', and conversion between double and int64 big -- constants is always lossy. Not sure if it can be solved somehow. -- checkv(R.test_int64(0x7fffffffffffffff), 0x7fffffffffffffff, 'number') -- checkv(R.test_int64(-0x8000000000000000), -0x8000000000000000, 'number') -- check(not pcall(R.test_int64, 0x8000000000000000)) -- check(not pcall(R.test_int64, -0x8000000000000001)) end function gireg.type_uint64() local R = lgi.Regress checkv(R.test_uint64(0), 0, 'number') checkv(R.test_uint64(1), 1, 'number') checkv(R.test_uint64(1.1), 1, 'number') check(not pcall(R.test_uint64, -1)) check(not pcall(R.test_uint64)) check(not pcall(R.test_uint64, nil)) check(not pcall(R.test_uint64, 'string')) check(not pcall(R.test_uint64, true)) check(not pcall(R.test_uint64, {})) check(not pcall(R.test_uint64, function() end)) -- See comment above about lossy conversions. -- checkv(R.test_uint64(0xffffffffffffffff), 0xffffffffffffffff, 'number') -- check(not pcall(R.test_uint64, 0x10000000000000000)) end function gireg.type_short() local R = lgi.Regress checkv(R.test_short(0), 0, 'number') checkv(R.test_short(1), 1, 'number') checkv(R.test_short(-1), -1, 'number') checkv(R.test_short(1.1), 1, 'number') checkv(R.test_short(-1.1), -1, 'number') end function gireg.type_ushort() local R = lgi.Regress checkv(R.test_ushort(0), 0, 'number') checkv(R.test_ushort(1), 1, 'number') checkv(R.test_ushort(1.1), 1, 'number') check(not pcall(R.test_ushort, -1)) end function gireg.type_int() local R = lgi.Regress checkv(R.test_int(0), 0, 'number') checkv(R.test_int(1), 1, 'number') checkv(R.test_int(-1), -1, 'number') checkv(R.test_int(1.1), 1, 'number') checkv(R.test_int(-1.1), -1, 'number') end function gireg.type_uint() local R = lgi.Regress checkv(R.test_uint(0), 0, 'number') checkv(R.test_uint(1), 1, 'number') checkv(R.test_uint(1.1), 1, 'number') check(not pcall(R.test_uint, -1)) end function gireg.type_ssize() local R = lgi.Regress checkv(R.test_ssize(0), 0, 'number') checkv(R.test_ssize(1), 1, 'number') checkv(R.test_ssize(-1), -1, 'number') checkv(R.test_ssize(1.1), 1, 'number') checkv(R.test_ssize(-1.1), -1, 'number') end function gireg.type_size() local R = lgi.Regress checkv(R.test_size(0), 0, 'number') checkv(R.test_size(1), 1, 'number') checkv(R.test_size(1.1), 1, 'number') check(not pcall(R.test_size, -1)) end -- Helper, checks that given value has requested type and value, with some -- tolerance because of low precision of gfloat type. local function checkvf(val, exp, tolerance) check(type(val) == 'number', string.format( "got type `%s', expected `number'", type(val)), 2) check(math.abs(val - exp) <= tolerance, string.format("got value `%s', expected `%s'", tostring(val), tostring(exp)), 2) end function gireg.type_float() local R = lgi.Regress local t = 0.0000001 checkvf(R.test_float(0), 0, t) checkvf(R.test_float(1), 1, t) checkvf(R.test_float(1.1), 1.1, t) checkvf(R.test_float(-1), -1, t) checkvf(R.test_float(-1.1), -1.1, t) checkvf(R.test_float(0x8000), 0x8000, t) checkvf(R.test_float(0xffff), 0xffff, t) checkvf(R.test_float(-0x8000), -0x8000, t) checkvf(R.test_float(-0xffff), -0xffff, t) check(not pcall(R.test_float)) check(not pcall(R.test_float, nil)) check(not pcall(R.test_float, 'string')) check(not pcall(R.test_float, true)) check(not pcall(R.test_float, {})) check(not pcall(R.test_float, function() end)) end function gireg.type_double() local R = lgi.Regress checkv(R.test_double(0), 0, 'number') checkv(R.test_double(1), 1, 'number') checkv(R.test_double(1.1), 1.1, 'number') checkv(R.test_double(-1), -1, 'number') checkv(R.test_double(-1.1), -1.1, 'number') checkv(R.test_double(0x80000000), 0x80000000, 'number') checkv(R.test_double(0xffffffff), 0xffffffff, 'number') checkv(R.test_double(-0x80000000), -0x80000000, 'number') checkv(R.test_double(-0xffffffff), -0xffffffff, 'number') check(not pcall(R.test_double)) check(not pcall(R.test_double, nil)) check(not pcall(R.test_double, 'string')) check(not pcall(R.test_double, true)) check(not pcall(R.test_double, {})) check(not pcall(R.test_double, function() end)) end function gireg.type_timet() local R = lgi.Regress checkv(R.test_timet(0), 0, 'number') checkv(R.test_timet(1), 1, 'number') checkv(R.test_timet(10000), 10000, 'number') check(not pcall(R.test_timet)) check(not pcall(R.test_timet, nil)) check(not pcall(R.test_timet, 'string')) check(not pcall(R.test_timet, true)) check(not pcall(R.test_timet, {})) check(not pcall(R.test_timet, function() end)) end function gireg.type_gtype() local R = lgi.Regress checkv(R.test_gtype(), nil, 'nil') checkv(R.test_gtype(nil), nil, 'nil') checkv(R.test_gtype(0), nil, 'nil') checkv(R.test_gtype('void'), 'void', 'string') checkv(R.test_gtype(4), 'void', 'string') checkv(R.test_gtype('GObject'), 'GObject', 'string') checkv(R.test_gtype(80), 'GObject', 'string') checkv(R.test_gtype(R.TestObj), 'RegressTestObj', 'string') check(not pcall(R.test_gtype, true)) check(not pcall(R.test_gtype, function() end)) end function gireg.utf8_const_return() local R = lgi.Regress local utf8_const = 'const \226\153\165 utf8' check(R.test_utf8_const_return() == utf8_const) end function gireg.utf8_nonconst_return() local R = lgi.Regress local utf8_nonconst = 'nonconst \226\153\165 utf8' check(R.test_utf8_nonconst_return() == utf8_nonconst) end function gireg.utf8_const_in() local R = lgi.Regress local utf8_const = 'const \226\153\165 utf8' R.test_utf8_const_in(utf8_const) R.test_utf8_const_in(bytes.new(utf8_const .. '\0')) end function gireg.utf8_out() local R = lgi.Regress local utf8_nonconst = 'nonconst \226\153\165 utf8' check(R.test_utf8_out() == utf8_nonconst) end function gireg.utf8_inout() local R = lgi.Regress local utf8_const = 'const \226\153\165 utf8' local utf8_nonconst = 'nonconst \226\153\165 utf8' check(R.test_utf8_inout(utf8_const) == utf8_nonconst) end function gireg.filename_return() local R = lgi.Regress local fns = R.test_filename_return() check(type(fns) == 'table') check(#fns == 2) check(fns[1] == 'åäö') check(fns[2] == '/etc/fstab') end function gireg.utf8_int_out_utf8() local R = lgi.Regress check(R.test_int_out_utf8('') == 0) check(R.test_int_out_utf8('abc') == 3) local utf8_const = 'const \226\153\165 utf8' check(R.test_int_out_utf8(utf8_const) == 12) end function gireg.multi_double_args() local R = lgi.Regress local o1, o2 = R.test_multi_double_args(1) check(o1 == 2 and o2 == 3) check(#{R.test_multi_double_args(1)} == 2) end function gireg.utf8_out_out() local R = lgi.Regress local o1, o2 = R.test_utf8_out_out() check(o1 == 'first' and o2 == 'second') check(#{R.test_utf8_out_out()} == 2) end function gireg.utf8_out_nonconst_return() local R = lgi.Regress local o1, o2 = R.test_utf8_out_nonconst_return() check(o1 == 'first' and o2 == 'second') check(#{R.test_utf8_out_nonconst_return()} == 2) end function gireg.utf8_null_in() local R = lgi.Regress R.test_utf8_null_in(nil) R.test_utf8_null_in() end function gireg.utf8_null_out() local R = lgi.Regress check(R.test_utf8_null_out() == nil) end function gireg.array_int_in() local R = lgi.Regress check(R.test_array_int_in{1,2,3} == 6) check(R.test_array_int_in{1.1,2,3} == 6) check(R.test_array_int_in{} == 0) check(not pcall(R.test_array_int_in, nil)) check(not pcall(R.test_array_int_in, 'help')) check(not pcall(R.test_array_int_in, {'help'})) end function gireg.array_int_out() local R = lgi.Regress local a = R.test_array_int_out() check(#a == 5) check(a[1] == 0 and a[2] == 1 and a[3] == 2 and a[4] == 3 and a[5] == 4) check(#{R.test_array_int_out()} == 1) end function gireg.array_int_inout() local R = lgi.Regress local a = R.test_array_int_inout({1, 2, 3, 4, 5}) check(#a == 4) check(a[1] == 3 and a[2] == 4 and a[3] == 5 and a[4] == 6) check(#{R.test_array_int_inout({1, 2, 3, 4, 5})} == 1) check(not pcall(R.test_array_int_inout, nil)) check(not pcall(R.test_array_int_inout, 'help')) check(not pcall(R.test_array_int_inout, {'help'})) end function gireg.array_gint8_in() local R = lgi.Regress check(R.test_array_gint8_in{1,2,3} == 6) check(R.test_array_gint8_in{1.1,2,3} == 6) check(R.test_array_gint8_in('0123') == 48 + 49 + 50 + 51) check(R.test_array_gint8_in(bytes.new('0123')) == 48 + 49 + 50 + 51) check(R.test_array_gint8_in{} == 0) check(not pcall(R.test_array_gint8_in, nil)) check(not pcall(R.test_array_gint8_in, {'help'})) end function gireg.array_gint16_in() local R = lgi.Regress check(R.test_array_gint16_in{1,2,3} == 6) check(R.test_array_gint16_in{1.1,2,3} == 6) check(R.test_array_gint16_in{} == 0) check(not pcall(R.test_array_gint16_in, nil)) check(not pcall(R.test_array_gint16_in, 'help')) check(not pcall(R.test_array_gint16_in, {'help'})) end function gireg.array_gint32_in() local R = lgi.Regress check(R.test_array_gint32_in{1,2,3} == 6) check(R.test_array_gint32_in{1.1,2,3} == 6) check(R.test_array_gint32_in{} == 0) check(not pcall(R.test_array_gint32_in, nil)) check(not pcall(R.test_array_gint32_in, 'help')) check(not pcall(R.test_array_gint32_in, {'help'})) end function gireg.array_gint64_in() local R = lgi.Regress check(R.test_array_gint64_in{1,2,3} == 6) check(R.test_array_gint64_in{1.1,2,3} == 6) check(R.test_array_gint64_in{} == 0) check(not pcall(R.test_array_gint64_in, nil)) check(not pcall(R.test_array_gint64_in, 'help')) check(not pcall(R.test_array_gint64_in, {'help'})) end function gireg.array_strv_in() local R = lgi.Regress check(R.test_strv_in{'1', '2', '3'}) check(not pcall(R.test_strv_in)) check(not pcall(R.test_strv_in, '1')) check(not pcall(R.test_strv_in, 1)) check(not R.test_strv_in{'3', '2', '1'}) check(not R.test_strv_in{'1', '2', '3', '4'}) end function gireg.array_gtype_in() local R = lgi.Regress local GObject = lgi.GObject local str = R.test_array_gtype_in { lgi.GObject.Value._gtype, lgi.GObject.type_from_name('gchar') } check(str == '[GValue,gchar,]') check(R.test_array_gtype_in({}) == '[]') check(not pcall(R.test_array_gtype_in)) check(not pcall(R.test_array_gtype_in, '')) check(not pcall(R.test_array_gtype_in, 1)) check(not pcall(R.test_array_gtype_in, function() end)) end function gireg.array_strv_out() local R = lgi.Regress local a = R.test_strv_out() check(type(a) == 'table' and #a == 5) check(table.concat(a, ' ') == 'thanks for all the fish') check(#{R.test_strv_out()} == 1) end function gireg.array_strv_out_container() local R = lgi.Regress local a = R.test_strv_out_container() check(type(a) == 'table' and #a == 3) check(table.concat(a, ' ') == '1 2 3') end function gireg.array_strv_outarg() local R = lgi.Regress local a = R.test_strv_outarg() check(type(a) == 'table' and #a == 3) check(table.concat(a, ' ') == '1 2 3') check(#{R.test_strv_outarg()} == 1) end function gireg.array_fixed_size_int_out() local R = lgi.Regress local a = R.test_array_fixed_size_int_out() check(type(a) == 'table' and #a == 5) check(a[1] == 0 and a[2] == 1 and a[3] == 2 and a[4] == 3 and a[5] == 4) check(#{R.test_array_fixed_size_int_out()} == 1) end function gireg.array_fixed_size_int_return() local R = lgi.Regress local a = R.test_array_fixed_size_int_return() check(type(a) == 'table' and #a == 5) check(a[1] == 0 and a[2] == 1 and a[3] == 2 and a[4] == 3 and a[5] == 4) check(#{R.test_array_fixed_size_int_return()} == 1) end function gireg.array_strv_out_c() local R = lgi.Regress local a = R.test_strv_out_c() check(type(a) == 'table' and #a == 5) check(table.concat(a, ' ') == 'thanks for all the fish') end function gireg.array_int_full_out() local R = lgi.Regress local a = R.test_array_int_full_out() check(type(a) == 'table' and #a == 5) check(a[1] == 0 and a[2] == 1 and a[3] == 2 and a[4] == 3 and a[5] == 4) check(#{R.test_array_int_full_out()} == 1) end function gireg.array_int_full_out() local R = lgi.Regress local a = R.test_array_int_full_out() check(type(a) == 'table' and #a == 5) check(a[1] == 0 and a[2] == 1 and a[3] == 2 and a[4] == 3 and a[5] == 4) check(#{R.test_array_int_full_out()} == 1) end function gireg.array_int_null_in() local R = lgi.Regress R.test_array_int_null_in() R.test_array_int_null_in(nil) end function gireg.array_int_null_out() local R = lgi.Regress local a = R.test_array_int_null_out() check(type(a) == 'table' and not next(a)) end function gireg.glist_nothing_return() local R = lgi.Regress check(select('#', R.test_glist_nothing_return()) == 1) a = R.test_glist_nothing_return() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.glist_nothing_return2() local R = lgi.Regress check(select('#', R.test_glist_nothing_return2()) == 1) a = R.test_glist_nothing_return2() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.glist_container_return() local R = lgi.Regress check(select('#', R.test_glist_container_return()) == 1) a = R.test_glist_container_return() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.glist_everything_return() local R = lgi.Regress check(select('#', R.test_glist_everything_return()) == 1) a = R.test_glist_everything_return() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.glist_nothing_in() local R = lgi.Regress R.test_glist_nothing_in {'1', '2', '3'} end function gireg.glist_nothing_in2() local R = lgi.Regress R.test_glist_nothing_in2 {'1', '2', '3'} end function gireg.glist_null_in() local R = lgi.Regress R.test_glist_null_in {} R.test_glist_null_in(nil) R.test_glist_null_in() end function gireg.glist_null_out() local R = lgi.Regress check(select('#', R.test_glist_null_out()) == 1) local a = R.test_glist_null_out() check(type(a) == 'table' and #a == 0) end function gireg.gslist_nothing_return() local R = lgi.Regress check(select('#', R.test_gslist_nothing_return()) == 1) a = R.test_gslist_nothing_return() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.gslist_nothing_return2() local R = lgi.Regress check(select('#', R.test_gslist_nothing_return2()) == 1) a = R.test_gslist_nothing_return2() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.gslist_container_return() local R = lgi.Regress check(select('#', R.test_gslist_container_return()) == 1) a = R.test_gslist_container_return() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.gslist_everything_return() local R = lgi.Regress check(select('#', R.test_gslist_everything_return()) == 1) a = R.test_gslist_everything_return() check(type(a) == 'table' and #a == 3) check(a[1] == '1' and a[2] == '2' and a[3] == '3') end function gireg.gslist_nothing_in() local R = lgi.Regress R.test_gslist_nothing_in {'1', '2', '3'} end function gireg.gslist_nothing_in2() local R = lgi.Regress R.test_gslist_nothing_in2 {'1', '2', '3'} end function gireg.gslist_null_in() local R = lgi.Regress R.test_gslist_null_in {} R.test_gslist_null_in(nil) R.test_gslist_null_in() end function gireg.gslist_null_out() local R = lgi.Regress check(select('#', R.test_gslist_null_out()) == 1) local a = R.test_gslist_null_out() check(type(a) == 'table' and #a == 0) end function gireg.ghash_null_return() local R = lgi.Regress check(select('#', R.test_ghash_null_return()) == 1) check(R.test_ghash_null_return() == nil) end local function size_htab(h) local size = 0 for _ in pairs(h) do size = size + 1 end return size end function gireg.ghash_nothing_return() local R = lgi.Regress local count = 0 check(select('#', R.test_ghash_nothing_return()) == 1) local h = R.test_ghash_nothing_return() check(type(h) == 'table') check(size_htab(h) == 3) check(h.foo == 'bar' and h.baz == 'bat' and h.qux == 'quux') end function gireg.ghash_container_return() local R = lgi.Regress local count = 0 check(select('#', R.test_ghash_container_return()) == 1) local h = R.test_ghash_container_return() check(type(h) == 'table') check(size_htab(h) == 3) check(h.foo == 'bar' and h.baz == 'bat' and h.qux == 'quux') end function gireg.ghash_everything_return() local R = lgi.Regress local count = 0 check(select('#', R.test_ghash_everything_return()) == 1) local h = R.test_ghash_everything_return() check(type(h) == 'table') check(size_htab(h) == 3) check(h.foo == 'bar' and h.baz == 'bat' and h.qux == 'quux') end function gireg.ghash_null_in() local R = lgi.Regress R.test_ghash_null_in(nil) R.test_ghash_null_in() check(not pcall(R.test_ghash_null_in,1)) check(not pcall(R.test_ghash_null_in,'string')) check(not pcall(R.test_ghash_null_in,function() end)) end function gireg.ghash_null_out() local R = lgi.Regress check(R.test_ghash_null_out() == nil) end function gireg.ghash_nothing_in() local R = lgi.Regress R.test_ghash_nothing_in({ foo = 'bar', baz = 'bat', qux = 'quux' }) check(not pcall(R.test_ghash_nothing_in)) check(not pcall(R.test_ghash_nothing_in, 1)) check(not pcall(R.test_ghash_nothing_in, 'test')) check(not pcall(R.test_ghash_nothing_in, function() end)) end function gireg.ghash_nested_everything_return() local R = lgi.Regress check(select('#', R.test_ghash_nested_everything_return) == 1); local a = R.test_ghash_nested_everything_return() check(type(a) == 'table') check(size_htab(a) == 1) check(type(a.wibble) == 'table') check(size_htab(a.wibble) == 3) check(a.wibble.foo == 'bar' and a.wibble.baz == 'bat' and a.wibble.qux == 'quux') end function gireg.enum() local R = lgi.Regress check(R.TestEnum.VALUE1 == 0) check(R.TestEnum.VALUE2 == 1) check(R.TestEnum.VALUE3 == -1) check(R.TestEnum[0] == 'VALUE1') check(R.TestEnum[1] == 'VALUE2') check(R.TestEnum[-1] == 'VALUE3') check(R.TestEnum[43] == 43) check(R.test_enum_param(0) == 'value1') check(R.test_enum_param(1) == 'value2') check(R.test_enum_param(-1) == 'value3') check(R.TestEnumUnsigned.VALUE1 == 1) check(R.TestEnumUnsigned.VALUE2 == 0x80000000) check(R.TestEnumUnsigned[1] == 'VALUE1') check(R.TestEnumUnsigned[0x80000000] == 'VALUE2') check(R.TestEnumUnsigned[-1] == -1) end function gireg.flags() local R = lgi.Regress check(R.TestFlags.FLAG1 == 1) check(R.TestFlags.FLAG2 == 2) check(R.TestFlags.FLAG3 == 4) check(R.TestFlags[7].FLAG1 == true) check(R.TestFlags[7].FLAG2 == true) check(R.TestFlags[7].FLAG3 == true) check(R.TestFlags[3].FLAG1 == true) check(R.TestFlags[3].FLAG2 == true) check(R.TestFlags[3].FLAG3 == nil) check(R.TestFlags[10].FLAG2 == true) check(R.TestFlags[10][1] == 8) checkv(R.TestFlags { 'FLAG1', 'FLAG2' }, 3, 'number') checkv(R.TestFlags { 1, 2, 'FLAG1', R.TestFlags.FLAG2 }, 3, 'number') checkv(R.TestFlags { 10, FLAG2 = 2 }, 10, 'number') checkv(R.TestFlags { 2, 'FLAG2' }, 2, 'number') end function gireg.flags_out() local R = lgi.Regress local out = R.global_get_flags_out() check(type(out) == 'table') check(out.FLAG1 == true) check(out.FLAG2 == nil) check(out.FLAG3 == true) check(#out == 0) end function gireg.const() local R = lgi.Regress checkv(R.INT_CONSTANT, 4422, 'number') checkv(R.DOUBLE_CONSTANT, 44.22, 'number') checkv(R.STRING_CONSTANT, 'Some String', 'string') checkv(R.Mixed_Case_Constant, 4423, 'number') end function gireg.struct_a() local R = lgi.Regress check(select('#', R.TestStructA()) == 1) local a = R.TestStructA() check(type(a) == 'userdata') a.some_int = 42 check(a.some_int == 42) a.some_int8 = 12 check(a.some_int8 == 12) a.some_double = 3.14 check(a.some_double == 3.14) a.some_enum = R.TestEnum.VALUE2 check(a.some_enum == 'VALUE2') a = R.TestStructA { some_int = 42, some_int8 = 12, some_double = 3.14, some_enum = 'VALUE2' } a.some_int = 43 a.some_int8 = 13 check(a.some_int == 43) check(a.some_int8 == 13) check(a.some_double == 3.14) check(a.some_enum == 'VALUE2') a.some_double = 3.15 check(a.some_int == 43) check(a.some_int8 == 13) check(a.some_double == 3.15) check(a.some_enum == 'VALUE2') a.some_enum = R.TestEnum.VALUE3 check(a.some_int == 43) check(a.some_int8 == 13) check(a.some_double == 3.15) check(a.some_enum == 'VALUE3') check(not pcall(function() return a.foo end)) check(not pcall(function() a.foo = 1 end)) check(select('#', (function() a.some_int = 0 end)()) == 0) check(select('#', (function() return a.some_int end)()) == 1) check(select('#', (function() local b = a.some_int end)()) == 0) end function gireg.struct_a_clone() local R = lgi.Regress local a = R.TestStructA { some_int = 42, some_int8 = 12, some_double = 3.14, some_enum = R.TestEnum.VALUE2 } check(a == a) check(select('#', a:clone()) == 1) local b = a:clone() check(type(b) == 'userdata') check(b ~= a) check(b == b) check(b.some_int == 42) check(b.some_int8 == 12) check(b.some_double == 3.14) check(b.some_enum == 'VALUE2') check(a.some_int == 42) check(a.some_int8 == 12) check(a.some_double == 3.14) check(a.some_enum == 'VALUE2') end function gireg.struct_b() local R = lgi.Regress local b = R.TestStructB() -- Basic fields assignments. b.some_int8 = 13 check(b.some_int8 == 13) b.nested_a.some_int = -1 check(b.some_int8 == 13) check(b.nested_a.some_int == -1) b.nested_a.some_int8 = -2 check(b.some_int8 == 13) check(b.nested_a.some_int == -1) check(b.nested_a.some_int8 == -2) -- Whole nested structure assignment. b.nested_a = { some_int = 42, some_int8 = 12, some_double = 3.14, some_enum = R.TestEnum.VALUE2 } check(b.nested_a.some_int == 42) check(b.nested_a.some_int8 == 12) check(b.nested_a.some_double == 3.14) check(b.nested_a.some_enum == 'VALUE2') -- Nested structure construction. b = R.TestStructB { some_int8 = 21, nested_a = { some_int = 42, some_int8 = 12, some_double = 3.14, some_enum = R.TestEnum.VALUE2 } } check(b.some_int8 == 21) check(b.nested_a.some_int == 42) check(b.nested_a.some_int8 == 12) check(b.nested_a.some_double == 3.14) check(b.nested_a.some_enum == 'VALUE2') end function gireg.struct_b_clone() local R = lgi.Regress local b = R.TestStructB { some_int8 = 21, nested_a = { some_int = 42, some_int8 = 12, some_double = 3.14, some_enum = R.TestEnum.VALUE2 } } check(b == b) check(select('#', b:clone()) == 1) local bc = b:clone() check(type(bc) == 'userdata') check(bc ~= b) check(bc == bc) check(bc.some_int8 == 21) check(bc.nested_a.some_int == 42) check(bc.nested_a.some_int8 == 12) check(bc.nested_a.some_double == 3.14) check(bc.nested_a.some_enum == 'VALUE2') check(bc.nested_a.some_int == 42) check(bc.nested_a.some_int8 == 12) check(bc.nested_a.some_double == 3.14) check(bc.nested_a.some_enum == 'VALUE2') check(b.some_int8 == 21) check(b.nested_a.some_int == 42) check(b.nested_a.some_int8 == 12) check(b.nested_a.some_double == 3.14) check(b.nested_a.some_enum == 'VALUE2') check(b.nested_a.some_int == 42) check(b.nested_a.some_int8 == 12) check(b.nested_a.some_double == 3.14) check(b.nested_a.some_enum == 'VALUE2') end function gireg.boxed_a_equals() local R = lgi.Regress check(R.TestSimpleBoxedA({ some_int = 1, some_int8 = 2, some_double = 3.14 }):equals( R.TestSimpleBoxedA({ some_int = 1, some_int8 = 2, some_double = 3.14 }))) check(not R.TestSimpleBoxedA({ some_int = 2, some_int8 = 2, some_double = 3.14 }):equals( R.TestSimpleBoxedA({ some_int = 1, some_int8 = 2, some_double = 3.14 }))) check(R.TestSimpleBoxedA():equals(R.TestSimpleBoxedA())) check(not pcall(R.TestSimpleBoxedA().equals)) check(not pcall(R.TestSimpleBoxedA().equals, nil)) check(not pcall(R.TestSimpleBoxedA().equals, {})) check(not pcall(R.TestSimpleBoxedA().equals, 1)) check(not pcall(R.TestSimpleBoxedA().equals, 'string')) check(not pcall(R.TestSimpleBoxedA().equals, function() end)) end function gireg.boxed_a_const_return() local R = lgi.Regress check(select('#', R.test_simple_boxed_a_const_return()) == 1) local a = R.test_simple_boxed_a_const_return() check(a.some_int == 5) check(a.some_int8 == 6) check(a.some_double == 7) end function gireg.boxed_new() local R = lgi.Regress check(select('#', R.TestBoxed.new()) == 1) local bn = R.TestBoxed.new() local bac1 = R.TestBoxed.new_alternative_constructor1(1) check(bac1.some_int8 == 1) local bac2 = R.TestBoxed.new_alternative_constructor2(1, 2) check(bac2.some_int8 == 3) local bac3 = R.TestBoxed.new_alternative_constructor3('25') check(bac3.some_int8 == 25) end function gireg.boxed_copy() local R = lgi.Regress local b = R.TestBoxed.new() b.some_int8 = 1 b.nested_a = { some_int = 1, some_int8 = 2, some_double = 3.14 } check(select('#', b:copy()) == 1) local bc = b:copy() check(bc ~= b) check(bc.some_int8 == 1) check(bc.nested_a.some_int == 1) check(bc.nested_a.some_int8 == 2) check(bc.nested_a.some_double == 3.14) end function gireg.boxed_equals() local R = lgi.Regress local b1 = R.TestBoxed.new() b1.some_int8 = 1 b1.nested_a = { some_int = 1, some_int8 = 2, some_double = 3.14 } local b2 = R.TestBoxed.new() b2.some_int8 = 1 b2.nested_a = { some_int = 1, some_int8 = 2, some_double = 3.14 } check(b1:equals(b2)) b1.some_int8 = 2 check(not b1:equals(b2)) b1.some_int8 = 1 b1.nested_a.some_int = 2 check(not b1:equals(b2)) b1.nested_a.some_int = 1 check(b1:equals(b2)) end function gireg.closure_simple() local R = lgi.Regress local GObject = lgi.GObject local closure = GObject.Closure(function(...) check(select('#', ...) == 0) return 42 end) checkv(R.test_closure(closure, 42), 42, 'number') local res = GObject.Value('gint') closure:invoke(res, {}, nil) check(res.gtype == 'gint' and res.value == 42) end function gireg.closure_arg() local GObject = lgi.GObject local R = lgi.Regress local closure = GObject.Closure(function(int, ...) check(select('#', ...) == 0) return int end) checkv(R.test_closure_one_arg(closure, 43), 43, 'number') local res = GObject.Value('gint') closure:invoke(res, { GObject.Value('gint', 43) }, nil) check(res.gtype == 'gint' and res.value == 43) end function gireg.gvalue_assign() local GObject = lgi.GObject local V = GObject.Value local v = V() check(v.gtype == nil) check(v.value == nil) v.gtype = 'gchararray' check(v.gtype == 'gchararray') check(v.value == nil) v.value = 'label' check(v.value == 'label') v.value = nil check(v.value == nil) check(v.gtype == 'gchararray') v.value = 'label' v.gtype = nil check(v.gtype == nil) check(v.value == nil) v.gtype = 'gint' v.value = 1 check(v.gtype == 'gint') check(v.value == 1) v.gtype = 'gdouble' check(v.gtype == 'gdouble') check(v.value == 1) v.value = 3.14 v.gtype = 'gint' check(v.gtype == 'gint') check(v.value == 3) end function gireg.gvalue_arg() local GObject = lgi.GObject local R = lgi.Regress checkv(R.test_int_value_arg(GObject.Value('gint', 42)), 42, 'number') end function gireg.gvalue_return() local R = lgi.Regress local v = R.test_value_return(43) checkv(v.value, 43, 'number') check(v.gtype == 'gint', 'incorrect value type') end function gireg.gvalue_date() local GObject = lgi.GObject local GLib = lgi.GLib local R = lgi.Regress local v v = R.test_date_in_gvalue() check(v.gtype == 'GDate') check(v.value:get_day() == 5) check(v.value:get_month() == 'DECEMBER') check(v.value:get_year() == 1984) local d = GLib.Date() d:set_dmy(25, 1, 1975) v = GObject.Value(GLib.Date, d) check(v.gtype == 'GDate') check(v.value:get_day() == 25) check(v.value:get_month() == 'JANUARY') check(v.value:get_year() == 1975) end function gireg.gvalue_strv() local GObject = lgi.GObject local R = lgi.Regress local v = R.test_strv_in_gvalue() check(v.gtype == 'GStrv') check(#v.value == 3) check(v.value[1] == 'one') check(v.value[2] == 'two') check(v.value[3] == 'three') v = GObject.Value('GStrv', { '1', '2', '3' }) check(#v.value == 3) check(v.value[1] == '1') check(v.value[2] == '2') check(v.value[3] == '3') end function gireg.obj_create() local R = lgi.Regress local o = R.TestObj() check(o) check(type(o) == 'userdata') check(select('#', R.TestObj()) == 1) o = R.TestObj.new_from_file('unused') check(type(o) == 'userdata') check(select('#', R.TestObj.new_from_file('unused')) == 1) end function gireg.obj_methods() local R = lgi.Regress local GLib = lgi.GLib local Gio = lgi.Gio if R.TestObj._method.do_matrix then R.TestObj._method.invoke_matrix = R.TestObj._method.do_matrix R.TestObj._method.do_matrix = nil end local o = R.TestObj() check(o:instance_method() == -1) check(o.static_method(42) == 42) local y, z, q = o:torture_signature_0(1, 'foo', 2) check(y == 1) check(z == 2) check(q == 5) local y, z, q = o:torture_signature_1(1, 'foo', 2) check(y == 1) check(z == 2) check(q == 5) local res, err = o:torture_signature_1(1, 'foo', 3) check(not res) check(GLib.Error:is_type_of(err)) check(err:matches(Gio.IOErrorEnum, 'FAILED')) check(o:invoke_matrix('unused') == 42) end function gireg.obj_null_args() local R = lgi.Regress R.func_obj_null_in(nil) R.func_obj_null_in() check(R.TestObj.null_out() == nil) check(select('#', R.TestObj.null_out()) == 1) end function gireg.obj_virtual_methods() local R = lgi.Regress local o = R.TestObj() check(o:do_matrix('unused') == 42) end function gireg.obj_prop_int() local R = lgi.Regress local o = R.TestObj() check(o.int == 0) o.int = 42 check(o.int == 42) check(not pcall(function() o.int = {} end)) check(not pcall(function() o.int = 'lgi' end)) check(not pcall(function() o.int = nil end)) check(not pcall(function() o.int = function() end end)) end function gireg.obj_prop_float() local R = lgi.Regress local o = R.TestObj() check(o.float == 0) o.float = 42.1 checkvf(o.float, 42.1, 0.00001) check(not pcall(function() o.float = {} end)) check(not pcall(function() o.float = 'lgi' end)) check(not pcall(function() o.float = nil end)) check(not pcall(function() o.float = function() end end)) end function gireg.obj_prop_double() local R = lgi.Regress local o = R.TestObj() check(o.double == 0) o.double = 42.1 checkvf(o.double, 42.1, 0.0000000001) check(not pcall(function() o.double = {} end)) check(not pcall(function() o.double = 'lgi' end)) check(not pcall(function() o.double = nil end)) check(not pcall(function() o.double = function() end end)) end function gireg.obj_prop_string() local R = lgi.Regress local o = R.TestObj() check(o.string == nil) o.string = 'lgi' check(o.string == 'lgi') o.string = nil check(o.string == nil) check(not pcall(function() o.string = {} end)) check(not pcall(function() o.string = function() end end)) end function gireg.obj_prop_bare() local R = lgi.Regress local o = R.TestObj() check(o.bare == nil) local pv = R.TestObj() o.bare = pv check(o.bare == pv) o.bare = nil check(o.bare == nil) o:set_bare(pv) check(o.bare == pv) o.bare = nil check(o.bare == nil) check(not pcall(function() o.bare = {} end)) check(not pcall(function() o.bare = 42 end)) check(not pcall(function() o.bare = 'lgi' end)) check(not pcall(function() o.bare = function() end end)) check(not pcall(function() o.bare = R.TestBoxed() end)) end function gireg.obj_prop_boxed() local R = lgi.Regress local o = R.TestObj() check(o.boxed == nil) local pv = R.TestBoxed() o.boxed = pv check(o.boxed:equals(pv)) o.boxed = nil check(o.boxed == nil) check(not pcall(function() o.boxed = {} end)) check(not pcall(function() o.boxed = 42 end)) check(not pcall(function() o.boxed = 'lgi' end)) check(not pcall(function() o.boxed = function() end end)) check(not pcall(function() o.boxed = R.TestObj() end)) end function gireg.obj_prop_hash() local R = lgi.Regress local o = R.TestObj() check(o.hash_table == nil) o.hash_table = { a = 1, b = 2 } local ov = o.hash_table check(ov.a == 1 and ov.b == 2) check(not pcall(function() o.hash_table = 42 end)) check(not pcall(function() o.hash_table = 'lgi' end)) check(not pcall(function() o.hash_table = function() end end)) check(not pcall(function() o.hash_table = R.TestObj() end)) check(not pcall(function() o.hash_table = R.TestBoxed() end)) end function gireg.obj_prop_list() local R = lgi.Regress local o = R.TestObj() check(o.hash_table == nil) o.list = { 'one', 'two', 'three', } local ov = o.list check(#ov == 3 and ov[1] == 'one' and ov[2] == 'two' and ov[3] == 'three') check(not pcall(function() o.list = 42 end)) check(not pcall(function() o.list = 'lgi' end)) check(not pcall(function() o.list = function() end end)) check(not pcall(function() o.list = R.TestObj() end)) check(not pcall(function() o.list = R.TestBoxed() end)) end function gireg.obj_prop_dynamic() local R = lgi.Regress local o = R.TestObj() -- Remove static property information, force lgi to use dynamic -- GLib property system. local old_prop = R.TestObj.int R.TestObj._property.int = nil R.TestObj._cached = nil check(R.TestObj.int == nil) check(o.int == 0) o.int = 3 check(o.int == 3) check(not pcall(function() o.int = 'string' end)) check(not pcall(function() o.int = {} end)) check(not pcall(function() o.int = true end)) check(not pcall(function() o.int = function() end end)) -- Restore TestObj to work normally. R.TestObj._property.int = old_prop end function gireg.obj_subobj() local R = lgi.Regress local o = R.TestSubObj() local pv = R.TestObj() check(o:instance_method() == 0) o.bare = pv check(o.bare == pv) o:unset_bare() check(o.bare == nil) o = R.TestSubObj.new() o:set_bare(pv) check(o.bare == pv) o:unset_bare() check(o.bare == nil) end function gireg.obj_naming() local R = lgi.Regress local o = R.TestWi8021x() o:set_testbool(true) check(o.testbool == true) o.testbool = false check(o:get_testbool() == false) end function gireg.obj_floating() local R = lgi.Regress local o = R.TestFloating() check(o) o = nil collectgarbage() collectgarbage() end function gireg.obj_fundamental() local R = lgi.Regress local f = R.TestFundamentalSubObject.new('foo-nda-mental') check(f) check(f.data == 'foo-nda-mental') local v = lgi.GObject.Value(R.TestFundamentalSubObject, f) check(v.value == f) f = nil collectgarbage() end function gireg.callback_simple() local R = lgi.Regress check(R.test_callback(function() return 42 end) == 42) check(R.test_callback() == 0) check(R.test_callback(nil) == 0) check(not pcall(R.test_callback, 1)) check(not pcall(R.test_callback, 'foo')) check(not pcall(R.test_callback, {})) check(not pcall(R.test_callback, R)) check(R.test_multi_callback(function() return 22 end) == 44) check(R.test_multi_callback() == 0) end function gireg.callback_data() local R = lgi.Regress local called R.test_simple_callback(function() called = true end) check(called) check(R.test_callback_user_data(function() return 42 end) == 42) called = nil R.TestObj.static_method_callback(function() called = true return 42 end) check(called) local o = R.TestObj() called = nil o.static_method_callback(function() called = true return 42 end) check(called) called = nil o:instance_method_callback(function() called = true return 42 end) check(called) end function gireg.callback_notified() local R = lgi.Regress check(R.test_callback_destroy_notify(function() return 1 end) == 1) check(R.test_callback_destroy_notify(function() return 2 end) == 2) check(R.test_callback_destroy_notify(function() return 3 end) == 3) collectgarbage() collectgarbage() check(R.test_callback_thaw_notifications() == 6) R.TestObj.new_callback(function() return 1 end) collectgarbage() collectgarbage() check(R.test_callback_thaw_notifications() == 1) end function gireg.callback_async() local R = lgi.Regress R.test_callback_async(function() return 1 end) collectgarbage() collectgarbage() check(R.test_callback_thaw_async() == 1) end
local iosPayWebView = require(ViewPath.."hall/shortCutRecharge/iosPayWebView"); local IosPayWebView = class(CommonGameLayer, false); IosPayWebView.Delegate = { onIosPayWebViewClose = "onIosPayWebViewClose"; } IosPayWebView.s_controls = { groundBg = 1; returnBtn = 2; content = 3; bg = 4; }; IosPayWebView.ctor = function(self) super(self,iosPayWebView); self:getControl(IosPayWebView.s_controls.bg):setEventTouch(nil , function() end); self:getControl(IosPayWebView.s_controls.bg):setEventDrag(nil , function() end); end IosPayWebView.getWebFrame = function (self) local contentView = self:findViewById(IosPayWebView.s_controls.groundBg); local x,y = contentView:getAbsolutePos(); local w,h = contentView:getSize(); return x*System.getLayoutScale(), y*System.getLayoutScale(), w*System.getLayoutScale(), h*System.getLayoutScale(); end --关闭界面 IosPayWebView.onReturnBtnClick = function(self) NativeEvent.getInstance():closeIosWebPay(); self:execDelegate(IosPayWebView.Delegate.onIosPayWebViewClose, true); end IosPayWebView.s_controlConfig = { [IosPayWebView.s_controls.groundBg] = {"ground_bg"}; [IosPayWebView.s_controls.returnBtn] = {"topView","returnBtn"}; [IosPayWebView.s_controls.content] = {"content"}; [IosPayWebView.s_controls.bg] = {"bg"}; }; IosPayWebView.s_controlFuncMap = { [IosPayWebView.s_controls.returnBtn] = IosPayWebView.onReturnBtnClick; } IosPayWebView.s_nativeEventFuncMap = { ["closeLuaIosWebPayView"] = IosPayWebView.onReturnBtnClick; }; return IosPayWebView;
function setPlayerData (player, key, data) local id = exports.database:getPlayerId (player); setMemberData (id, key, data); end function getPlayerData (player, key) local id = exports.database:getPlayerId (player); return getMemberData (id, key, data); end function isPlayerInAGroup (player) return getPlayerGroup (player) ~= false; end function getPlayerGroup (player) return getPlayerData (player, "group_id") end function getMemberGroup (id) return getMemberData (id, "group_id"); end function setMemberGroup (id, group) setMemberData (id, "group_id", group); setMemberData (id, "join_time", getRealTime().timestamp); end function setPlayerGroup (player, group) local canhe, err = canPlayerJoinGroup(player); if not canhe then exports.mtatr_hud:dm (err, player, 200, 0, 0); return; end local id = exports.database:getPlayerId (player); setMemberGroup (id, group); local name = getGroupName (group); local r, g, b = getGroupColor (group); if TEAM then local team = getTeamFromName (name); if not isElement (team) then team = createTeam (name, r, g, b); end setPlayerTeam (player, team); else player:setData (TEAM_DATA, name); setPlayerNametagColor (player, r, g, b); local tag = getGroupData (getGroupFromName (name), "tag"); if tag and exports.mtatr_accounts:getPlayerCurrentCharacter (player) then local name = tag..exports.mtatr_accounts:getPlayerCurrentCharacter (player); if #name > 22 then name = name:sub (1, 22 - (#name - 22)); end setPlayerName (player, name); end end end function canPlayerCreateGroup (player, name, tag) if isPlayerInAGroup (player) then return false, "Grup kurmak için şuanki grubunuzdan çıkmanız gerekmektedir."; end if doesGroupExist (name) then return false, "Bu isimde bir grup zaten var. Lütfen başka isim seçin."; end if getGroupFromTag (tag) then return false, "Bu tagi başka bir klan kullanıyor. Lütfen başka bir tag seçin."; end local money = tonumber (get ("*Miktar")); local level = tonumber (get ("*Level")); if getPlayerMoney (player) < money then return false, "Grup oluşturmak için yeterli miktarda paranız yok."; end if exports.mtatr_mode:getPlayerCharacterLevel (player) < level then return false, "Grup oluşturmak için en az "..level.." seviye karakteriniz olmalı."; end return true; end function canPlayerJoinGroup (player) if isPlayerInAGroup (player) then return false, "Gruba girmek için şuanki grubunuzdan çıkmanız gerekmektedir."; end return true; end function kickMemberOut (id) local group = getPlayersInGroup(getMemberGroup(id)); dbExec (db, "DELETE FROM fr_group_members WHERE user_id = ?", id); members[id] = nil; for i, v in ipairs (group) do updateInfo(v); end end function kickPlayerOut (player) if isElement (player) then local id = exports.database:getPlayerId(player); kickMemberOut (id); if TEAM then setPlayerTeam (player, nil); end player:setData(TEAM_DATA, nil); setGroupWindow (player, false); local r, g, b = math.random(1, 255), math.random (1, 255), math.random(1, 255); if exports.database:getPlayerData (exports.database:getPlayerId (player), "userinfo", "usercolour") then r, g, b = unpack (fromJSON (exports.database:getPlayerData (exports.database:getPlayerId (player), "userinfo", "usercolour"))) end setPlayerName (player, exports.mtatr_accounts:getPlayerCurrentCharacter (player)); setPlayerNametagColor (player, r, g, b); end end --ranks function getMemberRank (member) return getMemberData (member, "rank_id"); end function setMemberRank (member, rank) setMemberData (member, "rank_id", rank); end function getPlayerRank (player) local id = exports.database:getPlayerId(player); return getMemberRank (id); end function setPlayerRank (player, rank) local id = exports.database:getPlayerId(player); setMemberRank (id, rank); end function getMembersByRank (group, rank) local tbl = {}; for i, v in ipairs (getMembersInGroup (group)) do if getMemberRank (v) == rank then table.insert (tbl, v); end end return tbl; end function promoteMember (promoter, player) if getPlayerRank (promoter)~= "Kurucu" then exports.mtatr_hud:dm ("Rank yükseltmek için kurucu olmanız gerek.", promoter, 200, 0, 0); return false; end if getMemberRank (player) == "Kurucu" then exports.mtatr_hud:dm ("Oyuncu rankı en üst seviyede.", promoter, 200, 0, 0); return false; end if getMemberRank (player) == "Lider" then -- setMemberRank (player, "Kurucu"); exports.mtatr_hud:dm ("Oyuncu rankı en üst seviyede.", promoter, 200, 0, 0); return false elseif getMemberRank (player) == "Üye" then setMemberRank (player, "Kıdemli"); elseif getMemberRank (player) == "Kıdemli" then setMemberRank (player, "Yrd. Lider"); elseif getMemberRank (player) == "Yrd. Lider" then setMemberRank (player, "Lider"); end return true; end function demoteMember (demoter, player) local rank = getMemberRank (player); local group = getPlayerGroup (demoter); if getPlayerRank (demoter) ~= "Kurucu" then exports.mtatr_hud:dm ("Rank indirmek için kurucu olmanız gerek.", demoter, 200, 0, 0); return false; end if rank == getPlayerRank (demoter) and exports.database:getPlayerId (demoter) ~= player then exports.mtatr_hud:dm ("Aynı ranka sahip üyenin rankını indiremezsiniz.", demoter, 200, 0, 0); return false; end if rank == "Kurucu" then if #getMembersByRank (group, "Kurucu") == 1 then exports.mtatr_hud:dm ("Bu işlemi yapmak için başka birini kuruculuğa yükseltmeniz gerekmektedir.", demoter, 200, 0, 0); return false; end end if rank == "Üye" then return false; end if rank == "Lider" then setMemberRank (player, "Yrd. Lider"); elseif rank == "Yrd. Lider" then setMemberRank (player, "Kıdemli"); elseif rank == "Kıdemli" then setMemberRank (player, "Üye"); elseif rank == "Kurucu" then setMemberRank (player, "Lider"); end return true; end function chatGroup (player, msg) local group = getPlayerGroup (player); local r, g, b = getGroupColor (group); local name = getGroupName (group); for i, v in ipairs (getPlayersInGroup(group)) do outputChatBox ("[GRUP] "..player:getName()..":#ffffff "..msg, v, r, g, b, true); end end addEvent ("onPlayerCharacterLogin"); addEventHandler ("onPlayerCharacterLogin", root, function () if isPlayerInAGroup (source) then local group = getPlayerGroup (source); local name = getGroupName (group); local r, g, b = getGroupColor (group) if TEAM then local team = getTeamFromName (name); if not isElement (team) then team = createTeam (name, r, g, b); end setPlayerTeam (source, team); else source:setData (TEAM_DATA, name); setPlayerNametagColor (source, r, g, b); end end end, true, "high+7" ); addEventHandler ("onPlayerQuit", root, function () if TEAM then local team = getPlayerTeam (source); if isElement (team) then if countPlayersInTeam (team) == 1 then team:destroy(); end end end end );
local MockPlayers = {} MockPlayers.__index = MockPlayers function MockPlayers.new() local playerAddedBindable = Instance.new("BindableEvent") local playerRemovingBindable = Instance.new("BindableEvent") local self = setmetatable({ _playerAddedBindable = playerAddedBindable, _playerRemovingBindable = playerRemovingBindable, PlayerAdded = playerAddedBindable.Event, PlayerRemoving = playerRemovingBindable.Event, GetPlayerByUserId = MockPlayers.GetPlayerByUserId, GetPlayers = MockPlayers.GetPlayers, _players = {}, }, MockPlayers) return self end function MockPlayers:addPlayer(userId, userName, displayName) local player = { UserId = userId, Name = userName, DisplayName = displayName, } table.insert(self._players, player) self._playerAddedBindable:Fire(player) return player end function MockPlayers:removePlayer(userId) for i = #self._players, 1, -1 do local player = self._players[i] if player.UserId == userId then self._playerRemovingBindable:Fire(player) table.remove(self._players, i) break end end end function MockPlayers:GetPlayerByUserId(userId) for _, player in ipairs(self._players) do if player.UserId == userId then return player end end return nil end function MockPlayers:GetPlayers() return self._players end return function() local PiiFilter = require(script.Parent.PiiFilter) it("should clean PII from strings", function() local mockPlayers = MockPlayers.new() mockPlayers:addPlayer(1234567, "TestUsername", "TestDisplayName") local filter = PiiFilter.new({ eraseTimeout = 5, testHarness = { players = mockPlayers, wait = function() end, } }) filter:startTracking() local testString = "something(1234567) + u/n TestUsername + display TestDisplayName" local expectedString = "something(UserId(1)) + u/n UserName(1) + display DisplayName(1)" local cleanedString = filter:cleanPii(testString) expect(cleanedString).to.equal(expectedString) filter:stopTracking() end) it("should use the same disambiguator if the player leaves and rejoins", function() local mockPlayers = MockPlayers.new() mockPlayers:addPlayer(1234567, "TestUsername", "TestDisplayName") local filter = PiiFilter.new({ eraseTimeout = 5, testHarness = { players = mockPlayers, wait = function() end, } }) filter:startTracking() local testString = "something(1234567) + u/n TestUsername + display TestDisplayName" local firstOutput = filter:cleanPii(testString) mockPlayers:removePlayer(1234567) mockPlayers:addPlayer(1234567) local secondOutput = filter:cleanPii(testString) expect(secondOutput).to.equal(firstOutput) filter:stopTracking() end) it("should keep PII info stored for a short time after the player leaves", function() local mockPlayers = MockPlayers.new() mockPlayers:addPlayer(1234567, "TestUsername", "TestDisplayName") local waitFnCallCount = 0 local function waitFn(delay) expect(delay).to.equal(1) waitFnCallCount += 1 wait(delay) end local filter = PiiFilter.new({ eraseTimeout = 1, testHarness = { players = mockPlayers, wait = waitFn, } }) filter:startTracking() mockPlayers:removePlayer(1234567) expect(waitFnCallCount).to.equal(1) -- It's within 1 second of the player leaving, so their information should still be stored -- in the filter and should be removed. local testString = "something(1234567) + u/n TestUsername + display TestDisplayName" local cleanedString = filter:cleanPii(testString) expect(cleanedString).to.equal("something(UserId(1)) + u/n UserName(1) + display DisplayName(1)") wait(1) -- At this point the PII info should be removed, per the erase timeout. -- We expect no filtering to take place. local uncleanedString = filter:cleanPii(testString) expect(uncleanedString).to.equal(testString) filter:stopTracking() end) end
include('shared.lua') include('rules.lua') local brdpos = { ["x"] = { [1] = -14.7, [2] = -10.5, [3] = -6.3, [4] = -2.1, [5] = 2.1, [6] = 6.3, [7] = 10.5, [8] = 14.7 }, ["y"] = { [1] = -14.45, [2] = -10.3, [3] = -6.15, [4] = -2, [5] = 2.25, [6] = 6.4, [7] = 10.55, [8] = 14.7 } } local rectpos = { ["x"] = { [1] = -20, [2] = -15, [3] = -10, [4] = -5, [5] = 0, [6] = 5, [7] = 10, [8] = 15 }, ["y"] = { [1] = 15, [2] = 10, [3] = 5, [4] = 0, [5] = -5, [6] = -10, [7] = -15, [8] = -20 } } local mdlsize = { [1] = 0.13, [2] = 0.22 } local ChessModels = { [1] = "models/props_phx/games/chess/white_rook.mdl", [2] = "models/props_phx/games/chess/white_knight.mdl", [3] = "models/props_phx/games/chess/white_bishop.mdl", [4] = "models/props_phx/games/chess/white_king.mdl", [5] = "models/props_phx/games/chess/white_queen.mdl", [6] = "models/props_phx/games/chess/white_pawn.mdl", [7] = "models/props_phx/games/chess/black_rook.mdl", [8] = "models/props_phx/games/chess/black_knight.mdl", [9] = "models/props_phx/games/chess/black_bishop.mdl", [10] = "models/props_phx/games/chess/black_king.mdl", [11] = "models/props_phx/games/chess/black_queen.mdl", [12] = "models/props_phx/games/chess/black_pawn.mdl" } surface.CreateFont( "ChessGameFontPlayer", { font = "Default", size = 30, weight = 450, antialias = true, additive = false, shadow = false, outline = false } ) net.Receive('Chess_Game', function() local chess = Entity(net.ReadUInt(32)) local cmd = net.ReadUInt(4) if not IsValid(chess) then return end if cmd == 1 then chess.brd_data = net.ReadTable() elseif cmd == 2 then chess:ChangeStep(net.ReadTable(),net.ReadBool()) elseif cmd == 3 then chess:ChangePiece(net.ReadUInt(7)) elseif cmd == 4 then chess:SendPlyData(net.ReadTable(),net.ReadTable()) elseif cmd == 5 then hook.Remove( "KeyPress", chess ) elseif cmd == 6 then chess:ResetGameCl() end end) function ENT:SendPlyData(t_type,t_moved) self.piece.type = t_type self.piece.moved = t_moved self.sel = { ["x"] = 0, ["y"] = 0 } self.look = { ["x"] = 0, ["y"] = 0 } self:ResetAvailable() self:AddHooks() self:CheckKing() end function ENT:ChangePiece(ind) if self.mdls and self.mdls.piece and IsValid(self.mdls.piece[ind]) then self.piece.type[ind] = 5 self.mdls.piece[ind]:Remove() if ind <= 16 then self.mdls.piece[ind] = ClientsideModel(ChessModels[5], RENDERGROUP_OPAQUE) else self.mdls.piece[ind] = ClientsideModel(ChessModels[11], RENDERGROUP_OPAQUE) end self.mdls.piece[ind]:SetNoDraw(true) self.mdls.piece[ind]:SetPos(self:GetPos()) local mat = Matrix() mat:Scale(Vector(mdlsize[2], mdlsize[2], mdlsize[2])) self.mdls.piece[ind]:EnableMatrix("RenderMultiply", mat) end end function ENT:Initialize() self.available = {} self.brd_data = {} self.sel = { ["x"] = 0, ["y"] = 0 } self.look = { ["x"] = 0, ["y"] = 0 } self.kwarn = { ["x"] = 0, ["y"] = 0 } self.piece = { ["type"] = {}, ["moved"] = {} } self:ResetBrdData() net.Start( 'Chess_Game' ) net.WriteUInt( self:EntIndex(), 32 ) net.WriteUInt( 0, 3 ) net.WriteEntity( LocalPlayer() ) net.SendToServer() end function ENT:AddHooks() local last_time = RealTime() - 3 hook.Add("KeyPress", self, function(self, ply, key) if not IsValid(self) then return end if key == IN_RELOAD and self:GetPly(self:GetTableOwner()) == ply and RealTime() - last_time > 3 then net.Start( 'Chess_Game' ) net.WriteUInt( self:EntIndex(), 32 ) net.WriteUInt( 1, 3 ) net.WriteEntity( LocalPlayer() ) net.SendToServer() last_time = RealTime() end if key == IN_ATTACK and self:GetPly(self:GetTableTurn()) == ply and self.look.x != 0 and self.look.y != 0 then if self.available[self.look.x][self.look.y] then self:MovePiece(self.look.x,self.look.y) else if self.brd_data[self.look.x][self.look.y] != 0 then self:CheckPiece( self.look.x, self.look.y ) end end end end) end function ENT:CreateModels() self.mdls = {} self.mdls.brd = ClientsideModel("models/props_phx/games/chess/board.mdl", RENDERGROUP_OPAQUE) self.mdls.brd:SetNoDraw(true) self.mdls.brd:SetPos(self:GetPos()) local matbrd = Matrix() matbrd:Scale(Vector(mdlsize[1], mdlsize[1], mdlsize[1])) self.mdls.brd:EnableMatrix("RenderMultiply", matbrd) self:CreatePieceModels() end function ENT:CreatePieceModels() self.mdls.piece = { [1] = ClientsideModel(ChessModels[1], RENDERGROUP_OPAQUE), [2] = ClientsideModel(ChessModels[2], RENDERGROUP_OPAQUE), [3] = ClientsideModel(ChessModels[3], RENDERGROUP_OPAQUE), [4] = ClientsideModel(ChessModels[4], RENDERGROUP_OPAQUE), [5] = ClientsideModel(ChessModels[5], RENDERGROUP_OPAQUE), [6] = ClientsideModel(ChessModels[3], RENDERGROUP_OPAQUE), [7] = ClientsideModel(ChessModels[2], RENDERGROUP_OPAQUE), [8] = ClientsideModel(ChessModels[1], RENDERGROUP_OPAQUE), [9] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [10] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [11] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [12] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [13] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [14] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [15] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [16] = ClientsideModel(ChessModels[6], RENDERGROUP_OPAQUE), [17] = ClientsideModel(ChessModels[7], RENDERGROUP_OPAQUE), [18] = ClientsideModel(ChessModels[8], RENDERGROUP_OPAQUE), [19] = ClientsideModel(ChessModels[9], RENDERGROUP_OPAQUE), [20] = ClientsideModel(ChessModels[10], RENDERGROUP_OPAQUE), [21] = ClientsideModel(ChessModels[11], RENDERGROUP_OPAQUE), [22] = ClientsideModel(ChessModels[9], RENDERGROUP_OPAQUE), [23] = ClientsideModel(ChessModels[8], RENDERGROUP_OPAQUE), [24] = ClientsideModel(ChessModels[7], RENDERGROUP_OPAQUE), [25] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [26] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [27] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [28] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [29] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [30] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [31] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE), [32] = ClientsideModel(ChessModels[12], RENDERGROUP_OPAQUE) } for k,v in pairs(self.mdls.piece) do v:SetNoDraw(true) v:SetPos(self:GetPos()) local mat = Matrix() mat:Scale(Vector(mdlsize[2], mdlsize[2], mdlsize[2])) v:EnableMatrix("RenderMultiply", mat) end end function ENT:ResetAvailable() for i=1,8 do self.available[i] = {} for j=1,8 do self.available[i][j] = false end end end function ENT:ResetGameCl() self.sel.x = 0 self.sel.y = 0 self:RemovePieceModels() self:CreatePieceModels() self:ResetBrdData() self:ResetAvailable() for i=1,32 do self.piece.moved[i] = false end for i=9,16 do self.piece.type[i] = 0 end for i=25,32 do self.piece.type[i] = 0 end self.piece.type[1] = 1 self.piece.type[2] = 2 self.piece.type[3] = 3 self.piece.type[4] = 4 self.piece.type[5] = 5 self.piece.type[6] = 3 self.piece.type[7] = 2 self.piece.type[8] = 1 self.piece.type[17] = 1 self.piece.type[18] = 2 self.piece.type[19] = 3 self.piece.type[20] = 4 self.piece.type[21] = 5 self.piece.type[22] = 3 self.piece.type[23] = 2 self.piece.type[24] = 1 self.kwarn = { ["x"] = 0, ["y"] = 0 } end function ENT:Think() if LocalPlayer() != self:GetPly(self:GetTableTurn()) then return end local piecepos,pieceang = LocalToWorld(Vector(0.1, 0, 34.5), Angle(0, 180, 0), self:GetPos(), self:GetAngles()) local vec = util.IntersectRayWithPlane(LocalPlayer():EyePos(), LocalPlayer():EyeAngles():Forward(), piecepos, pieceang:Up()) if vec == nil then return end local brpos,brang = WorldToLocal(vec, Angle(), self:GetPos(), self:GetAngles()) local posx = math.ceil( brpos.X / 4.2 + 4 ) local posy = math.ceil( brpos.Y / 4.2 + 4 ) if posx > 8 or posx < 1 or posy > 8 or posy < 1 then return end self.look.x = posx self.look.y = posy end function ENT:MovePiece(x,y) net.Start( 'Chess_Game' ) net.WriteUInt( self:EntIndex(), 32 ) net.WriteUInt( 2, 3 ) net.WriteEntity( LocalPlayer() ) net.WriteUInt( self.sel.x, 5 ) net.WriteUInt( self.sel.y, 5 ) net.WriteUInt( x, 5 ) net.WriteUInt( y, 5 ) net.SendToServer() self.sel.x = 0 self.sel.y = 0 self.kwarn = { ["x"] = 0, ["y"] = 0 } self:ResetAvailable() end function SetPosToChess(pos, ang, x, y, z ) local setvector = Vector(x, y, z) setvector:Rotate( ang ) local setpos = pos + setvector return setpos end function ENT:Draw() self:DrawModel() if not self.mdls or not IsValid(self.mdls.brd) then self:CreateModels() end local boardpos,boardang = LocalToWorld(Vector(0, 0, 32), Angle(-90, 0, 0), self:GetPos(), self:GetAngles()) self.mdls.brd:SetRenderOrigin(boardpos) self.mdls.brd:SetRenderAngles(boardang) self.mdls.brd:DrawModel() if LocalPlayer():GetShootPos():Distance(self:GetPos()) > 500 then return end local piecepos,pieceang = LocalToWorld(Vector(0, 0, 34.5), Angle(0, 0, 0), self:GetPos(), self:GetAngles()) local piecepos_w,pieceang_w = LocalToWorld(Vector(0, 0, 34.5), Angle(0, -90, 0), self:GetPos(), self:GetAngles()) local piecepos_b,pieceang_b = LocalToWorld(Vector(0, 0, 34.5), Angle(0, 90, 0), self:GetPos(), self:GetAngles()) for i=1,8 do for j=1,8 do if self.brd_data[i][j] != 0 then local mdl = self.mdls.piece[self.brd_data[i][j]] mdl:SetRenderOrigin(SetPosToChess(piecepos, pieceang, brdpos.x[i], brdpos.y[j], 0 )) if self.brd_data[i][j] == 2 or self.brd_data[i][j] == 7 then mdl:SetRenderAngles(pieceang_w) elseif self.brd_data[i][j] == 18 or self.brd_data[i][j] == 23 then mdl:SetRenderAngles(pieceang_b) else mdl:SetRenderAngles(pieceang) end mdl:DrawModel() end end end if IsValid(self:GetPly1()) then local ang = self:GetAngles() ang:RotateAroundAxis( ang:Up(), 180 ) cam.Start3D2D( SetPosToChess(self:GetPos(), self:GetAngles(), 0, 20, 32.3 ), ang, 0.2 ) if self:GetTableTurn() then draw.DrawText( self:GetPly1():Nick(), "ChessGameFontPlayer", 0, 0, Color( 0, 255, 0 ), 1 ) else draw.DrawText( self:GetPly1():Nick(), "ChessGameFontPlayer", 0, 0, Color( 255, 0, 0 ), 1 ) end if self:GetTableOwner() then draw.DrawText("Owner", "ChessGameFontPlayer", 0, 20, Color(255, 255, 0), TEXT_ALIGN_CENTER) end cam.End3D2D() end if IsValid(self:GetPly2()) then cam.Start3D2D( SetPosToChess(self:GetPos(), self:GetAngles(), 0, -20, 32.3 ), self:GetAngles(), 0.2 ) if not self:GetTableTurn() then draw.DrawText( self:GetPly2():Nick(), "ChessGameFontPlayer", 0, 0, Color( 0, 255, 0 ), 1 ) else draw.DrawText( self:GetPly2():Nick(), "ChessGameFontPlayer", 0, 0, Color( 255, 0, 0 ), 1 ) end if not self:GetTableOwner() then draw.DrawText("Owner", "ChessGameFontPlayer", 0, 20, Color(255, 255, 0), TEXT_ALIGN_CENTER) end cam.End3D2D() end if LocalPlayer() == self:GetPly(self:GetTableTurn()) then cam.Start3D2D( SetPosToChess(self:GetPos(), self:GetAngles(), 0, 0.2, 34.58 ), self:GetAngles(), 0.085 ) if self.look.x != 0 and self.look.y != 0 then if ( self.brd_data[self.look.x][self.look.y] != 0 and (self:GetTableTurn() and self.brd_data[self.look.x][self.look.y] < 17) or ( not self:GetTableTurn() and self.brd_data[self.look.x][self.look.y] > 16)) then surface.SetDrawColor(Color(0,255,0,200)) else surface.SetDrawColor(Color(255,0,0,200)) end surface.DrawRect(rectpos.x[self.look.x] * 10, rectpos.y[self.look.y] * 9.8, 50, 50) end if self.sel.x != 0 and self.sel.y != 0 then surface.SetDrawColor(Color(0,150,0,200)) surface.DrawRect(rectpos.x[self.sel.x] * 10, rectpos.y[self.sel.y] * 9.8, 50, 50) for i=1,8 do for j=1,8 do if self.available[i][j] == true then surface.SetDrawColor(Color(0,0,255,200)) surface.DrawRect(rectpos.x[i] * 10, rectpos.y[j] * 9.8, 50, 50) end end end end if self.kwarn.x != 0 and self.kwarn.y != 0 then surface.SetDrawColor(Color(255,100,0,200)) surface.DrawRect(rectpos.x[self.kwarn.x] * 10, rectpos.y[self.kwarn.y] * 9.8, 50, 50) end cam.End3D2D() end end function ENT:RemovePieceModels() for k,v in pairs(self.mdls.piece) do if v.SetNoDraw then v:Remove() end end end function ENT:OnRemove() if self.mdls.brd.SetNoDraw then self.mdls.brd:Remove() end self:RemovePieceModels() hook.Remove( "KeyPress", self ) end
return Def.ActorFrame{ Def.Quad{ InitCommand=cmd(setsize,SCREEN_WIDTH,SCREEN_HEIGHT/2;diffuse,color("0,0,0,1");xy,SCREEN_CENTER_X,SCREEN_CENTER_Y-SCREEN_HEIGHT/2;valign,1); OnCommand=cmd(y,SCREEN_CENTER_Y-SCREEN_HEIGHT/2;sleep,1;linear,0.3;y,SCREEN_CENTER_Y); }; Def.Quad{ InitCommand=cmd(setsize,SCREEN_WIDTH,SCREEN_HEIGHT/2;diffuse,color("0,0,0,1");xy,SCREEN_CENTER_X,SCREEN_CENTER_Y+SCREEN_HEIGHT/2;valign,0); OnCommand=cmd(y,SCREEN_CENTER_Y+SCREEN_HEIGHT/2;sleep,1;linear,0.3;y,SCREEN_CENTER_Y); }; };
require"imlua" require"imlua_process" require"imlua_fftw" local filename = "lena.jpg" local image = im.FileImageLoad(filename) local complex = im.ImageCreate(image:Width(), image:Height(), image:ColorSpace(), im.CFLOAT) im.ProcessFFT(image, complex) local c = complex[0][5][10] -- component=0(Red), y = 5 x =10 print(c[1], c[2]) complex[0][5][10] = { 2*c[1], c[2]/2 } local c = complex[0][5][10] print(c[1], c[2])
--[[ Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. ]]-- local tnt = require 'torchnet.env' local argcheck = require 'argcheck' local CoroutineBatchDataset, BatchDataset = torch.class('tnt.CoroutineBatchDataset', 'tnt.BatchDataset', tnt) CoroutineBatchDataset.__init = argcheck{ doc = [[ <a name="CoroutineBatchDataset"> #### tnt.CoroutineBatchDataset(@ARGP) @ARGT Given a `dataset`, `tnt.CoroutineBatchDataset` merges samples from this dataset to form a new sample which can be interpreted as a batch (of size `batchsize`). It behaves the same and has the same arguments as `tnt.BatchDataset` (see the documentation there for additional details), with one important distinction: it allows the underlying dataset to postpone returning the individual samples once by doing a call to `coroutine.yield()` (from the underlying dataset). This is useful when using datasets that are inefficient or slow when they need to provide the required sample immediately after a call to `dataset:get()`. The general pattern of code in the underlying `dataset:get()` would be: ```lua FooDataset.get = function(self, idx) prepare(idx) -- stores sample in self.__data[idx] coroutine.yield() return self.__data[idx] end ``` Herein, the function `prepare(idx)` can implement, for instance, a buffering of indices before actually fetching them. ]], {name = 'self', type = 'tnt.CoroutineBatchDataset'}, {name = 'dataset', type = 'tnt.Dataset'}, {name = 'batchsize', type = 'number'}, {name = 'perm', type = 'function', default = function(idx, size) return idx end}, {name = 'merge', type = 'function', opt = true}, {name = 'policy', type = 'string', default = 'include-last'}, call = function(self, dataset, batchsize, perm, merge, policy) BatchDataset.__init(self, dataset, batchsize, perm, merge, policy) end } CoroutineBatchDataset.get = argcheck{ {name = 'self', type = 'tnt.CoroutineBatchDataset'}, {name = 'idx', type = 'number'}, call = function(self, idx) assert(idx >= 1 and idx <= self:size(), 'index out of bound') assert(idx == math.floor(idx), 'index should be integer value') -- create and start coroutines that perform get(): local crs, samples, maxidx = {}, {}, self.dataset:size() for n = 1,self.batchsize do local idx = (idx - 1) * self.batchsize + n if idx > maxidx then break end -- start coroutine: crs[n] = coroutine.create( function() return self.dataset:get(self.perm(idx)) end ) -- create coroutine that gets example local status, sample = coroutine.resume(crs[n]) -- register sample if not status then error(string.format('dataset threw error: %s', sample)) end -- if coroutine does not yield but dies, store sample: if coroutine.status(crs[n]) == 'dead' then samples[n] = sample end end -- get the samples from coroutines that are suspended: for n = 1,self.batchsize do if crs[n] and coroutine.status(crs[n]) == 'suspended' then local status, sample = coroutine.resume(crs[n]) if not status then error(string.format('dataset threw error: %s', sample)) end assert(coroutine.status(crs[n]) == 'dead', 'coroutine did not die') samples[n] = sample end end -- return batch: samples = self.makebatch(samples) collectgarbage() return samples end }
local module = {} local mt = {} mt.__unm = function(rhs) return module.Vector3D(-rhs[1], -rhs[2], -rhs[3]) end mt.__add = function(lhs, rhs) return module.Vector3D(lhs[1] + rhs[1], lhs[2] + rhs[2], lhs[3] + rhs[3]) end mt.__sub = function(lhs, rhs) return module.Vector3D(lhs[1] - rhs[1], lhs[2] - rhs[2], lhs[3] - rhs[3]) end mt.__mul = function(lhs, rhs) if type(rhs) == 'number' then return module.Vector3D(lhs[1] * rhs, lhs[2] * rhs, lhs[3] * rhs) elseif type(lhs) == 'number' then return module.Vector3D(lhs * rhs[1], lhs * rhs[2], lhs * rhs[3]) else return module.Vector3D(lhs[1] * rhs[1], lhs[2] * rhs[2], lhs[3] * rhs[3]) end end mt.__div = function(lhs, rhs) if type(rhs) == 'number' then return module.Vector3D(lhs[1] / rhs, lhs[2] / rhs, lhs[3] / rhs) elseif type(lhs) == 'number' then return module.Vector3D(lhs / rhs[1], lhs / rhs[2]) else return module.Vector3D(lhs[1] / rhs[1], lhs[1] / rhs[1], lhs[3] / rhs[3]) end end mt.__tostring = function(v) return '{'..v[1]..', '..v[2]..', '..v[3]..'}' end mt.__eq = function(lhs, rhs) return (lhs[1] == rhs[1]) and (lhs[2] == rhs[2]) and (lhs[3] == rhs[3]) end local funcs = {} function funcs:Dup() return module.Vector3D(self[1], self[2], self[3]) end local _sqrt = math.sqrt function funcs:GetLength() --Return the length of the vector (i.e. the distance from (0,0), see README.md for examples of using this) return _sqrt(self[1]^2 + self[2]^2 + self[3]^2) end function funcs:GetSquaredLength() return self[1]^2 + self[2]^2 + self[3]^2 end function funcs:Normalize() local invLength = 1 / self:GetLength() return module.Vector3D( self[1] * invLength, self[2] * invLength, self[3] * invLength) end function funcs:Dot(other) return self[1]*other[1] + self[2]*other[2] + self[3]*other[3] end function funcs:Cross(other) local u1 = self[1] local u2 = self[2] local u3 = self[3] local v1 = other[1] local v2 = other[2] local v3 = other[3] local x = u2*v3 - u3*v2 local y = u3*v1 - u1*v3 local z = u1*v2 - u2*v1 return module.Vector3D(x, y, z) end mt.__index = funcs module.Vector3D = function(ix, iy, iz) return setmetatable({ix, iy, iz}, mt) end return module
require('Utilities'); function Client_PresentMenuUI(rootParent, setMaxSize, setScrollable, game) if (not WL.IsVersionOrHigher or not WL.IsVersionOrHigher("5.17")) then UI.Alert("You must update your app to the latest version to use this mod"); return; end Game = game; SubmitBtn = nil; setMaxSize(450, 400); vert = UI.CreateVerticalLayoutGroup(rootParent); if (game.Us == nil) then UI.CreateLabel(vert).SetText("You cannot gift armies since you're not in the game"); return; end local row1 = UI.CreateHorizontalLayoutGroup(vert); UI.CreateLabel(row1).SetText("Gift armies to this player: "); TargetPlayerBtn = UI.CreateButton(row1).SetText("Select player...").SetOnClick(TargetPlayerClicked); local row2 = UI.CreateHorizontalLayoutGroup(vert); UI.CreateLabel(row2).SetText("Gift armies from this territory: "); TargetTerritoryBtn = UI.CreateButton(row2).SetText("Select source territory...").SetOnClick(TargetTerritoryClicked); TargetTerritoryInstructionLabel = UI.CreateLabel(vert).SetText("").SetPreferredHeight(70); --give it a fixed height just so things don't jump around as we change its text end function TargetPlayerClicked() local players = filter(Game.Game.Players, function (p) return p.ID ~= Game.Us.ID end); local options = map(players, PlayerButton); UI.PromptFromList("Select the player you'd like to give armies to", options); end function PlayerButton(player) local name = player.DisplayName(nil, false); local ret = {}; ret["text"] = name; ret["selected"] = function() TargetPlayerBtn.SetText(name); TargetPlayerID = player.ID; end return ret; end function TargetTerritoryClicked() UI.InterceptNextTerritoryClick(TerritoryClicked); TargetTerritoryInstructionLabel.SetText("Please click on the territory you wish to gift armies from. If needed, you can move this dialog out of the way."); TargetTerritoryBtn.SetInteractable(false); end function TerritoryClicked(terrDetails) TargetTerritoryBtn.SetInteractable(true); if (terrDetails == nil) then --The click request was cancelled. TargetTerritoryInstructionLabel.SetText(""); else --Territory was clicked, remember it TargetTerritoryInstructionLabel.SetText("Selected territory: " .. terrDetails.Name); SelectedTerritory = terrDetails; CheckCreateFinalStep(); end return ret; end function CheckCreateFinalStep() if (SubmitBtn == nil) then local row3 = UI.CreateHorizontalLayoutGroup(vert); UI.CreateLabel(row3).SetText("How many armies would you like to gift: "); NumArmiesInput = UI.CreateNumberInputField(row3).SetSliderMinValue(1); SubmitBtn = UI.CreateButton(vert).SetText("Gift").SetOnClick(SubmitClicked); end local maxArmies = Game.LatestStanding.Territories[SelectedTerritory.ID].NumArmies.NumArmies; NumArmiesInput.SetSliderMaxValue(maxArmies).SetValue(maxArmies); end function SubmitClicked() local msg = 'Gifting ' .. NumArmiesInput.GetValue() .. ' armies from ' .. SelectedTerritory.Name .. ' to ' .. Game.Game.Players[TargetPlayerID].DisplayName(nil, false); local payload = 'GiftArmies2_' .. NumArmiesInput.GetValue() .. ',' .. SelectedTerritory.ID .. ',' .. TargetPlayerID; local orders = Game.Orders; table.insert(orders, WL.GameOrderCustom.Create(Game.Us.ID, msg, payload)); Game.Orders = orders; end
function Client_PresentSettingsUI(rootParent) end
return function() local module = Deus:Load("Deus.Symbol") describe("global symbols", function() it("should equal", function() expect(module.get("foo")).to.be.equal(module.get("foo")) end) it("should never equal", function() expect(module.get("foo")).to.never.be.equal(module.get("bar")) end) end) describe("non-global symbols", function() it("should equal", function() local symbol = module.new("foo", true) expect(symbol).to.be.equal(symbol) end) it("should never equal", function() expect(module.new("foo", true)).to.never.be.equal(module.new("foo", true)) end) end) end
Crate:describe(function(s) s.name = 'Flow' s.version = '0.8.0' s.date = '2019-11-15' s.summary = 'Flux Core.' s.description = 'Core files that provide most of what Flux actually is.' s.author = 'TeslaCloud Studios' s.email = 'support@teslacloud.net' s.files = { 'lib/inflector/sh_inflector.lua', 'lib/inflector/sh_inflections.lua', 'shared.lua' } s.global = 'Flow' s.website = 'https://teslacloud.net' s.license = 'MIT' end)
local install_path = vim.fn.stdpath("data") .. "/site/pack/packer/start/packer.nvim" if vim.fn.empty(vim.fn.glob(install_path)) > 0 then vim.fn.system({ "git", "clone", "https://github.com/wbthomason/packer.nvim", install_path }) vim.api.nvim_command("packadd packer.nvim") end vim.cmd("packadd packer.nvim") local packer = require("packer") packer.init({ display = { non_interactive = true }, }) packer.startup(function(use) use("nvim-lua/plenary.nvim") end) vim.cmd("set rtp+=.") -- The hidden option is required for termmaker to work vim.o.hidden = true
--[[-- baseurl = request.get_relative_baseurl() This function returns a relative base URL of the application. If request.force_absolute_baseurl() has been called before, an absolute URL is returned. --]]-- function request.get_relative_baseurl() if request._force_absolute_baseurl then return (request.get_absolute_baseurl()) else return request._relative_baseurl end end
--[[********************************** * * Multi Theft Auto - Admin Panel * * client/admin_guard.lua * * Original File by lil_Toady * **************************************]] _addEventHandler = addEventHandler function addEventHandler(event, element, handler, propagated) _addEventHandler( event, element, function(...) if (sourceResource ~= getThisResource()) then local resource = getResourceName(sourceResource) outputDebugString( "Warning: Resource '" .. resource .. "' tried to access admin event '" .. event .. "'", 2, 255, 0, 0 ) return end handler(...) end, propagated ) end
----------------------------------- -- Area: Norg -- NPC: Quntsu-Nointsu -- Title Change NPC -- !pos -67 -1 34 252 ----------------------------------- require("scripts/globals/titles") ----------------------------------- local eventId = 1011 local titleInfo = { { cost = 200, title = { tpz.title.HONORARY_DOCTORATE_MAJORING_IN_TONBERRIES, tpz.title.BUSHIDO_BLADE, tpz.title.BLACK_MARKETEER, tpz.title.CRACKER_OF_THE_SECRET_CODE, tpz.title.LOOKS_SUBLIME_IN_A_SUBLIGAR, tpz.title.LOOKS_GOOD_IN_LEGGINGS, }, }, { cost = 300, title = { tpz.title.APPRENTICE_SOMMELIER, tpz.title.TREASUREHOUSE_RANSACKER, tpz.title.HEIR_OF_THE_GREAT_WATER, tpz.title.PARAGON_OF_SAMURAI_EXCELLENCE, tpz.title.PARAGON_OF_NINJA_EXCELLENCE, tpz.title.GUIDER_OF_SOULS_TO_THE_SANCTUARY, tpz.title.BEARER_OF_BONDS_BEYOND_TIME, tpz.title.FRIEND_OF_THE_OPOOPOS, tpz.title.PENTACIDE_PERPETRATOR, }, }, { cost = 400, title = { tpz.title.BEARER_OF_THE_WISEWOMANS_HOPE, tpz.title.BEARER_OF_THE_EIGHT_PRAYERS, tpz.title.LIGHTWEAVER, tpz.title.DESTROYER_OF_ANTIQUITY, tpz.title.SEALER_OF_THE_PORTAL_OF_THE_GODS, tpz.title.BURIER_OF_THE_ILLUSION, }, }, } function onTrade(player,npc,trade) end function onTrigger(player,npc) tpz.title.changerOnTrigger(player, eventId, titleInfo) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) tpz.title.changerOnEventFinish(player, csid, option, eventId, titleInfo) end
local TestActorComponent = Inherit(CppObjectBase) function TestActorComponent:BeginPlay() CppObjectBase.BeginPlay(self) -- test link to actor -- self:Timer(self.TestLinkDestroy, self):Time(1) end function TestActorComponent:TestLinkDestroy() end return TestActorComponent
local crud = require "kong.api.crud_helpers" return { ["/upstreams/"] = { GET = function(self, dao_factory) crud.paginated_set(self, dao_factory.upstreams) end, PUT = function(self, dao_factory) crud.put(self.params, dao_factory.upstreams) end, POST = function(self, dao_factory, helpers) crud.post(self.params, dao_factory.upstreams) end }, ["/upstreams/:name_or_id"] = { before = function(self, dao_factory, helpers) crud.find_upstream_by_name_or_id(self, dao_factory, helpers) end, GET = function(self, dao_factory, helpers) return helpers.responses.send_HTTP_OK(self.upstream) end, PATCH = function(self, dao_factory) crud.patch(self.params, dao_factory.upstreams, self.upstream) end, DELETE = function(self, dao_factory) crud.delete(self.upstream, dao_factory.upstreams) end }, ["/upstreams/:name_or_id/targets/"] = { before = function(self, dao_factory, helpers) crud.find_upstream_by_name_or_id(self, dao_factory, helpers) self.params.upstream_id = self.upstream.id end, GET = function(self, dao_factory) crud.paginated_set(self, dao_factory.targets) end, POST = function(self, dao_factory, helpers) -- when to cleanup: invalid-entries > (valid-ones * cleanup_factor) local cleanup_factor = 10 --cleaning up history, check if it's necessary... local target_history = dao_factory.targets:find_all( { upstream_id = self.params.upstream_id }) if target_history then --ignoring errors here, will be caught when posting below -- sort the targets for _,target in ipairs(target_history) do target.order = target.created_at..":"..target.id end -- sort table in reverse order table.sort(target_history, function(a,b) return a.order>b.order end) -- do clean up local cleaned = {} local delete = {} for _, entry in ipairs(target_history) do if cleaned[entry.target] then -- we got a newer entry for this target than this, so this one can go delete[#delete+1] = entry else -- haven't got this one, so this is the last one for this target cleaned[entry.target] = true cleaned[#cleaned+1] = entry if entry.weight == 0 then delete[#delete+1] = entry end end end -- do we need to cleanup? -- either nothing left, or when 10x more outdated than active entries if (#cleaned == 0 and #delete > 0) or (#delete >= (math.max(#cleaned,1)*cleanup_factor)) then ngx.log(ngx.INFO, "[admin api] Starting cleanup of target table for upstream ", tostring(self.params.upstream_id)) local cnt = 0 for _, entry in ipairs(delete) do -- not sending update events, one event at the end, based on the -- post of the new entry should suffice to reload only once dao_factory.targets:delete( { id = entry.id }, { quiet = true } ) -- ignoring errors here, deleted by id, so should not matter -- in case another kong-node does the same cleanup simultaneously cnt = cnt + 1 end ngx.log(ngx.INFO, "[admin api] Finished cleanup of target table", " for upstream ", tostring(self.params.upstream_id), " removed ", tostring(cnt), " target entries") end end crud.post(self.params, dao_factory.targets) end, }, }
local lfs = require "lfs" local Util = require("Lua/Util/Util") local parser = require("Lua/Util/wowtoolsparser") Util:MakeDir("src/data/globalstring") local pre = [[import type { GlobalStringInterface } from "./GlobalStringInterface" export const data: GlobalStringInterface = { ]] local locales = { "deDE", "enUS", -- same as enGB "esES", "esMX", "frFR", "itIT", "koKR", "ptBR", -- same as ptPT "ruRU", "zhCN", "zhTW", } -- its fine not escaping symbols, except single backslashes and backquotes local fixes = { KEY_BACKSLASH = [[\]], KEY_LEFTBRACKET = [[`]], -- esES/esMX } local m = {} local function IsValidTableKey(s) return not s:find("-") and not s:find("^%d") end function m:ToTypeScript(locale) local globalstrings = parser:ReadCSV("globalstrings", {header = true, build = CONSTANTS.LATEST_MAINLINE, locale = locale}) local stringsTable = {} for line in globalstrings:lines() do local flags = tonumber(line.Flags) if flags and flags&0x1 > 0 then table.insert(stringsTable, { BaseTag = line.BaseTag, TagText = line.TagText_lang }) end end table.sort(stringsTable, function(a, b) return a.BaseTag < b.BaseTag end) local t = {} local fs1 = '\t%s: String.raw`%s`,' local fs2 = '\t"%s": String.raw`%s`,' for _, tbl in pairs(stringsTable) do local key, value = tbl.BaseTag, tbl.TagText value = value:gsub("\\32", " ") -- space char if fixes[key] and value == fixes[key] then value = [[\]]..value end local fs = IsValidTableKey(key) and fs1 or fs2 table.insert(t, fs:format(key, value)) end table.insert(t, "}\n") return pre..table.concat(t, "\n") end function m:WriteLocales() local latest = parser:FindBuild("globalstrings", CONSTANTS.LATEST_MAINLINE) local cache = string.format("Lua/Data/cache/globalstrings/globalstrings_%s_enUS.csv", latest) if not lfs.attributes(cache) then -- skip if already exported for _, locale in pairs(locales) do local path = string.format("src/data/globalstring/%s.ts", locale) local data = self:ToTypeScript(locale) Util:WriteFile(path, data) end end end return m
for i,v in ipairs({ {972,-716.5,503.3,1370.7,0,0,340}, {972,-726.7,483.4,1370.7,0,0,325}, {972,-743,467.8,1368.7,7,0,305}, {972,-763,456,1365.9,9,0,298}, {972,-783,449.8,1362.3,10,0,277}, {972,-807,448.5,1355,10,0,270}, {972,-826.5,448,1352,10,0,272}, {972,-851,440,1349,7,0,300}, {972,-889.9,443.7,1343,7,0,270}, {5013,-725.65216,562.0235,1371.09912,0,0,0}, {4848,-874.10443,435.15048,1349.46594,0,0,0.0001}, {4848,-855.9823,435.1741,1354.28503,0,0,0.0001}, {4848,-804.67163,480.66504,1361.18628,0,11.1727,180}, {4848,-834.64172,480.66406,1355.24756,0,11.1727,180}, {4848,-806.04553,480.36514,1373.52942,0,0.8594,180}, {4848,-756.11145,518.32141,1375.09412,0,0.8594,180.8595}, {4848,-772.10083,518.26373,1379.73389,0,0.8594,180}, {4848,-793.71021,518.11725,1384.0376,0,0.8594,180}, {17531,-864.9953,482.2356,1351.66699,359.1406,0.8594,270}, {13132,-914.07361,508.13242,1349.23706,0,0,180}, {7019,-934.66406,431.02521,1349.4762,0,0,0}, {8428,-910.62763,440.31259,1349.08862,0,0,90}, {4848,-855.64502,438.94522,1345.90784,0,354.8434,0.0001}, {4848,-875.45441,438.74728,1343.99121,0,353.9839,0.0001}, {1505,-848.60852,441.33716,1351.96558,0,0,0}, {1505,-858.61267,441.43713,1351.07922,0,0,0}, {1505,-868.58929,441.38852,1349.96509,0,0,0}, {1505,-878.57697,441.31354,1349.04712,0,0,0}, {1505,-888.61578,441.28854,1348.00635,0,0,0}, {9949,-703.4386,550.05652,1382.98987,0,0,0}, {5013,-900.72742,513.12018,1346.01257,0,0,0}, {4848,-884.36694,531.00617,1349.6488,0,0,270.0001}, {4848,-883.88995,550.30005,1349.68445,0,0,270.0001}, {5013,-900.68457,593.99841,1346.01746,0,0,180}, {4848,-875.2735,499.45978,1348.1344,0,0,0.0001}, {4848,-884.3277,488.43655,1348.08814,2.5783,0,90}, {4848,-734.828,572.85748,1367.38355,0,0,90.0001}, {734,-732.6286,472.51477,1370.2854,0,0,314.9999}, {733,-716.28467,492.07434,1366.06433,0,0,213.7499}, {728,-719.14594,500.96744,1371.29956,0,0,213.7499}, {4848,-846.88275,587.40253,1347.23767,0,6.8755,179.1406}, {4848,-850.96704,589.09735,1353.54834,0,6.8755,180}, {4848,-824.48364,587.99133,1355.55127,0,0.8594,180}, {4848,-796.857,588.04541,1361.39185,0,9.4538,180}, {4848,-775.65662,588.05328,1367.13757,0,9.4538,180}, {4848,-756.10828,588.0426,1370.78674,0,9.4538,180}, {4848,-883.0141,510.68707,1348.03491,0,0,90}, {4848,-884.49377,515.00787,1343.09607,354.8434,0,90}, {4848,-754.29993,578.76953,1363.45349,0,16.3293,180}, {3361,-847.85779,440.79346,1352.2605,0,0,90}, {3361,-857.86292,440.70117,1351.19885,0,0,90}, {3361,-867.89496,440.73868,1350.16858,0,0,90}, {3361,-877.88825,440.86353,1349.35877,0,0,90}, {3361,-887.78589,440.7226,1348.14514,0,0,90}, {4848,-738.69635,542.28003,1367.55286,0,0,90.0001}, {13006,-941.91632,546.66711,1345.82849,0,0,271.7189}, {10063,-924.53107,590.26447,1359.22534,0,0,90}, {18240,-929.70819,567.41705,1345.96118,0,0,270.0003}, {18240,-944.67828,533.11877,1345.78626,0,0,91.7189}, {10063,-901.03912,609.323,1359.15686,0,0,0}, {4848,-875.03705,586.98468,1343.83032,0,6.8755,179.1406}, {823,-822.2298,576.55493,1355.51318,0,0,0}, {1506,-908.65448,510.71671,1346.18164,0,0,270}, {1506,-890.68189,541.32599,1346.20691,0,0,270}, {4848,-756.05023,519.41351,1375.2312,0,0.8594,0.0001}, {5017,-917.12091,488.68082,1349.3905,0,0,0}, {1506,-910.03668,496.85544,1346.12427,0,0,270}, {4848,-926.39319,517.13666,1347.42249,0,0,0.0001}, {4848,-884.88916,600.67474,1342.4635,0,0,270.0001}, {734,-750.75818,447.28873,1363.65051,0,0,0}, {4848,-744.25311,550.31622,1374.5791,89.3814,0,90.0001}, {4848,-744.224,532.37921,1374.72852,90.2408,0,90.0001}, {4848,-744.25458,587.67615,1374.55408,90.2408,0,90.0001}, {4848,-747.0398,550.15448,1374.92871,89.3814,0,270.0001}, {4880,-715.17157,596.16962,1376.88989,0,0,180}, {733,-764.17572,446.85501,1364.11829,0,0,281.2499}, {4848,-925.89142,478.26486,1347.07764,356.5623,0,0.0001}, }) do local obj = createObject(v[1], v[2], v[3], v[4], v[5], v[6], v[7]) setObjectScale(obj, 1) setElementDimension(obj, 0) setElementInterior(obj, 1) setElementDoubleSided(obj, true) end
Kick Script: game.Players.--Put name here: Remove()
ITEM.name = "Izlom Hand" ITEM.model ="models/lostsignalproject/items/parts/izlom_hand.mdl" ITEM.description = "The hand from an izlom." ITEM.longdesc = "A severed hand of an izlom - an extremely deformed humanoid mutant. It is certain that these creatures used to be humans and that they are the direct result of the second Chernobyl incident. From the remains of their clothing we can deduce that izloms originate from prisoner population that was stationed in the Exclusion Zone and sentenced to forced labor. Since all Izloms suffer almost the same the deformation of the body, it is supposed that when the exposure took place all subjects were in the same body position - either because they were being transported at the time or because someone forced them. All specimens encountered so far were male and sterile. Hence it can be safely assumed that the izlom population is unable to reproduce, and their number in the Zone will be steadily getting lower." ITEM.width = 1 ITEM.height = 1 ITEM.price = 2300 ITEM.pricepertier = 550 ITEM.baseweight = 1.500 ITEM.varweight = 0.250
-- (c) 2016 Flexiant Ltd -- Released under the Apache 2.0 Licence - see LICENCE for details function scheduled_create_snapshot_trigger(p) if (p == nil) then return { ref = "scheduled_create_snapshot", name = "Scheduled Create Snapshot Tiggger", description = "This will create a snapshot for user if he has right customer key enabled", priority = 0, triggerType = "SCHEDULED", schedule = {frequency = {HOUR = 1}}, api = "TRIGGER", version = 1, } end print("========= SCHEDULED TRIGGER CREATE SNAPSHOT =========") local serverList = getServersWithKey('AUTO_SNAPSHOTS', 'MAXSNAPSHOTS') for serverUUID, server in pairs(serverList) do local newSnapshotDate = p.timeStamp - server.snapshotTime * 60 * 60 * 1000 local userToken = getUserToken(server.customerUUID) userAPI:setSessionUser(userToken) createNewSnapshot(server.customerUUID, serverUUID, "SERVER", server.maxSnapshots) if (tonumber(server.maxSnapshots) > 0) then removeOldSnapshots(serverUUID, server.maxSnapshots); end end local diskList = getDisksWithKey('AUTO_SNAPSHOTS', 'MAXSNAPSHOTS') for diskUUID, disk in pairs(diskList) do local newSnapshotDate = p.timeStamp - disk.snapshotTime * 60 * 60 * 1000 local userToken = getUserToken(disk.customerUUID) userAPI:setSessionUser(userToken) createNewSnapshot(disk.customerUUID, diskUUID, "DISK", disk.maxSnapshots) if (tonumber(disk.maxSnapshots) > 0) then removeOldSnapshots(diskUUID, disk.maxSnapshots); end end print("======== SCHEDULED TRIGGER CREATE SNAPSHOT COMPLETE=========") return {exitState = "SUCCESS"} end function removeOldSnapshots(resourceUUID, maxSnapshots) local searchFilter = new("SearchFilter") local filterCondition1 = new("FilterCondition") filterCondition1:setField('parentuuid') filterCondition1:setValue({resourceUUID}) filterCondition1:setCondition(new("Condition", "IS_EQUAL_TO")) searchFilter:addCondition(filterCondition1) local snapshots = adminAPI:listResources(searchFilter, nil, new("ResourceType", "SNAPSHOT")) if (tonumber(snapshots:getList():size()) > tonumber(maxSnapshots)) then local snapshotList = {} local dateHelper = new("FDLDateHelper") for i = 0, snapshots:getList():size() - 1, 1 do snapshotList[snapshots:getList():get(i):getResourceUUID()] = dateHelper:getTimestamp(snapshots:getList():get(i):getResourceCreateDate()) local oldSnapshots = filterOldSnapshots(snapshotList, maxSnapshots); for oldSnapshotUUID, oldSnapshotCreateDate in pairs(oldSnapshots) do print("======= oldSnapshotUUID to be deleted=========") print(oldSnapshotUUID) userAPI:deleteResource(oldSnapshotUUID, true, nil) end end end end function getUserToken(customerUUID) local searchFilter = new("SearchFilter") local filterCondition1 = new("FilterCondition") filterCondition1:setField('resourceuuid') filterCondition1:setValue({customerUUID}) filterCondition1:setCondition(new("Condition", "IS_EQUAL_TO")) searchFilter:addCondition(filterCondition1) local customer = adminAPI:listResources(searchFilter, nil, new("ResourceType", "CUSTOMER")) local userEmail = customer:getList():get(0):getUsers():get(0):getEmail() return userEmail .. "/" .. customer:getList():get(0):getResourceUUID() end function filterOldSnapshots(snapshotTable, maxSnapshots) local list = {} for name, value in pairs(snapshotTable) do list[#list + 1] = name end function byval(a, b) return snapshotTable[a] > snapshotTable[b] end table.sort(list, byval) local response = {} for k = maxSnapshots + 1, #list do response[list[k]] = snapshotTable[list[k]] end return response end function createNewSnapshot(customerUUID, resourceUUID, type, maxSnapshots) print('===== Max Snapshot value taken from key =====') print(maxSnapshots) if (tostring(maxSnapshots) == '0') then print('===== Max snapshot is 0, No snapshots taken =====') end local snapshotSkeleton = new("Snapshot") snapshotSkeleton:setCustomerUUID(customerUUID) snapshotSkeleton:setParentUUID(resourceUUID) snapshotSkeleton:setType(new("SnapshotType", type)) local snapshot = userAPI:createSnapshot(snapshotSkeleton, nil) local jobQueue = userAPI:waitForJob(snapshot:getResourceUUID(), true) print("======== Waiting on create JOB to complete ========") print(jobQueue:getResourceUUID()) end function getDisksWithKey(resourceKeyName, resourceKeyName1) local searchFilter = new("SearchFilter") local filterCondition1 = new("FilterCondition") filterCondition1:setField('status') filterCondition1:setValue({"ATTACHED_TO_SERVER"}) filterCondition1:setCondition(new("Condition", "IS_EQUAL_TO")) local filterCondition2 = new("FilterCondition") filterCondition2:setField('resourcekey.name[1]') filterCondition2:setValue({resourceKeyName}) filterCondition2:setCondition(new("Condition", "STARTS_WITH")) local filterCondition3 = new("FilterCondition") filterCondition3:setField('resourcekey.name[2]') filterCondition3:setValue({resourceKeyName1}) filterCondition3:setCondition(new("Condition", "STARTS_WITH")) searchFilter:addCondition(filterCondition1) searchFilter:addCondition(filterCondition2) searchFilter:addCondition(filterCondition3) local disks = adminAPI:listResources(searchFilter, nil, new("ResourceType", "DISK")) local responseData = {} for i = 0, disks:getList():size() - 1, 1 do responseData[disks:getList():get(i):getResourceUUID()] = {snapshotTime = getResourceKeyValue(resourceKeyName, disks:getList():get(i):getResourceKey()), customerUUID = disks:getList():get(i):getCustomerUUID(), maxSnapshots = getResourceKeyValue('MAXSNAPSHOTS', disks:getList():get(i):getResourceKey())} end return responseData end function getServersWithKey(resourceKeyName, resourceKeyName1) local searchFilter = new("SearchFilter") local filterCondition1 = new("FilterCondition") filterCondition1:setField('resourcekey.name[1]') filterCondition1:setValue({resourceKeyName}) filterCondition1:setCondition(new("Condition", "STARTS_WITH")) local filterCondition2 = new("FilterCondition") filterCondition2:setField('resourcekey.name[2]') filterCondition2:setValue({resourceKeyName1}) filterCondition2:setCondition(new("Condition", "STARTS_WITH")) searchFilter:addCondition(filterCondition1) searchFilter:addCondition(filterCondition2) local servers = adminAPI:listResources(searchFilter, nil, new("ResourceType", "SERVER")) local responseData = {} for i = 0, servers:getList():size() - 1, 1 do responseData[servers:getList():get(i):getResourceUUID()] = {snapshotTime = getResourceKeyValue(resourceKeyName, servers:getList():get(i):getResourceKey()), customerUUID = servers:getList():get(i):getCustomerUUID(), maxSnapshots = getResourceKeyValue('MAXSNAPSHOTS', servers:getList():get(i):getResourceKey())} end return responseData end function getResourceKeyValue(resourceKeyName, resouceKeyList) for j = 0, resouceKeyList:size() - 1, 1 do if (resouceKeyList:get(j):getName() == resourceKeyName) then return resouceKeyList:get(j):getValue() end end return 0; end function spairs(t, order) -- collect the keys local keys = {} for k in pairs(t) do keys[#keys + 1] = k end -- if order function given, sort by it by passing the table and keys a, b, -- otherwise just sort the keys if order then table.sort(keys, function (a, b) return order(t, a, b) end) else table.sort(keys) end -- return the iterator function local i = 0 return function () i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end end function register() return {"scheduled_create_snapshot_trigger"} end
-- Cause mapcreators are lazy and don't follow the right varables ... local function SortVectors(...) local ar = {...} table.sort( ar, function(a,b) if a.z > b.z then return true end return false end ) local t = ar[2] ar[2] = ar[3] ar[3] = t return ar end --[[ Test thingy. Left for me to easy debug. local function TestWindow( ent , time ) local pos = ent:GetNWVector("SF_POS10") local pos2 = ent:GetNWVector("SF_POS11") local pos3 = ent:GetNWVector("SF_POS01") local pos4 = ent:GetNWVector("SF_POS00") local arr = SortVectors(pos,pos2,pos3,pos4) for k,v in pairs(arr) do local lifetime = time or 15 debugoverlay.Sphere(v,5,lifetime,Color( 255, 255, 255 ),true) debugoverlay.Text(v,k,lifetime,false) end return --arr end]] if SERVER then -- Give each window the required varables hook.Add("EntityKeyValue","StormFox - SetData",function(ent,key,val) -- GetKeyValues() on client plz if ent:GetClass() ~= "func_breakable_surf" then return end if key == "upperleft" then -- ↖ 00 local t = string.Explode(" ",val) ent:SetNWVector("SF_POS00",Vector(t[1],t[2],t[3])) elseif key == "upperright" then -- ↗ 01 local t = string.Explode(" ",val) ent:SetNWVector("SF_POS01",Vector(t[1],t[2],t[3])) elseif key == "lowerleft" then -- ↙ 10 local t = string.Explode(" ",val) ent:SetNWVector("SF_POS10",Vector(t[1],t[2],t[3])) elseif key == "lowerright" then -- ↘ 11 local t = string.Explode(" ",val) ent:SetNWVector("SF_POS11",Vector(t[1],t[2],t[3])) end end) return end local function CheckSettings() local con = GetConVar("sf_enable_windoweffect") if not con then return false end if not con:GetBool() then return false end if not StormFox.EFEnabled() then return false end return true end -- Only need to calculate some things once local s = 10 -- Texture size local function HandleVarablesWindow( ent ) -- Get the window varables local pos = ent:GetNWVector("SF_POS10") local pos2 = ent:GetNWVector("SF_POS11") local pos3 = ent:GetNWVector("SF_POS01") local pos4 = ent:GetNWVector("SF_POS00") -- Is it valid? if type(pos)~= "Vector" or type(pos2)~= "Vector" or type(pos3)~= "Vector" or type(pos4)~= "Vector" then return end -- We can't trust mapcreators .. never do. Sort the varables by height. local arr = SortVectors(pos,pos2,pos3,pos4) pos = arr[1] pos2 = arr[4] pos3 = arr[2] pos4 = arr[3] -- Create some useful varables local size = pos3 - pos local center = pos + size / 2 local ang = (pos2 - pos):Angle() local w = pos:Distance(pos4) local h = pos:Distance(pos2) -- Create the meshes ( we update the uvs later) local c = (CurTime() / 10) % 1 local verts = { { pos = pos4, u = w / s, v = -c }, -- Vertex 1 TOP { pos = pos3, u = w / s, v = h / s-c }, -- Vertex 2 BOTTOM { pos = pos2, u = 0, v = h / s -c}, -- Vertex 3 BOTTOM { pos = pos, u = 0, v = -c }, -- Vertex 4 TOP } local verts2 = { { pos = pos, u = 0, v = -c }, -- Vertex 1 { pos = pos2, u = 0, v = h / s -c }, -- Vertex 2 { pos = pos3, u = w / s, v = h / s-c}, -- Vertex 3 { pos = pos4, u = w / s, v = -c }, -- Vertex 4 } -- Save the varables on the window ent.sf_vars = {} ent.sf_vars.center = center ent.sf_vars.normal = -ang:Right() ent.sf_vars.w = w ent.sf_vars.h = h ent.sf_vars.verts = verts ent.sf_vars.verts2 = verts2 ent.sf_vars.entity = ent end -- Check if the window is in the wind local convar = GetConVar("sf_enable_windoweffect_enable_tr") local function IsWindowInRain( data, ent ) if (ent.sf_inwindowcost or 0) > CurTime() then return ent.sf_inwindow or false end ent.sf_inwindowcost = CurTime() + 4 if not convar:GetBool() then ent.sf_inwindow = true return true end --verts then ent.sf_inwindow = StormFox.IsVectorInWind( data.center , ent ) return ent.sf_inwindow end -- Draw rain on windows local t = {} -- List of windows to render stuff on local s_timer = 0 hook.Add("Think","StormFox - RainWindowEffectThink",function() if s_timer > CurTime() then return end -- Call this twice pr second s_timer = CurTime() + 0.5 -- Remove all render windows table.Empty(t) -- Check settings if not CheckSettings() then return end -- Only trigger this in semi-heavy rain if StormFox.GetData("Gauge",10) <= 5 then return end local p = LocalPlayer():GetShootPos() for _,ent in pairs(ents.FindByClass("func_breakable_surf")) do -- Check health if ent:Health() <= 0 then continue end -- Check if there are any useful varables if not ent.sf_vars then HandleVarablesWindow(ent) end if not ent.sf_vars then return end -- No valid windowdata -- Check the distance local dis = p:DistToSqr(ent.sf_vars.center) ent.sf_vars.dis = dis if dis > 90000 then continue end -- Check if its in the wind if not IsWindowInRain(ent.sf_vars,ent) then return end table.insert(t,ent) -- Add the window to the list end end) -- Check if all varables is valid. This is to protect the mesh from causing errors. local function CheckValid(data) -- Mesh errors will ruin the whole game. Better get it right. if not data.dis then return false end if not data.entity then return false end if not data.center then return false end if not data.verts then return false end if not data.verts2 then return false end if not data.h then return false end if not data.w then return false end return true end -- Render the effect local clamp = math.Clamp local b = false local mat = Material("stormfox/effects/rainscreen") hook.Add("PreDrawTranslucentRenderables","StormFox - RainWindowEffect",function() if #t <= 0 then return end render.SetColorMaterial() render.SetMaterial(mat) for _,ent in pairs(t) do if not IsValid(ent) then continue end if ent:Health() <= 0 then continue end if not CheckValid(ent.sf_vars) then continue end local a = clamp(455 - ent.sf_vars.dis / 152,0,255) -- Alpha. doesn't really work well with this type of material. if a <= 0 then continue end -- Mesh protector 2#. Stops the game from going crazy if b then return end b = true -- Update texture UV local c = (CurTime() / 20) % 1 -- Used to calculate UV for windows ent.sf_vars.verts[1].v = -c ent.sf_vars.verts[2].v = ent.sf_vars.h / s - c ent.sf_vars.verts[3].v = ent.sf_vars.h / s - c ent.sf_vars.verts[4].v = -c ent.sf_vars.verts2[1].v = -c ent.sf_vars.verts2[2].v = ent.sf_vars.h / s - c ent.sf_vars.verts2[3].v = ent.sf_vars.h / s - c ent.sf_vars.verts2[4].v = -c -- Here goes nothing mesh.Begin( MATERIAL_QUADS, 1 ) -- Begin writing to the dynamic mesh for i,verts in pairs(ent.sf_vars.verts) do mesh.Position( verts.pos ) -- Set the position mesh.Color(255,255,255,a) mesh.TexCoord( 0, verts.u, verts.v ) -- Set the texture UV coordinates mesh.AdvanceVertex() -- Write the vertex end mesh.End() mesh.Begin( MATERIAL_QUADS, 1 ) -- Begin writing to the dynamic mesh for i,verts in pairs(ent.sf_vars.verts2) do mesh.Position( verts.pos ) -- Set the position mesh.Color(255,255,255,a) mesh.TexCoord( 0, verts.u, verts.v ) -- Set the texture UV coordinates mesh.AdvanceVertex() -- Write the vertex end mesh.End() b = false end end)
local AddRecipe = AddRecipe GLOBAL.setfenv(1, GLOBAL) -- 月镐和月锤 -- AddRecipe("moonglasspickaxe", {Ingredient("twigs", 2), Ingredient("moonglass", 3)}, RECIPETABS.CELESTIAL, TECH.CELESTIAL_THREE, nil, nil, true) AddRecipe("moonglasshammer", {Ingredient("twigs", 3), Ingredient("cutgrass", 6), Ingredient("moonglass", 3)}, RECIPETABS.CELESTIAL, TECH.CELESTIAL_THREE, nil, nil, true) AllRecipes["moonglasspickaxe"].sortkey = AllRecipes["moonglassaxe"].sortkey + 0.1 AllRecipes["moonglasshammer"].sortkey = AllRecipes["moonglasspickaxe"].sortkey + 0.1
-------------------------------------------------------- local Keys = { ["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57, ["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177, ["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18, ["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182, ["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81, ["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70, ["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178, ["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173, ["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118 } ESX = nil Citizen.CreateThread(function() while ESX == nil do TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) Citizen.Wait(0) end while ESX.GetPlayerData().job == nil do Citizen.Wait(10) end PlayerData = ESX.GetPlayerData() end) RegisterNetEvent('esx:playerLoaded') AddEventHandler('esx:playerLoaded', function(xPlayer) PlayerData = xPlayer end) function DrawText3D(x, y, z, text) local onScreen,_x,_y=World3dToScreen2d(x, y, z) local px,py,pz=table.unpack(GetGameplayCamCoords()) SetTextScale(0.37, 0.37) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) local factor = (string.len(text)) / 370 DrawRect(_x,_y+0.0125, 0.015+ factor, 0.03, 33, 33, 33, 133) end local Anulowano = false local ZrespTuPojazd = {x = 221.45880126953, y = -2967.1662597656, z = 5.8969} local rampaCoord = {x = 138.2465057373, y = -3089.1518554688, z = 5.89631} local wezCar = {x = 145.67060852051, y = -3108.6743164063, z = 5.896} local zlecenieDist = {x = 152.32009887695, y = -3101.5874023438, z = 5.8963} local zrespione = false local silnikOn = false local rodzajPojazdu = nil local naklejkaAuto = 0 local kartonKoord1 = {x = 161.97207641602, y = -3142.4104003906, z = 5.959} local kartonKoord2 = {x = 161.18479919434, y = -3041.7497558594, z = 5.974014} local kartonKoord3 = {x = 166.7626953125, y = -3258.3393554688, z = 5.86072} local kartonKoord4 = {x = 116.09323120117, y = -3164.1032714844, z = 6.0136} local kartonKoord5 = {x = 117.36480712891, y = -2989.3310546875, z = 6.020} local czasikDostaw = 0 local dostawaTimer = false local PrzejetyHangar = 0 local premia1 = 5 local premia2 = 20 local premia3 = 10 -----------------------garaz2 local ZrespTuPojazd2 = {x = 275.67260742188, y = -3166.150390625, z = 5.7902} local rampaCoord2 = {x = 158.15670776367, y = -3196.2829589844, z = 6.021} local wezCar2 = {x = 146.82814025879, y = -3210.5979003906, z = 5.8575} local zlecenieDist2 = {x = 152.90745544434, y = -3211.7609863281, z = 5.901} local pilot function ZrespPaczuszke(a)czasikDostaw=0;dostawaTimer=true;if a=='deski'then paczuszka=CreateObject(GetHashKey('prop_boxpile_06a'),kartonKoord1.x,kartonKoord1.y,kartonKoord1.z-0.95,true,true,true)SetEntityAsMissionEntity(paczuszka)SetEntityDynamic(paczuszka,true)FreezeEntityPosition(paczuszka,false)SetNewWaypoint(kartonKoord1.x,kartonKoord1.y)elseif a=='lody'then paczuszka=CreateObject(GetHashKey('prop_boxpile_02b'),kartonKoord2.x,kartonKoord2.y,kartonKoord2.z-0.95,true,true,true)SetEntityAsMissionEntity(paczuszka)SetEntityDynamic(paczuszka,true)FreezeEntityPosition(paczuszka,false)SetNewWaypoint(kartonKoord2.x,kartonKoord2.y)elseif a=='leki'then paczuszka=CreateObject(GetHashKey('prop_boxpile_06a'),kartonKoord3.x,kartonKoord3.y,kartonKoord3.z-0.95,true,true,true)SetEntityAsMissionEntity(paczuszka)SetEntityDynamic(paczuszka,true)FreezeEntityPosition(paczuszka,false)SetNewWaypoint(kartonKoord3.x,kartonKoord3.y)elseif a=='napoje'then paczuszka=CreateObject(GetHashKey('prop_boxpile_09a'),kartonKoord4.x,kartonKoord4.y,kartonKoord4.z-0.95,true,true,true)SetEntityAsMissionEntity(paczuszka)SetEntityDynamic(paczuszka,true)FreezeEntityPosition(paczuszka,false)SetNewWaypoint(kartonKoord4.x,kartonKoord4.y)elseif a=='kawa'then paczuszka=CreateObject(GetHashKey('prop_boxpile_06a'),kartonKoord5.x,kartonKoord5.y,kartonKoord5.z-0.95,true,true,true)SetEntityAsMissionEntity(paczuszka)SetEntityDynamic(paczuszka,true)FreezeEntityPosition(paczuszka,false)SetNewWaypoint(kartonKoord5.x,kartonKoord5.y)end end RegisterNetEvent('tostdostawa:rampanpcdawaj')AddEventHandler('tostdostawa:rampanpcdawaj',function(a)Anulowano=false;if a=='1'then if zrespione==true then ESX.ShowNotification('~r~Zakończ poprzednie zlecenie!')return end;local b=math.random(1,5)if b==1 then naklejkaAuto=3;ESX.ShowNotification('~g~Kierowca oczekuje załadunku desek.')ZrespPaczuszke('deski')elseif b==2 then naklejkaAuto=4;ESX.ShowNotification('~g~Kierowca oczekuje załadunku ryb.')ZrespPaczuszke('lody')elseif b==3 then naklejkaAuto=6;ESX.ShowNotification('~g~Kierowca oczekuje załadunku lekarstw.')ZrespPaczuszke('leki')elseif b==4 then naklejkaAuto=2;ESX.ShowNotification('~g~Kierowca oczekuje załadunku napojów Logger Light.')ZrespPaczuszke('napoje')elseif b==5 then naklejkaAuto=1;ESX.ShowNotification('~g~Kierowca oczekuje załadunku kawy.')ZrespPaczuszke('kawa')end;RequestModel(GetHashKey('benson'))while not HasModelLoaded(GetHashKey('benson'))do Citizen.Wait(0)end;ClearAreaOfVehicles(ZrespTuPojazd.x,ZrespTuPojazd.y,ZrespTuPojazd.z,15.0,false,false,false,false,false)transport=CreateVehicle(GetHashKey('benson'),ZrespTuPojazd.x,ZrespTuPojazd.y,ZrespTuPojazd.z,-2.436,996.786,25.1887,true,true)SetEntityAsMissionEntity(transport)SetEntityHeading(transport,52.00)SetVehicleDoorsLocked(transport,2)SetVehicleDoorsLockedForAllPlayers(transport,true)SetVehicleExtra(transport,1,true)SetVehicleExtra(transport,2,true)SetVehicleExtra(transport,3,true)SetVehicleExtra(transport,4,true)SetVehicleExtra(transport,5,true)SetVehicleExtra(transport,6,true)SetVehicleExtra(transport,7,true)SetVehicleExtra(transport,naklejkaAuto,false)RequestModel("s_m_m_security_01")while not HasModelLoaded("s_m_m_security_01")do Wait(10)end;pilot=CreatePedInsideVehicle(transport,1,"s_m_m_security_01",-1,true,true)SetBlockingOfNonTemporaryEvents(pilot,true)SetEntityInvincible(pilot,true)TaskVehiclePark(pilot,transport,rampaCoord.x,rampaCoord.y,rampaCoord.z,266.0,1,1.0,false)SetDriveTaskDrivingStyle(pilot,263100)SetPedKeepTask(pilot,true)ESX.ShowNotification('~y~Kierowca jest w drodze.')zrespione=true;silnikOn=true;Citizen.Wait(900)while silnikOn do Citizen.Wait(1000)local c=GetIsVehicleEngineRunning(transport)if c==1 then Citizen.Wait(200)else silnikOn=false end end;ESX.ShowNotification('~r~Kierowca się zatrzymał i otworzył bagażnik')SetVehicleDoorOpen(transport,5,false,false)backOpened=true;local d,e,f=table.unpack(GetOffsetFromEntityInWorldCoords(transport,0.0,-6.0,-1.0))while backOpened do Citizen.Wait(2)DrawMarker(1,d,e,f,0,0,0,0,0,0,1.7,1.7,1.7,135,31,35,150,1,0,0,0)local g=GetEntityCoords(paczuszka)local h=Vdist(d,e,f,g.x,g.y,g.z)if h<=2.0 then SetVehicleDoorShut(transport,5,false)DeleteEntity(paczuszka)backOpened=false end end;if Anulowano==true then return end;ESX.ShowNotification('~r~Paczka załadowana, kierowca się zawija.')ESX.ShowNotification('~w~Załadowałeś paczkę w ~b~'..czasikDostaw..' sekund.')if czasikDostaw<41 then ESX.ShowNotification('~b~Premia ~g~'..premia1 ..'$~b~ za szybką dostawę')TriggerServerEvent("tostdostawa:wykonanieMisji",premia1)Citizen.Wait(200)elseif czasikDostaw>=41 and czasikDostaw<=55 then ESX.ShowNotification('~b~Premia ~g~'..premia2 ..'$~b~ za szybką dostawę')TriggerServerEvent("tostdostawa:wykonanieMisji",premia2)Citizen.Wait(200)elseif czasikDostaw>=56 and czasikDostaw<=65 then ESX.ShowNotification('~b~Premia ~g~'..premia3 ..'$~b~ za szybką dostawę')TriggerServerEvent("tostdostawa:wykonanieMisji",premia3)Citizen.Wait(200)elseif czasikDostaw>65 then ESX.ShowNotification('~w~Brak premi za szybką dostawe')end;czasikDostaw=0;dostawaTimer=false;TriggerServerEvent("tostdostawa:wykonanieMisji",'nie')TaskVehicleDriveWander(pilot,transport,50.0,263100)Citizen.Wait(15000)DeleteEntity(transport)DeleteEntity(pilot)zrespione=0;ESX.ShowNotification('~r~Możesz przyjąć kolejne zlecenie')elseif a=='2'then if zrespione==true then ESX.ShowNotification('~r~Zakończ poprzednie zlecenie!')return end;local b=math.random(1,5)if b==1 then naklejkaAuto=3;ESX.ShowNotification('~g~Kierowca oczekuje załadunku desek.')ZrespPaczuszke('deski')elseif b==2 then naklejkaAuto=4;ESX.ShowNotification('~g~Kierowca oczekuje załadunku ryb.')ZrespPaczuszke('lody')elseif b==3 then naklejkaAuto=6;ESX.ShowNotification('~g~Kierowca oczekuje załadunku lekarstw.')ZrespPaczuszke('leki')elseif b==4 then naklejkaAuto=2;ESX.ShowNotification('~g~Kierowca oczekuje załadunku napojów Logger Light.')ZrespPaczuszke('napoje')elseif b==5 then naklejkaAuto=1;ESX.ShowNotification('~g~Kierowca oczekuje załadunku kawy.')ZrespPaczuszke('kawa')end;RequestModel(GetHashKey('benson'))while not HasModelLoaded(GetHashKey('benson'))do Citizen.Wait(0)end;ClearAreaOfVehicles(ZrespTuPojazd.x,ZrespTuPojazd.y,ZrespTuPojazd.z,15.0,false,false,false,false,false)transport=CreateVehicle(GetHashKey('benson'),ZrespTuPojazd2.x,ZrespTuPojazd2.y,ZrespTuPojazd2.z,-2.436,996.786,25.1887,true,true)SetEntityAsMissionEntity(transport)SetEntityHeading(transport,52.00)SetVehicleDoorsLocked(transport,2)SetVehicleDoorsLockedForAllPlayers(transport,true)SetVehicleExtra(transport,1,true)SetVehicleExtra(transport,2,true)SetVehicleExtra(transport,3,true)SetVehicleExtra(transport,4,true)SetVehicleExtra(transport,5,true)SetVehicleExtra(transport,6,true)SetVehicleExtra(transport,7,true)SetVehicleExtra(transport,naklejkaAuto,false)RequestModel("s_m_m_security_01")while not HasModelLoaded("s_m_m_security_01")do Wait(10)end;pilot=CreatePedInsideVehicle(transport,1,"s_m_m_security_01",-1,true,true)SetBlockingOfNonTemporaryEvents(pilot,true)SetEntityInvincible(pilot,true)TaskVehiclePark(pilot,transport,rampaCoord2.x,rampaCoord2.y,rampaCoord2.z,266.0,1,1.0,false)SetDriveTaskDrivingStyle(pilot,263100)SetPedKeepTask(pilot,true)ESX.ShowNotification('~y~Kierowca jest w drodze.')zrespione=true;silnikOn=true;Citizen.Wait(900)while silnikOn do Citizen.Wait(1000)local c=GetIsVehicleEngineRunning(transport)if c==1 then Citizen.Wait(200)else silnikOn=false end end;ESX.ShowNotification('~r~Kierowca się zatrzymał i otworzył bagażnik')SetVehicleDoorOpen(transport,5,false,false)backOpened=true;local d,e,f=table.unpack(GetOffsetFromEntityInWorldCoords(transport,0.0,-6.0,-1.0))while backOpened do Citizen.Wait(2)DrawMarker(1,d,e,f,0,0,0,0,0,0,1.7,1.7,1.7,135,31,35,150,1,0,0,0)local g=GetEntityCoords(paczuszka)local h=Vdist(d,e,f,g.x,g.y,g.z)if h<=2.0 then SetVehicleDoorShut(transport,5,false)DeleteEntity(paczuszka)backOpened=false end end;if Anulowano==true then return end;ESX.ShowNotification('~r~Paczka załadowana, kierowca się zawija.')ESX.ShowNotification('~w~Załadowałeś paczkę w ~b~'..czasikDostaw..' sekund.')if czasikDostaw<61 then ESX.ShowNotification('~b~Premia ~g~'..premia1 ..'$~b~ za szybką dostawę')TriggerServerEvent("tostdostawa:wykonanieMisji",premia1)Citizen.Wait(200)elseif czasikDostaw>=61 and czasikDostaw<=75 then ESX.ShowNotification('~b~Premia ~g~'..premia2 ..'$~b~ za szybką dostawę')TriggerServerEvent("tostdostawa:wykonanieMisji",premia2)Citizen.Wait(200)elseif czasikDostaw>=76 and czasikDostaw<=85 then ESX.ShowNotification('~b~Premia ~g~'..premia3 ..'$~b~ za szybką dostawę')TriggerServerEvent("tostdostawa:wykonanieMisji",premia3)Citizen.Wait(200)elseif czasikDostaw>85 then ESX.ShowNotification('~w~Brak premi za szybką dostawe')end;czasikDostaw=0;dostawaTimer=false;TriggerServerEvent("tostdostawa:wykonanieMisji",'nie')TaskVehicleDriveWander(pilot,transport,50.0,263100)Citizen.Wait(15000)DeleteEntity(transport)DeleteEntity(pilot)zrespione=0;ESX.ShowNotification('~r~Możesz przyjąć kolejne zlecenie')end end) Citizen.CreateThread(function() while true do Citizen.Wait(1000) if dostawaTimer == true then czasikDostaw = czasikDostaw +1 if czasikDostaw > 140 then Anulowano = true zrespione = 0 czasikDostaw = 0 dostawaTimer = false backOpened = false silnikOn = false DeleteEntity(transport) DeleteEntity(pilot) DeleteEntity(paczuszka) ESX.ShowNotification('~r~Zlecenie anulowano z powodu zbyt długiego załadunku') end else Citizen.Wait(2000) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(4) if DoesEntityExist(paczuszka) then local paczkCoord = GetEntityCoords(paczuszka) DrawMarker(0, paczkCoord.x, paczkCoord.y, paczkCoord.z+2.1, 0, 0, 0, 0, 0, 0, 1.0, 1.0, 1.0, 135, 31, 35, 150, 1, 0, 0, 0) else Citizen.Wait(2500) end end end) RegisterNetEvent('tostdostawa:maszHangar') AddEventHandler('tostdostawa:maszHangar', function() PrzejetyHangar = 1 end) Citizen.CreateThread(function() while true do Citizen.Wait(3) local plyCoords = GetEntityCoords(GetPlayerPed(-1), false) local distCar = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, wezCar.x, wezCar.y, wezCar.z) local zlecDist = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, zlecenieDist.x, zlecenieDist.y, zlecenieDist.z) if distCar <= 25.0 or zlecDist <= 25.0 then DrawMarker(25, wezCar.x, wezCar.y, wezCar.z-0.90, 0, 0, 0, 0, 0, 0, 1.301, 1.3001, 1.3001, 0, 205, 250, 200, 0, 0, 0, 0) DrawMarker(25, zlecenieDist.x, zlecenieDist.y, zlecenieDist.z-0.90, 0, 0, 0, 0, 0, 0, 1.301, 1.3001, 1.3001, 0, 205, 250, 200, 0, 0, 0, 0) else Citizen.Wait(1500) end if distCar <= 1.0 then DrawText3D(wezCar.x, wezCar.y, wezCar.z, "~g~[E]~b~ Aby zabrać wózek widłowy") if IsControlJustPressed(0, Keys['E']) then PozyczPojazd('1') end end if zlecDist <= 1.0 then DrawText3D(zlecenieDist.x, zlecenieDist.y, zlecenieDist.z, "~g~[E]~b~ Wez zlecenie") DrawText3D(zlecenieDist.x, zlecenieDist.y, zlecenieDist.z-0.13, "~g~[G]~b~ Przejmij hangar") if IsControlJustPressed(0, Keys['E']) then if PrzejetyHangar == 1 then TriggerEvent('tostdostawa:rampanpcdawaj','1') TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_CLIPBOARD", 0, false) Citizen.Wait(2000) ClearPedTasks(GetPlayerPed(-1)) ESX.ShowNotification('~y~Paczka do dostarczenia zostala zaznaczona na GPS, uzyj wózka widłowego.') else ESX.ShowNotification('~y~Musisz przejąć hangar') end elseif IsControlJustPressed(0, Keys['G']) then if PrzejetyHangar == 1 then ESX.ShowNotification('~y~Masz już hangar') else TriggerServerEvent("tostdostawa:przejmijHangar", '1') Citizen.Wait(500) end end end end end) ----garaz 2 Citizen.CreateThread(function() while true do Citizen.Wait(3) local plyCoords = GetEntityCoords(GetPlayerPed(-1), false) local distCar2 = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, wezCar2.x, wezCar2.y, wezCar2.z) local zlecDist2 = Vdist(plyCoords.x, plyCoords.y, plyCoords.z, zlecenieDist2.x, zlecenieDist2.y, zlecenieDist2.z) if distCar2 <= 25.0 or zlecDist2 <= 25.0 then DrawMarker(25, wezCar2.x, wezCar2.y, wezCar2.z-0.90, 0, 0, 0, 0, 0, 0, 1.301, 1.3001, 1.3001, 0, 205, 250, 200, 0, 0, 0, 0) DrawMarker(25, zlecenieDist2.x, zlecenieDist2.y, zlecenieDist2.z-0.90, 0, 0, 0, 0, 0, 0, 1.301, 1.3001, 1.3001, 0, 205, 250, 200, 0, 0, 0, 0) else Citizen.Wait(1500) end if distCar2 <= 1.0 then DrawText3D(wezCar2.x, wezCar2.y, wezCar2.z, "~g~[E]~b~ Aby zabrać wózek widłowy") if IsControlJustPressed(0, Keys['E']) then PozyczPojazd('2') end end if zlecDist2 <= 1.0 then DrawText3D(zlecenieDist2.x, zlecenieDist2.y, zlecenieDist2.z, "~g~[E]~b~ Wez zlecenie") DrawText3D(zlecenieDist2.x, zlecenieDist2.y, zlecenieDist2.z-0.13, "~g~[G]~b~ Przejmij hangar") if IsControlJustPressed(0, Keys['E']) then if PrzejetyHangar == 1 then TriggerEvent('tostdostawa:rampanpcdawaj','2') TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_CLIPBOARD", 0, false) Citizen.Wait(2000) ClearPedTasks(GetPlayerPed(-1)) ESX.ShowNotification('~y~Paczka do dostarczenia zostala zaznaczona na GPS, uzyj wózka widłowego.') else ESX.ShowNotification('~y~Musisz przejąć hangar') end elseif IsControlJustPressed(0, Keys['G']) then if PrzejetyHangar == 1 then ESX.ShowNotification('~y~Masz już hangar') else TriggerServerEvent("tostdostawa:przejmijHangar", '2') Citizen.Wait(500) end end end end end) local PojazdWyjety = 0 local wozek function PozyczPojazd(a)if a=='1'then if PojazdWyjety==0 then RequestModel(GetHashKey('forklift'))while not HasModelLoaded(GetHashKey('forklift'))do Citizen.Wait(0)end;ClearAreaOfVehicles(wezCar.x,wezCar.y,wezCar.z,15.0,false,false,false,false,false)wozek=CreateVehicle(GetHashKey('forklift'),wezCar.x,wezCar.y,wezCar.z,-2.436,996.786,25.1887,true,true)SetEntityHeading(wozek,52.00)TaskWarpPedIntoVehicle(GetPlayerPed(-1),wozek,-1)SetVehicleColours(wozek,111,111)PojazdWyjety=1 else PojazdWyjety=0;DeleteEntity(wozek)ESX.ShowNotification('~y~Twój poprzedni pojazd został skasowany, możesz pobrać nowy')end elseif a=='2'then if PojazdWyjety==0 then RequestModel(GetHashKey('forklift'))while not HasModelLoaded(GetHashKey('forklift'))do Citizen.Wait(0)end;ClearAreaOfVehicles(wezCar2.x,wezCar2.y,wezCar2.z,15.0,false,false,false,false,false)wozek=CreateVehicle(GetHashKey('forklift'),wezCar2.x,wezCar2.y,wezCar2.z,-2.436,996.786,25.1887,true,true)SetEntityHeading(wozek,52.00)TaskWarpPedIntoVehicle(GetPlayerPed(-1),wozek,-1)SetVehicleColours(wozek,111,111)PojazdWyjety=1 else PojazdWyjety=0;DeleteEntity(wozek)ESX.ShowNotification('~y~Twój poprzedni pojazd został skasowany, możesz pobrać nowy')end end end ---- Citizen.CreateThread(function()while true do Citizen.Wait(1500)local a=GetEntityCoords(GetPlayerPed(-1),false)local b=Vdist(a.x,a.y,a.z,zlecenieDist2.x,zlecenieDist2.y,zlecenieDist2.z)local c=Vdist(a.x,a.y,a.z,zlecenieDist.x,zlecenieDist.y,zlecenieDist.z)if PrzejetyHangar==1 then if b>205.0 then ESX.ShowNotification('~y~Zbyt daleko oddaliles sie od magazynu dlatego straciles wlasciciela.')TriggerServerEvent("tostdostawa:OdszedlDalekoo")Citizen.Wait(1500)else Citizen.Wait(3500)end;if c>205.0 then ESX.ShowNotification('~y~Zbyt daleko oddaliles sie od magazynu dlatego straciles wlasciciela.')TriggerServerEvent("tostdostawa:OdszedlDalekoo")Citizen.Wait(1500)else Citizen.Wait(3500)end end end end)
slot0 = class("AnniversaryMediator", import("..base.ContextMediator")) slot0.ON_SUBMIT_TASK = "AnniversaryMediator:ON_SUBMIT_TASK" slot0.TO_TASK = "AnniversaryMediator:TO_TASK" slot0.register = function (slot0) slot0:bind(slot0.TO_TASK, function (slot0, slot1) slot0:sendNotification(GAME.TASK_GO, { taskVO = slot1 }) end) slot0.bind(slot0, slot0.ON_SUBMIT_TASK, function (slot0, slot1) slot0:sendNotification(GAME.SUBMIT_TASK, slot1) end) slot0.viewComponent:setActivity(slot2) slot0:acceptTask(slot2) slot0.viewComponent:setTaskList(slot0:getTaskByIds()) end slot0.acceptTask = function (slot0, slot1) slot2 = getProxy(TaskProxy) slot4 = pg.TimeMgr.GetInstance() slot5 = math.clamp(slot4:DiffDay(slot1.data1, slot4:GetServerTime()) + 1, 1, #slot1:getConfig("config_data")) if slot1.data3 == 0 or (slot6 < slot5 and _.all(_.flatten({ slot3[slot6] }), function (slot0) return slot0:getFinishTaskById(slot0) ~= nil end)) then slot0.sendNotification(slot0, GAME.ACTIVITY_OPERATION, { cmd = 1, activity_id = slot1.id }) end end slot0.getTaskByIds = function (slot0) slot1 = {} for slot7, slot8 in pairs(slot3) do slot1[slot8.id] = slot8 end for slot8, slot9 in pairs(slot4) do slot1[slot9.id] = slot9 end return slot1 end slot0.listNotificationInterests = function (slot0) return { TaskProxy.TASK_ADDED, TaskProxy.TASK_UPDATED, TaskProxy.TASK_REMOVED, TaskProxy.TASK_FINISH, GAME.SUBMIT_TASK_DONE, ActivityProxy.ACTIVITY_UPDATED } end slot0.handleNotification = function (slot0, slot1) slot3 = slot1:getBody() if slot1:getName() == TaskProxy.TASK_ADDED or slot2 == TaskProxy.TASK_UPDATED or slot2 == TaskProxy.TASK_REMOVED or slot2 == TaskProxy.TASK_FINISH then slot0.viewComponent:setTaskList(slot0:getTaskByIds()) elseif slot2 == GAME.SUBMIT_TASK_DONE then slot5 = getProxy(ActivityProxy).getActivityById(slot4, ActivityConst.ANNIVERSARY_TASK_LIST_ID) if slot0.viewComponent.dateIndex and slot0.viewComponent.dateIndex == slot5.data3 then slot0.viewComponent:updateTaskGroupDesc(slot5.data3) end slot0.viewComponent:updateBottomTaskGroup(slot5.data3) slot0.viewComponent:emit(BaseUI.ON_ACHIEVE, slot3) slot0:acceptTask(slot5) elseif slot2 == ActivityProxy.ACTIVITY_UPDATED and slot3.id == ActivityConst.ANNIVERSARY_TASK_LIST_ID then slot0.viewComponent:setActivity(slot3) slot0.viewComponent:updateTaskGroups() slot0.viewComponent:moveToTaskGroup(slot0.viewComponent.date, nil, true) end end return slot0
local id = x if check() then local n = tonumber(string.sub(x, 6)) id = player.episode[n].script or id end
local module = {} -- n/a <: sets little endian -- n/a >: sets big endian -- n/a =: sets native endian -- n/a ![n]: sets maximum alignment to n (default is native alignment) -- n/a s[n]: a string preceded by its length coded as an unsigned integer with n bytes (default is a size_t) -- n/a ' ': (empty space) ignored -- c b: a signed byte (char) -- C B: an unsigned byte (char) -- s h: a signed short (native size) -- S H: an unsigned short (native size) -- l l: a signed long (native size) -- L L: an unsigned long (native size) -- q j: a lua_Integer -- Q J: a lua_Unsigned -- Q T: a size_t (native size) -- i i[n]: a signed int with n bytes (default is native size) -- I I[n]: an unsigned int with n bytes (default is native size) -- f f: a float (native size) -- d d: a double (native size) -- d n: a lua_Number -- [#c] cn: a fixed-sized string with n bytes -- -- one or both may be useful for filling out to match actualSize from NSGetSizeAndAlignment -- -- also to skip over types we can't handle in data field? -- x: one byte of padding -- Xop: an empty item that aligns according to option op (which is otherwise ignored) -- ???? z: a zero-terminated string -- -- Objective-C -> Lua, would have to modify data from NSValue to replace * address with \0 terminated character stream -- Lua -> Objective-C, would need some way to know when to free the char* memory... and modify the data replacing the "stream" with the address -- ... useful for hs._asm.objc... anything else? worth the effort? -- probably going to need to do this in Objective-C to get a propert treatment of char* local objCTypeToPackType = { ["c"] = "b", ["i"] = "i", ["s"] = "h", ["l"] = "l", ["q"] = "j", ["C"] = "B", ["I"] = "I", ["S"] = "H", ["L"] = "L" ["Q"] = "J", ["f"] = "f", ["d"] = "d", ["B"] = "B", ["v"] = " ", ["*"] = "T", -- will require C-Side support for anything else ["@"] = "T", -- will require C-Side support for anything else ["#"] = "T", -- will require C-Side support for anything else [":"] = "T", -- will require C-Side support for anything else -- ["[array type]"] = ... -- converted to repetition or c# -- ["{name=type...}"] = ... -- stripped out via string.gsub -- ["(name=type...)"] = ... -- converted to c# -- ["bnum"] = ... ? -- ["^type"] = ... converted to T ["?"] = "T", } module.toLuaTypeString = function(objCType) local workingString = objCType ; -- convert union into [#c] with same size as largest type specified -- TODO: do we have to worry about alignment? need some rw examples -- Alignment works as follows: For each option, the format gets extra padding until the data starts at an offset that is a multiple of the minimum between the option size and the maximum alignment; this minimum must be a power of 2. Options "c" and "z" are not aligned; option "s" follows the alignment of its starting integer. -- local s, e = workingString:find("%(") while s do local openChar = workingString:sub(e, e) local count = 1 local closeChar = ")" while (count ~= 0 and e < #workingString) do e = e + 1 local nextChar = workingString:sub(e, e) if nextChar == openChar then count = count + 1 end if nextChar == closeChar then count = count - 1 end end if count ~= 0 then return error("mismatched union grouping with "..openChar) end local bytes = _xtras.sizeAndAlignment(workingString:sub(s, e))[2] workingString = workingString:sub(1, s - 1).."[?="..tostring(bytes).. "c]"..workingString:sub(e + 1, -1) s, e = workingString:find("%^") end print("Without Unions : ", workingString) ; -- convert pointers into "T" s, e = workingString:find("%^") while s do e = e + 1 local openChar = workingString:sub(e, e) if openChar == "[" or openChar == "{" or openChar == "(" then local count = 1 local closeChar = ({ ["["] = "]", ["("] = ")", ["{"] = "}" })[openChar] while (count ~= 0 and e < #workingString) do e = e + 1 local nextChar = workingString:sub(e, e) if nextChar == openChar then count = count + 1 end if nextChar == closeChar then count = count - 1 end end if count ~= 0 then return error("mismatched pointer grouping with "..openChar) end end workingString = workingString:sub(1, s - 1).."T"..workingString:sub(e + 1, -1) s, e = workingString:find("%^") end print("Without Pointers: ", workingString) ; -- convert array into # copies of what follows? -- [#c] gets turned into string of that length (c#); others... repeat? -- TODO: do we have to worry about alignment? need some rw examples -- Alignment works as follows: For each option, the format gets extra padding until the data starts at an offset that is a multiple of the minimum between the option size and the maximum alignment; this minimum must be a power of 2. Options "c" and "z" are not aligned; option "s" follows the alignment of its starting integer. -- print("Without Arrays : ", workingString) ; -- strip structures workingString = workingString:gsub("{[\w\d_%?]+=", ""):gsub("}", "") print("Without Structs : ", workingString) ; -- convert other types (simple substitution) for k, v in pairs(objCTypeToPackType) do workingString = workingString:gsub(i, v) end print("Converted Types : ", workingString) ; -- prefix string with '=!'..(third argument from table from _xtras.sizeAndAlignment on objCType) workingString = "=!".._xtras.sizeAndAlignment(objCType)[3] -- TODO: string.packsize and pad if not long enough print("Size Comparison : ", _xtras.sizeAndAlignment(objCType)[2], string.packsize(workingString)) -- pray. return workingString end module.toObjCTypeString = function(luaType) end module.padForNSValue = function(list, objCType) local luaType = module.toLuaTypeString(objCType) end module.tableFromNSValue = function(data, objCType) local luaType = module.toLuaTypeString(objCType) end return module
local assertion = require('vgit.core.assertion') local utils = { object = {}, } utils.age = function(current_time) assertion.assert(current_time) local time = os.difftime(os.time(), current_time) local time_divisions = { { 1, 'years' }, { 12, 'months' }, { 30, 'days' }, { 24, 'hours' }, { 60, 'minutes' }, { 60, 'seconds' }, } for i = 1, #time_divisions do time = time / time_divisions[i][1] end local counter = 1 local time_division = time_divisions[counter] local time_boundary = time_division[1] local time_postfix = time_division[2] while time < 1 and counter <= #time_divisions do time_division = time_divisions[counter] time_boundary = time_division[1] time_postfix = time_division[2] time = time * time_boundary counter = counter + 1 end local unit = utils.round(time) local how_long = unit <= 1 and time_postfix:sub(1, #time_postfix - 1) or time_postfix return { unit = unit, how_long = how_long, display = string.format('%s %s ago', unit, how_long), } end utils.retrieve = function(cmd, ...) if type(cmd) == 'function' then return cmd(...) end return cmd end utils.round = function(x) return x >= 0 and math.floor(x + 0.5) or math.ceil(x - 0.5) end utils.shorten_string = function(str, limit) if #str > limit then str = str:sub(1, limit - 3) str = str .. '...' end return str end utils.accumulate_string = function(existing_text, new_text) local top_range = #existing_text local end_range = top_range + #new_text local text = existing_text .. new_text return text, { top = top_range, bot = end_range, } end utils.strip_substring = function(given_string, substring) if substring == '' then return given_string end local rc_s = '' local i = 1 local found = false while i <= #given_string do local temp_i = 0 if not found then for j = 1, #substring do local s_j = substring:sub(j, j) local s_i = given_string:sub(i + temp_i, i + temp_i) if s_j == s_i then temp_i = temp_i + 1 end end end if temp_i == #substring then found = true i = i + temp_i else rc_s = rc_s .. given_string:sub(i, i) i = i + 1 end end return rc_s end utils.object.assign = function(state_object, config_object) return vim.tbl_deep_extend('force', state_object or {}, config_object or {}) end utils.object.pick = function(object, item) for i = 1, #object do if object[i] == item then return item end end return object[1] end utils.list_concat = function(a, b) for i = 1, #b do a[#a + 1] = b[i] end return a end utils.sanitized_str_len = function(str) local _, count = string.gsub(str, '[^\128-\193]', '') return count end return utils
local Bolt = {} Bolt.Version = "22.1.0" Bolt.VersionDetails = "Added checking ownership of game passes. Prompting purchases of game passes now returns true if the player bought them. Added RayCasting. Added MoveCamera" local players = game:GetService("Players") local marketplace = game:GetService("MarketplaceService") local datastores = game:GetService("DataStoreService") local badges = game:GetService("BadgeService") local chat = game:GetService("Chat") local input = game:GetService("UserInputService") local http = game:GetService("HttpService") local camera = workspace.Camera game.Players.PlayerAdded:Connect(function(player) Bolt.Stats = Instance.new("Folder", player) Bolt.Stats.Name = "stats" Bolt.Leaderstats = Instance.new("Folder", player) Bolt.Leaderstats.Name = "leaderstats" end) function Bolt.Kill(player) player.Character:WaitForChild("Humanoid").Health = 0 end function Bolt.RemoveHealth(player, health) player.Character:WaitForChild("Humanoid").Health = (player.Character:WaitForChild("Humanoid").Health - health) end function Bolt.AddHealth(player, health) player.Character:WaitForChild("Humanoid").Health = (player.Character:WaitForChild("Humanoid").Health + health) end function Bolt.NewLeaderstat(player, name, variableType) local value = Instance.new(variableType, player:WaitForChild("leaderstats")) value.Name = name end function Bolt.ChangeLeaderstat(player, name, value) local stat = player:WaitForChild("leaderstats"):WaitForChild(name) stat.Value = value end function Bolt.NewStat(player, name, variableType) local value = Instance.new(variableType, player:WaitForChild("stats")) value.Name = name end function Bolt.ChangeStat(player, name, value) local stat = player:WaitForChild("stats"):WaitForChild(name) stat.Value = value end function Bolt.PromptPremium(player) marketplace:PromptPremiumPurchase(player) end function Bolt.AwardBadge(playerId, badgeId) badges:AwardBadge(playerId, badgeId) end function Bolt.DarkBubbleChat() local BubbleChatSettings = { BackgroundColor3 = Color3.fromRGB(50, 50, 50), TextColor3 = Color3.fromRGB(255, 255, 255) } chat:SetBubbleChatSettings(BubbleChatSettings) end function Bolt.LightBubbleChat() local BubbleChatSettings = { BackgroundColor3 = Color3.fromRGB(255, 255, 255), TextColor3 = Color3.fromRGB(0, 0, 0) } chat:SetBubbleChatSettings(BubbleChatSettings) end function Bolt.Shoot(player, origin, mousePos, damage, distance) local RayCastParams = RaycastParams.new() RayCastParams.FilterDescendantsInstances = {player.Character} RayCastParams.FilterType = Enum.RaycastFilterType.Blacklist local RayCastResults = workspace:Raycast(origin, (mousePos - origin) * distance, RayCastParams) if RayCastResults then local HitPart = RayCastResults.Instance local Model = HitPart:FindFirstAncestorOfClass("Model") if Model then if Model:FindFirstChild("Humanoid") then Model.Humanoid.Health -= damage end end end end function Bolt.RayCast(origin, destination, damage, distance ,blacklist) local RayCastParams = RaycastParams.new() RayCastParams.FilterDescendantsInstances = blacklist RayCastParams.FilterType = Enum.RaycastFilterType.Blacklist local RayCastResults = workspace:Raycast(origin, (destination - origin) * distance, RayCastParams) if RayCastResults then return RayCastResults end end function Bolt.ChangeSpeed(player, speed) player.Character:WaitForChild("Humanoid").WalkSpeed = speed end function Bolt.Teleport(player, destination) local character = workspace:WaitForChild(player.Name) character:MoveTo(destination) end function Bolt:ChangeTeam(player, team) player.Team = team end function Bolt.PromptGamePass(player, gamePassId) marketplace:PromptGamePassPurchase(player, gamePassId) marketplace.PromptGamePassPurchaseFinished:Connect(function(player, purchasedPassID, purchaseSuccess) if purchaseSuccess == true and purchasedPassID == gamePassId then return true end end) end function Bolt.OwnsGamePass(player, gamePassId) local hasPass = false local success = pcall(function() hasPass = marketplace:UserOwnsGamePassAsync(player.UserId, gamePassId) end) if hasPass == true then return true else return false end end function Bolt.MoveCamera(CFrame) camera.CFrame = CFrame end return Bolt
-- default tip text in case the httpreq() messes up, so we dont crash displaying a tip that has nil text local tiptext = "" -- get text from website dohttpreq( "http://whatthecommit.com/index.txt", function(data, id) if not data:is_nil_or_empty() then -- format the text to not be a (tiny) webpage tiptext = string.sub( tostring(data), string.find(data, "<pre>") + 5, string.find(data, "</pre>") ) end end ) -- list of all tip icons that kinda make sense local applicable = { "crimenet_basic_heists", "crimenet_fbifiles", "general_achievements", "general_difficulty", "general_escapes", "general_maplayout", "general_mastermind", "general_preplanning", "tactics_medicbag", "contact_bain", "contact_dentist" } -- override tip-getting function function TipsTweakData:get_a_tip() return { image = applicable[math.random(#applicable)], index = math.random(2147483647), total = 2147483647, title = "tip", text = tiptext } end --[[ note that we don't override any other tip-related functions despite the entirety of TipsTweakData now becoming useless. this is because we want our mod to have as few incompatibilities as possible, and even though it would be optimisation to override those functions into nothing, that would be creeping outside of its original intended purpose. ]]--
object_mobile_som_som_ancient_guardian_ig = object_mobile_som_shared_som_ancient_guardian_ig:new { } ObjectTemplates:addTemplate(object_mobile_som_som_ancient_guardian_ig, "object/mobile/som/som_ancient_guardian_ig.iff")
package.cpath = "bin/?.dll" local iup = require "iuplua" local bgfx = require "bgfx" local bgfxu = require "bgfx.util" local util = require "util" local math3d = require "math3d" local ctx = { canvas = iup.canvas {}, } local dlg = iup.dialog { ctx.canvas, title = "15-shadowmaps_simple", size = "HALFxHALF", } local RENDER_SHADOW_PASS_ID = 0 local RENDER_SCENE_PASS_ID = 1 local vec0 = math3d.vector() local time = 0 local function mainloop() math3d.reset() time = time + 0.01 bgfx.touch(0) -- Setup lights. local lightPos = math3d.vector ( -math.cos(time), -1, -math.sin(time), 0) bgfx.set_uniform(ctx.u_lightPos, lightPos) -- Setup instance matrices. local mtxFloor = math3d.matrix { s = 30 } local mtxBunny = math3d.matrix { s = 5, r = { 0, math.pi - time, 0}, t={15,5,0} } local mtxHollowcube = math3d.matrix { s = 2.5, r = { 0.0, 1.56 - time, 0.0 }, t = { 0.0, 10.0, 0.0 } } local mtxCube = math3d.matrix { s = 2.5 , r = { 0.0, 1.56 - time, 0.0 }, t = { -15.0, 5.0, 0.0 } } -- Define matrices. local lightView = math3d.lookat ( math3d.sub( vec0, lightPos ) , vec0) local area = 30.0 local lightProj = math3d.projmat { ortho = true, l = -area, r = area, b = -area, t = area, n = -100, f = 100 } bgfx.set_view_rect(RENDER_SHADOW_PASS_ID, 0, 0, ctx.m_shadowMapSize, ctx.m_shadowMapSize) bgfx.set_view_frame_buffer(RENDER_SHADOW_PASS_ID, ctx.m_shadowMapFB) bgfx.set_view_transform(RENDER_SHADOW_PASS_ID, lightView, lightProj) bgfx.set_view_rect(RENDER_SCENE_PASS_ID, 0, 0, ctx.width, ctx.height) bgfx.set_view_transform(RENDER_SCENE_PASS_ID, ctx.view, ctx.proj) -- Clear backbuffer and shadowmap framebuffer at beginning. bgfx.set_view_clear(RENDER_SHADOW_PASS_ID, "CD",0x303030ff, 1.0, 0) bgfx.set_view_clear(RENDER_SCENE_PASS_ID, "CD",0x303030ff, 1.0, 0) local mtxTmp =math3d.mul(ctx.mtxCrop, lightProj) local mtxShadow = math3d.mul(mtxTmp, lightView) local lightMtx = math3d.mul(mtxShadow, mtxFloor) -- Floor. local cached = bgfx.set_transform(mtxFloor) for pass =1, 2 do local st = ctx.m_state[pass] bgfx.set_transform_cached(cached) for _,texture in ipairs(st.textures) do bgfx.set_texture(texture.stage, texture.sampler, texture.texture, texture.flags) end bgfx.set_uniform(ctx.u_lightMtx, lightMtx) bgfx.set_index_buffer(ctx.m_ibh) bgfx.set_vertex_buffer(ctx.m_vbh) bgfx.set_state(st.state) bgfx.submit(st.viewId, st.program) end -- Bunny. lightMtx = math3d.mul(mtxShadow , mtxBunny) bgfx.set_uniform(ctx.u_lightMtx, lightMtx) util.meshSubmitState(ctx.m_bunny, ctx.m_state[1], mtxBunny) bgfx.set_uniform(ctx.u_lightMtx, lightMtx) util.meshSubmitState(ctx.m_bunny, ctx.m_state[2], mtxBunny) -- Hollow cube. lightMtx = math3d.mul(mtxShadow, mtxHollowcube) bgfx.set_uniform(ctx.u_lightMtx, lightMtx) util.meshSubmitState(ctx.m_hollowcube, ctx.m_state[1], mtxHollowcube) bgfx.set_uniform(ctx.u_lightMtx, lightMtx) util.meshSubmitState(ctx.m_hollowcube, ctx.m_state[2], mtxHollowcube) -- Cube. lightMtx = math3d.mul(mtxShadow, mtxCube) bgfx.set_uniform(ctx.u_lightMtx, lightMtx) util.meshSubmitState(ctx.m_cube, ctx.m_state[1], mtxCube) bgfx.set_uniform(ctx.u_lightMtx, lightMtx) util.meshSubmitState(ctx.m_cube, ctx.m_state[2], mtxCube) bgfx.frame() end function ctx.init() -- Uniforms. ctx.s_shadowMap = bgfx.create_uniform("s_shadowMap", "s") ctx.u_lightPos = bgfx.create_uniform("u_lightPos", "v4") ctx.u_lightMtx = bgfx.create_uniform("u_lightMtx", "m4") -- When using GL clip space depth range [-1, 1] and packing depth into color buffer, we need to -- adjust the depth range to be [0, 1] for writing to the color buffer ctx.u_depthScaleOffset = bgfx.create_uniform("u_depthScaleOffset", "v4") if util.caps.homogeneousDepth then bgfx.set_uniform(ctx.u_depthScaleOffset, math3d.vector(1, 0, 0, 0)) else bgfx.set_uniform(ctx.u_depthScaleOffset, math3d.vector(0.5, 0.5, 0, 0)) end -- Create vertex stream declaration. ctx.vdecl = bgfx.vertex_layout { { "POSITION", 3, "FLOAT" }, { "NORMAL", 4, "UINT8", true, true }, } -- Meshes. ctx.m_bunny = util.meshLoad "meshes/bunny.bin" ctx.m_cube = util.meshLoad "meshes/cube.bin" ctx.m_hollowcube = util.meshLoad "meshes/hollowcube.bin" local encodeNormalRgba8 = bgfxu.encodeNormalRgba8 ctx.m_vbh = bgfx.create_vertex_buffer( bgfx.memory_buffer( "fffd", { -1.0, 0.0, 1.0, encodeNormalRgba8(0.0, 1.0, 0.0), 1.0, 0.0, 1.0, encodeNormalRgba8(0.0, 1.0, 0.0), -1.0, 0.0, -1.0, encodeNormalRgba8(0.0, 1.0, 0.0), 1.0, 0.0, -1.0, encodeNormalRgba8(0.0, 1.0, 0.0), } ) , ctx.vdecl) ctx.m_ibh = bgfx.create_index_buffer { 0, 1, 2, 1, 3, 2, } -- Render targets. ctx.m_shadowMapSize = 512 -- Shadow samplers are supported at least partially supported if texture -- compare less equal feature is supported. ctx.m_shadowSamplerSupported = util.caps.supported.TEXTURE_COMPARE_LEQUAL local shadowMapTexture if ctx.m_shadowSamplerSupported then -- Depth textures and shadow samplers are supported. ctx.m_progShadow = util.programLoad("vs_sms_shadow", "fs_sms_shadow") ctx.m_progMesh = util.programLoad("vs_sms_mesh", "fs_sms_mesh") shadowMapTexture = bgfx.create_texture2d( ctx.m_shadowMapSize , ctx.m_shadowMapSize , false , 1 , "D16" , "rtc[" -- BGFX_TEXTURE_RT | BGFX_TEXTURE_COMPARE_LEQUAL ) ctx.m_shadowMapFB = bgfx.create_frame_buffer({shadowMapTexture}, true) else -- Depth textures and shadow samplers are not supported. Use float -- depth packing into color buffer instead. ctx.m_progShadow = util.programLoad("vs_sms_shadow_pd", "fs_sms_shadow_pd") ctx.m_progMesh = util.programLoad("vs_sms_mesh", "fs_sms_mesh_pd") shadowMapTexture = bgfx.create_texture2d( ctx.m_shadowMapSize , ctx.m_shadowMapSize , false , 1 , "BGRA8" , "rt" -- BGFX_TEXTURE_RT ) local fbtextures = { shadowMapTexture, bgfx.create_texture2d( ctx.m_shadowMapSize , ctx.m_shadowMapSize , false , 1 , "D16" , "rw" -- BGFX_TEXTURE_RT_WRITE_ONLY ) } ctx.m_shadowMapFB = bgfx.create_frame_buffer(fbtextures, true) end ctx.m_state = {} ctx.m_state[1] = { state = bgfx.make_state { WRITE_MASK = "RGBAZ", DEPTH_TEST = "LESS", CULL = "CCW", MSAA = true, }, program = ctx.m_progShadow, viewId = RENDER_SHADOW_PASS_ID, textures = {} } ctx.m_state[2] = { state = bgfx.make_state { WRITE_MASK = "RGBAZ", DEPTH_TEST = "LESS", CULL = "CCW", MSAA = true, }, program = ctx.m_progMesh, viewId = RENDER_SCENE_PASS_ID, textures = {{ flags = nil, stage = 0, sampler = ctx.s_shadowMap, texture = shadowMapTexture }}, } local sy = util.caps.originBottomLeft and 0.5 or -0.5 local sz = util.caps.homogeneousDepth and 0.5 or 1 local tz = util.caps.homogeneousDepth and 0.5 or 0 ctx.mtxCrop = math3d.ref(math3d.matrix ( 0.5, 0.0, 0.0, 0.0, 0.0, sy, 0.0, 0.0, 0.0, 0.0, sz, 0.0, 0.5, 0.5, tz, 1.0 )) end function ctx.resize(w,h) ctx.width = w ctx.height = h bgfx.reset(ctx.width,ctx.height, "vmx") ctx.view = math3d.ref(math3d.lookat( { 0,30,-60 }, { 0,5,0 })) ctx.proj = math3d.ref(math3d.projmat { fov = 60, aspect = w/h, n = 0.1, f = 100 }) end util.init(ctx) dlg:showxy(iup.CENTER,iup.CENTER) dlg.usersize = nil util.run(mainloop)
local Thread = require('src.threads.thread') local SearchThread = class('SearchThread', Thread) function SearchThread:initialize() self.inner = 'src/threads/search_inner.lua' Thread.initialize(self) end return SearchThread
-- Copyright 2020 Ivan Belokobylskiy <belokobylskij@gmail.com> -- Licensed to the public under the Apache License 2.0. module("luci.controller.jntools", package.seeall) function index() entry({"admin", "system", "jntools"}, template("jntools"), _("Zigbee Tools"), 30) entry({"admin", "system", "jntools", "flash"}, post("action_flash")).leaf = true entry({"admin", "system", "jntools", "exec"}, post("action_exec")).leaf = true end function action_flash(command) local sys = require "luci.sys" local cmd = { "/usr/bin/jnflash" } local firmware = luci.http.formvalue("firmware") if command == 'do-flash-url' then sys.httpget(firmware, false, "/tmp/firmware.bin") firmware = "/tmp/firmware.bin" end if firmware then cmd[#cmd + 1] = firmware cmd[#cmd + 1] = "-q" end luci.http.prepare_content("application/json") luci.http.write_json(sys.process.exec(cmd, true, true)) end function action_exec(command) local sys = require "luci.sys" local nixio = require "nixio" local cmd = { "/usr/bin/jntool" } local baudrate = luci.http.formvalue("baudrate") if not baudrate then baudrate = "115200" end cmd[#cmd + 1] = command luci.http.prepare_content("application/json") nixio.setenv("BAUDRATE", baudrate) luci.http.write_json(sys.process.exec(cmd, true, true)) end
local png = {} do -- png.lua --[[ BSD 2-Clause License Copyright (c) 2018, Kartik Singh All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --]] local floor = math.floor local ceil = math.ceil local min = math.min local max = math.max local abs = math.abs -- utility functions function memoize(f) local cache = {} return function(...) local key = table.concat({...}, "-") if not cache[key] then cache[key] = f(...) end return cache[key] end end function int(bytes) local n = 0 for i = 1, #bytes do n = 256*n + bytes:sub(i, i):byte() end return n end int = memoize(int) function bint(bits) return tonumber(bits, 2) or 0 end bint = memoize(bint) function bits(b, width) local s = "" if type(b) == "number" then for i = 1, width do s = b%2 .. s b = floor(b/2) end else for i = 1, #b do s = s .. bits(b:sub(i, i):byte(), 8):reverse() end end return s end bits = memoize(bits) function fill(bytes, len) return bytes:rep(floor(len / #bytes)) .. bytes:sub(1, len % #bytes) end function zip(t1, t2) local zipped = {} for i = 1, max(#t1, #t2) do zipped[#zipped + 1] = {t1[i], t2[i]} end return zipped end function unzip(zipped) local t1, t2 = {}, {} for i = 1, #zipped do t1[#t1 + 1] = zipped[i][1] t2[#t2 + 1] = zipped[i][2] end return t1, t2 end function map(f, t) local mapped = {} for i = 1, #t do mapped[#mapped + 1] = f(t[i], i) end return mapped end function filter(pred, t) local filtered = {} for i = 1, #t do if pred(t[i], i) then filtered[#filtered + 1] = t[i] end end return filtered end function find(key, t) if type(key) == "function" then for i = 1, #t do if key(t[i]) then return i end end return nil else return find(function(x) return x == key end, t) end end function slice(t, i, j, step) local sliced = {} for k = i < 1 and 1 or i, i < 1 and #t + i or j or #t, step or 1 do sliced[#sliced + 1] = t[k] end return sliced end function range(i, j) local r = {} for k = j and i or 0, j or i - 1 do r[#r + 1] = k end return r end -- streams function byte_stream(raw) local stream = {} local curr = 0 function stream:read(n) local b = raw:sub(curr + 1, curr + n) curr = curr + n return b end function stream:seek(n, whence) if n == "beg" then curr = 0 elseif n == "end" then curr = #raw elseif whence == "beg" then curr = n else curr = curr + n end return self end function stream:is_empty() return curr >= #raw end function stream:pos() return curr end function stream:raw() return raw end return stream end function bit_stream(raw, offset) local stream = {} local curr = 0 offset = offset or 0 function stream:read(n, reverse) local start = floor(curr/8) + offset + 1 local b = bits(raw:sub(start, start + ceil(n/8))):sub(curr%8 + 1, curr%8 + n) curr = curr + n return reverse and b or b:reverse() end function stream:seek(n) if n == "beg" then curr = 0 elseif n == "end" then curr = #raw else curr = curr + n end return self end function stream:is_empty() return curr >= 8*#raw end function stream:pos() return curr end return stream end function output_stream() local stream, buffer = {}, {} local curr = 0 function stream:write(bytes) for i = 1, #bytes do buffer[#buffer + 1] = bytes:sub(i, i) end curr = curr + #bytes end function stream:back_read(offset, n) local read = {} for i = curr - offset + 1, curr - offset + n do read[#read + 1] = buffer[i] end return table.concat(read) end function stream:back_copy(dist, len) local start, copied = curr - dist + 1, {} for i = start, min(start + len, curr) do copied[#copied + 1] = buffer[i] end self:write(fill(table.concat(copied), len)) end function stream:pos() return curr end function stream:raw() return table.concat(buffer) end return stream end -- inflate local CL_LENS_ORDER = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} local MAX_BITS = 15 local PT_WIDTH = 8 function cl_code_lens(stream, hclen) local code_lens = {} for i = 1, hclen do code_lens[#code_lens + 1] = bint(stream:read(3)) end return code_lens end function code_tree(lens, alphabet) alphabet = alphabet or range(#lens) local using = filter(function(x, i) return lens[i] and lens[i] > 0 end, alphabet) lens = filter(function(x) return x > 0 end, lens) local tree = zip(lens, using) table.sort(tree, function(a, b) if a[1] == b[1] then return a[2] < b[2] else return a[1] < b[1] end end) return unzip(tree) end function codes(lens) local codes = {} local code = 0 for i = 1, #lens do codes[#codes + 1] = bits(code, lens[i]) if i < #lens then code = (code + 1)*2^(lens[i + 1] - lens[i]) end end return codes end function handle_long_codes(codes, alphabet, pt) local i = find(function(x) return #x > PT_WIDTH end, codes) local long = slice(zip(codes, alphabet), i) i = 0 repeat local prefix = long[i + 1][1]:sub(1, PT_WIDTH) local same = filter(function(x) return x[1]:sub(1, PT_WIDTH) == prefix end, long) same = map(function(x) return {x[1]:sub(PT_WIDTH + 1), x[2]} end, same) pt[prefix] = {rest = prefix_table(unzip(same)), unused = 0} i = i + #same until i == #long end function prefix_table(codes, alphabet) local pt = {} if #codes[#codes] > PT_WIDTH then handle_long_codes(codes, alphabet, pt) end for i = 1, #codes do local code = codes[i] if #code > PT_WIDTH then break end local entry = {value = alphabet[i], unused = PT_WIDTH - #code} if entry.unused == 0 then pt[code] = entry else for i = 0, 2^entry.unused - 1 do pt[code .. bits(i, entry.unused)] = entry end end end return pt end function huffman_decoder(lens, alphabet) local base_codes = prefix_table(codes(lens), alphabet) return function(stream) local codes = base_codes local entry repeat entry = codes[stream:read(PT_WIDTH, true)] stream:seek(-entry.unused) codes = entry.rest until not codes return entry.value end end function code_lens(stream, decode, n) local lens = {} repeat local value = decode(stream) if value < 16 then lens[#lens + 1] = value elseif value == 16 then for i = 1, bint(stream:read(2)) + 3 do lens[#lens + 1] = lens[#lens] end elseif value == 17 then for i = 1, bint(stream:read(3)) + 3 do lens[#lens + 1] = 0 end elseif value == 18 then for i = 1, bint(stream:read(7)) + 11 do lens[#lens + 1] = 0 end end until #lens == n return lens end function code_trees(stream) local hlit = bint(stream:read(5)) + 257 local hdist = bint(stream:read(5)) + 1 local hclen = bint(stream:read(4)) + 4 local cl_decode = huffman_decoder(code_tree(cl_code_lens(stream, hclen), CL_LENS_ORDER)) local ll_decode = huffman_decoder(code_tree(code_lens(stream, cl_decode, hlit))) local d_decode = huffman_decoder(code_tree(code_lens(stream, cl_decode, hdist))) return ll_decode, d_decode end function extra_bits(value) if value >= 4 and value <= 29 then return floor(value/2) - 1 elseif value >= 265 and value <= 284 then return ceil(value/4) - 66 else return 0 end end extra_bits = memoize(extra_bits) function decode_len(value, bits) assert(value >= 257 and value <= 285, "value out of range") assert(#bits == extra_bits(value), "wrong number of extra bits") if value <= 264 then return value - 254 elseif value == 285 then return 258 end local len = 11 for i = 1, #bits - 1 do len = len + 2^(i+2) end return floor(bint(bits) + len + ((value - 1) % 4)*2^#bits) end decode_len = memoize(decode_len) function a(n) if n <= 3 then return n + 2 else return a(n-1) + 2*a(n-2) - 2*a(n-3) end end a = memoize(a) function decode_dist(value, bits) assert(value >= 0 and value <= 29, "value out of range") assert(#bits == extra_bits(value), "wrong number of extra bits") return bint(bits) + a(value - 1) end decode_dist = memoize(decode_dist) function inflate(stream) local ostream = output_stream() repeat local bfinal, btype = bint(stream:read(1)), bint(stream:read(2)) assert(btype == 2, "compression method not supported") local ll_decode, d_decode = code_trees(stream) while true do local value = ll_decode(stream) if value < 256 then ostream:write(string.char(value)) elseif value == 256 then break else local len = decode_len(value, stream:read(extra_bits(value))) value = d_decode(stream) local dist = decode_dist(value, stream:read(extra_bits(value))) ostream:back_copy(dist, len) end end os.sleep(0) --write(".") until bfinal == 1 return ostream:raw() end -- chunk processing local CHANNELS = {} CHANNELS[0] = 1 CHANNELS[2] = 3 CHANNELS[3] = 1 CHANNELS[4] = 2 CHANNELS[6] = 4 function process_header(stream, image) stream:seek(8) image.width = int(stream:read(4)) image.height = int(stream:read(4)) image.bit_depth = int(stream:read(1)) image.color_type= int(stream:read(1)) image.channels = CHANNELS[image.color_type] image.compression_method = int(stream:read(1)) image.filter_method = int(stream:read(1)) image.interlace_method = int(stream:read(1)) assert(image.interlace_method == 0, "interlacing not supported") stream:seek(4) end function process_data(stream, image) local chunk_len = int(stream:read(4)) stream:seek(4) assert(int(stream:read(2)) % 31 == 0, "invalid zlib header") stream:seek(-2) local dstream = output_stream() repeat dstream:write(stream:read(chunk_len)) stream:seek(4) chunk_len = int(stream:read(4)) until stream:read(4) ~= "IDAT" stream:seek(-8) local bstream = bit_stream(dstream:raw(), 2) image.data = inflate(bstream) end function process_palette(stream, image) local chunk_len = int(stream:read(4)) stream:seek(4) assert(chunk_len % 3 == 0, "invalid palette") image.palette = {} for i = 0, chunk_len - 1, 3 do image.palette[i/3] = { r = int(stream:read(1)), g = int(stream:read(1)), b = int(stream:read(1)) } end stream:seek(4) end function process_chunk(stream, image) local chunk_len = int(stream:read(4)) local chunk_type = stream:read(4) stream:seek(-8) if chunk_type == "IHDR" then process_header(stream, image) elseif chunk_type == "IDAT" then process_data(stream, image) elseif chunk_type == "IEND" then stream:seek("end") elseif chunk_type == "PLTE" then process_palette(stream, image) else stream:seek(chunk_len + 12) end end -- reconstruction function paeth(a, b, c) local p = a + b - c local pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) if pa <= pb and pa <= pc then return a elseif pb <= pc then return b else return c end end function scanlines(image) assert(image.bit_depth % 8 == 0, "bit depth not supported") local stream = byte_stream(image.data) local pixel_width = image.channels * image.bit_depth/8 local scanline_width = image.width * pixel_width local ostream = output_stream() return function() local lstream = output_stream() if not stream:is_empty() then local filter_method = int(stream:read(1)) for i = 1, scanline_width do local x = int(stream:read(1)) local a = int(ostream:back_read(pixel_width, 1)) local b = int(ostream:back_read(scanline_width, 1)) local c = int(ostream:back_read(scanline_width + pixel_width, 1)) if i <= pixel_width then a, c = 0, 0 end local byte if filter_method == 0 then byte = string.char(x) elseif filter_method == 1 then byte = string.char((x + a) % 256) elseif filter_method == 2 then byte = string.char((x + b) % 256) elseif filter_method == 3 then byte = string.char((x + floor((a + b)/2)) % 256) elseif filter_method == 4 then byte = string.char((x + paeth(a, b, c)) % 256) end lstream:write(byte) ostream:write(byte) end end return lstream:raw() end end function pixel(stream, color_type, bit_depth) assert(bit_depth % 8 == 0, "bit depth not supported") local channels = CHANNELS[color_type] local function read_value() return int(stream:read(bit_depth/8)) end if color_type == 0 then return { v = read_value() } elseif color_type == 2 then return { r = read_value(), g = read_value(), b = read_value() } elseif color_type == 3 then return { v = int(stream:read(bit_depth/8)) } elseif color_type == 4 then return { v = read_value(), a = read_value() } elseif color_type == 6 then return { r = read_value(), g = read_value(), b = read_value(), a = read_value() } end end function png.pixels(image) local i = 0 local next_scanline = scanlines(image) local scanline = byte_stream(next_scanline()) return function() if scanline:is_empty() then return end local p = pixel(scanline, image.color_type, image.bit_depth) local x = i % image.width local y = floor(i / image.width) i = i + 1 if scanline:is_empty() then scanline = byte_stream(next_scanline()) end return p, x, y end end -- exports local PNG_HEADER = string.char(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a) function png.load_from_file(filename) local file = io.open(filename, "rb") local data = file:read("*all") file:close() return png.load(data) end function png.load(data) local stream = byte_stream(data) assert(stream:read(8) == PNG_HEADER, "PNG header not found") local image = {} repeat process_chunk(stream, image) until stream:is_empty() return image end end -- png.lua if not term.getGraphicsMode or not term.drawPixels then error("This requires CraftOS-PC v2.1 or later.") end local args = {...} if #args < 1 then error("Usage: pngview <image.png>") end local image = png.load_from_file(shell.resolve(args[1])) if image.data == nil then error("data is nil") end local w, h = term.getSize(2) if image.width > w or image.height > h then error("Image is too big") end os.queueEvent("nosleep") os.pullEvent() term.setGraphicsMode(2) term.clear() if image.color_type == 0 or image.color_type == 4 then for i = 0, 2^image.bit_depth-1 do term.setPaletteColor(i, i/(2^image.bit_depth-1), i/(2^image.bit_depth-1), i/(2^image.bit_depth-1)) end elseif image.color_type == 3 then for i = 0, #image.palette do term.setPaletteColor(i, image.palette[i].r/255, image.palette[i].g/255, image.palette[i].b/255) end elseif image.color_type == 2 or image.color_type == 6 then local palette = {} --local bpp = 3 + (bit.band(image.color_type, 4) / 4) --? local data = {} for p, x, y in png.pixels(image) do local idx for i,v in ipairs(palette) do if v.r == p.r and v.g == p.g and v.b == p.b then idx = i; break end end if idx == nil then if #palette >= 256 then term.setGraphicsMode(false) error("Image has too many colors") end idx = #palette + 1 palette[idx] = p end if data[y] == nil then data[y] = {} end data[y][x] = idx-1 --if x == 0 then os.sleep(0) end end for i,v in ipairs(palette) do term.setPaletteColor(i-1, v.r / 255, v.g / 255, v.b / 255) end term.drawPixels(0, 0, data) read() term.setGraphicsMode(false) for i = 0, 15 do term.setPaletteColor(2^i, term.nativePaletteColor(2^i)) end return else error("Image not supported") end term.clear() --local start = os.epoch("utc") local pixels = {} for y = 0, image.height - 1 do if image.color_type == 4 then local str = string.sub(image.data, y * (image.width * 2 + 1) + 1, (y + 1) * (image.width * 2 + 1)) pixels[y] = str for i = 1, #str, 2 do pixels[y] = pixels[y] .. string.sub(str, i, i) end else if image.bit_depth == 8 then pixels[y] = string.sub(image.data, y * (image.width + 2) + 1, (y + 1) * (image.width + 2)) else pixels[y] = "" for x = 1, image.width / (8 / image.bit_depth) do for i = 1, 8 / image.bit_depth do pixels[y] = pixels[y] .. string.char(bit32.band(bit32.rshift(string.byte(image.data, y * math.floor(image.width / (8 / image.bit_depth) + 1) + x), ((8/image.bit_depth)-i) * image.bit_depth), 2^image.bit_depth - 1)) end end end end end term.drawPixels(0, 0, pixels) --print("Render took " .. os.epoch("utc") - start .. " ms") read() term.setGraphicsMode(0) for i = 0, 15 do term.setPaletteColor(2^i, term.nativePaletteColor(2^i)) end
--[[ @ --]] -- ============================================================================= -- import -- ============================================================================= local convert = require("convert") -- load 3rd module local getopt = require("getopt") -- load module local input = require("input") local output = require("output") local bitmap = require("bitmap") -- ============================================================================= -- options setting -- ============================================================================= -- help infomation local function usage() local info = [[ bits number [input-base] [options] options -h | --help help info -r range_pattern from:to from+len from same as from:from from: same as from:end from+ same as from -i | --input-base {b|d|h} -o | --output-base {b|d|h} -s | --set-bits {bits,from [bits,from] [...]} index from 0 -l <y|n> when setting option "-r", this value will set y(--list) at the same time make sense only in --output-type is b --list same as -l y --no-list same as -l n -w | --width {number} the min-bits in input, defualt is -w 32 make sense only in --output is not list -d | --delimiter {gap separator} default is '-d 4 " " ' make sense only in --output is not list --gap {len} default is '--gap 4' --sep {separator} default is '--sep " "' ]] print(info) os.exit(0) end getopt.callback("h,help", usage) -- input config ----------------------- local function input_base(base) local _base = convert.parse_base(base) input:set_base(_base) end getopt.callback("i,input-base:N:1", input_base) local function set_width(width) local _w = tonumber(width) if not _w then error("width except get number") end input:set_width(_w) end getopt.callback("w,width:N:1", set_width) -- bitmap config ----------------------- local function set_mdf(...) local list = {...} bitmap:set_mdf(list) end getopt.callback("s,set-bits:U:1", set_mdf) -- output config ----------------------- local function set_range(pattern) output:set_range(pattern) end getopt.callback("r,range:N:1", set_range) local function set_list(list) if (list == "y") or (lsit == "Y") then output:set_list(true) elseif (list == "n") or (list == "N") then output:set_list(false) else error("error set list output") end end getopt.callback("l:N:1", set_list) local function nolist() output:set_list(false) end getopt.callback("no-list", nolist) local function list() output:set_list(true) end getopt.callback("list", list) local function output_base(base) local _base = convert.parse_base(base) output:set_base(_base) end getopt.callback("o,output-base:N:1", output_base) local function set_gap(len) output:set_style(nil, tonumber(len)) end getopt.callback("gap:N:1", set_gap) local function set_sep(separator) output:set_style(separator, nil) end getopt.callback("sep:N:1", set_sep) local function set_delimiter(gap, sep) set_sep(sep) set_gap(gap) end getopt.callback("d,delimiter:N:2", set_delimiter) -- main function -------------------- local function main(number, ibase, obase) if not number then error("none number input, you call use -h for help") end input:set_number(number) local _ = ibase and input_base(ibase) local _ = obase and output_base(obase) local i_bits = input:convert() bitmap:set(i_bits) bitmap:modify() local o_bits = bitmap:get() output:set(o_bits) output:print() end getopt.setmain(main) -- ============================================================================= -- main entry -- ============================================================================= local function run(param) getopt.run(param) end return { run = run }
---@meta ---@class hashlib local M = {} ---@class HashContext:userdata Hash context. local hash = {} ---@alias HashType ---|'"MD4"' ---|'"MD5"' ---|'"SHA1"' ---|'"SHA224"' ---|'"SHA256"' ---|'"SHA384"' ---|'"SHA512"' ---|'"RIPEMD160"' ---Update hash context with binary data. ---@param data string ---@return HashContext ctx function hash:update(data) end ---Return the digest of the data passed to the update() method so far. ---@return string digest ---@nodiscard function hash:digest() end ---Like ``digest()`` except the digest is returned as a string object of ---double length, containing only hexadecimal digits. ---@return string hexdigest ---@nodiscard function hash:hexdigest() end ---Create a hash context. ---@param type HashType ---@param key? string If key is set, HMAC will be used. ---@return HashContext ctx ---@nodiscard function M.create(type, key) end return M
dofile(debug.getinfo(1).source:match("@?(.*/)") .. '/default_config.lua') bag_path="data/00010_2019-05-16-03-59-04_0.bag" lidar_topic="/velodyne_2dscan_high_beams" odom_topic="/odometry/filtered" auto_lc=false pose_number=350 accuracy_change_stop_threshold = 0.005 translation_weight=1.0 rotation_weight=1.0 lidar_constraint_amount_max=10 outlier_threshold=1
-- 6-Speed gearboxes -- Weight local Gear6SW = 80 local Gear6MW = 160 local Gear6LW = 320 local StWB = 0.75 --straight weight bonus mulitplier -- Torque Rating local Gear6ST = 440 local Gear6MT = 1360 local Gear6LT = 10000 local StTB = 1.25 --straight torque bonus multiplier -- Inline ACF_DefineGearbox( "6Gear-L-S", { name = "6-Speed, Inline, Small", desc = "A small and light 6 speed inline gearbox, with a limited max torque rating.", model = "models/engines/linear_s.mdl", category = "6-Speed", weight = Gear6SW, switch = 0.15, maxtq = Gear6ST, gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-L-M", { name = "6-Speed, Inline, Medium", desc = "A medium duty 6 speed inline gearbox with a limited torque rating.", model = "models/engines/linear_m.mdl", category = "6-Speed", weight = Gear6MW, switch = 0.2, maxtq = Gear6MT, gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-L-L", { name = "6-Speed, Inline, Large", desc = "Heavy duty 6 speed inline gearbox, however not as resilient as a 4 speed.", model = "models/engines/linear_l.mdl", category = "6-Speed", weight = Gear6LW, switch = 0.3, maxtq = Gear6LT, gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 1 } } ) -- Inline Dual Clutch ACF_DefineGearbox( "6Gear-LD-S", { name = "6-Speed, Inline, Small, Dual Clutch", desc = "A small and light 6 speed inline gearbox, with a limited max torque rating. The dual clutch allows you to apply power and brake each side independently\n\nThe Final Drive slider is a multiplier applied to all the other gear ratios", model = "models/engines/linear_s.mdl", category = "6-Speed", weight = Gear6SW, switch = 0.15, maxtq = Gear6ST, gears = 6, doubleclutch = true, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-LD-M", { name = "6-Speed, Inline, Medium, Dual Clutch", desc = "A a medium duty 6 speed inline gearbox. The added gears reduce torque capacity substantially. The dual clutch allows you to apply power and brake each side independently\n\nThe Final Drive slider is a multiplier applied to all the other gear ratios", model = "models/engines/linear_m.mdl", category = "6-Speed", weight = Gear6MW, switch = 0.2, maxtq = Gear6MT, gears = 6, doubleclutch = true, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-LD-L", { name = "6-Speed, Inline, Large, Dual Clutch", desc = "Heavy duty 6 speed inline gearbox, however not as resilient as a 4 speed. The dual clutch allows you to apply power and brake each side independently\n\nThe Final Drive slider is a multiplier applied to all the other gear ratios", model = "models/engines/linear_l.mdl", category = "6-Speed", weight = Gear6LW, switch = 0.3, maxtq = Gear6LT, gears = 6, doubleclutch = true, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 1 } } ) -- Transaxial ACF_DefineGearbox( "6Gear-T-S", { name = "6-Speed, Transaxial, Small", desc = "A small and light 6 speed gearbox, with a limited max torque rating.", model = "models/engines/transaxial_s.mdl", category = "6-Speed", weight = Gear6SW, switch = 0.15, maxtq = Gear6ST, gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-T-M", { name = "6-Speed, Transaxial, Medium", desc = "A medium duty 6 speed gearbox with a limited torque rating.", model = "models/engines/transaxial_m.mdl", category = "6-Speed", weight = Gear6MW, switch = 0.2, maxtq = Gear6MT, gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-T-L", { name = "6-Speed, Transaxial, Large", desc = "Heavy duty 6 speed gearbox, however not as resilient as a 4 speed.", model = "models/engines/transaxial_l.mdl", category = "6-Speed", weight = Gear6LW, switch = 0.3, maxtq = Gear6LT, gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 1 } } ) -- Transaxial Dual Clutch ACF_DefineGearbox( "6Gear-TD-S", { name = "6-Speed, Transaxial, Small, Dual Clutch", desc = "A small and light 6 speed gearbox, with a limited max torque rating. The dual clutch allows you to apply power and brake each side independently\n\nThe Final Drive slider is a multiplier applied to all the other gear ratios", model = "models/engines/transaxial_s.mdl", category = "6-Speed", weight = Gear6SW, switch = 0.15, maxtq = Gear6ST, gears = 6, doubleclutch = true, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-TD-M", { name = "6-Speed, Transaxial, Medium, Dual Clutch", desc = "A a medium duty 6 speed gearbox. The added gears reduce torque capacity substantially. The dual clutch allows you to apply power and brake each side independently\n\nThe Final Drive slider is a multiplier applied to all the other gear ratios", model = "models/engines/transaxial_m.mdl", category = "6-Speed", weight = Gear6MW, switch = 0.2, maxtq = Gear6MT, gears = 6, doubleclutch = true, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-TD-L", { name = "6-Speed, Transaxial, Large, Dual Clutch", desc = "Heavy duty 6 speed gearbox, however not as resilient as a 4 speed. The dual clutch allows you to apply power and brake each side independently\n\nThe Final Drive slider is a multiplier applied to all the other gear ratios", model = "models/engines/transaxial_l.mdl", category = "6-Speed", weight = Gear6LW, switch = 0.3, maxtq = Gear6LT, gears = 6, doubleclutch = true, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 1 } } ) -- Straight-through gearboxes ACF_DefineGearbox( "6Gear-ST-S", { name = "6-Speed, Straight, Small", desc = "A small and light 6 speed straight-through gearbox.", model = "models/engines/t5small.mdl", category = "6-Speed", weight = math.floor(Gear6SW * StWB), switch = 0.15, maxtq = math.floor(Gear6ST * StTB), gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-ST-M", { name = "6-Speed, Straight, Medium", desc = "A medium 6 speed straight-through gearbox.", model = "models/engines/t5med.mdl", category = "6-Speed", weight = math.floor(Gear6MW * StWB), switch = 0.2, maxtq = math.floor(Gear6MT * StTB), gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } ) ACF_DefineGearbox( "6Gear-ST-L", { name = "6-Speed, Straight, Large", desc = "A large 6 speed straight-through gearbox.", model = "models/engines/t5large.mdl", category = "6-Speed", weight = math.floor(Gear6LW * StWB), switch = 0.3, maxtq = math.floor(Gear6LT * StTB), gears = 6, geartable = { [ 0 ] = 0, [ 1 ] = 0.1, [ 2 ] = 0.2, [ 3 ] = 0.3, [ 4 ] = 0.4, [ 5 ] = 0.5, [ 6 ] = -0.1, [ -1 ] = 0.5 } } )
object_tangible_loot_creature_loot_collections_meatlump_newspaper_06 = object_tangible_loot_creature_loot_collections_shared_meatlump_newspaper_06:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_meatlump_newspaper_06, "object/tangible/loot/creature/loot/collections/meatlump_newspaper_06.iff")
MOD = {} MOD.name = "ChargeTransmission" MOD.if_name = "charge-transmission" MOD.interfaces = {} MOD.commands = {} MOD.config = require "scripts/config" local Position = require "stdlib/area/position" require "stdlib/event/event" require "stdlib/table" -- Enables Debug mode for new saves if MOD.config.DEBUG then log(MOD.name .. " Debug mode enabled") require("stdlib/debug/quickstart") end local chargers, free_chargers, nodes, hashed_nodes, active_nodes, counters, constants --############################################################################-- -- LOGIC -- --############################################################################-- -- returns the node serving this cell, or nil -- even if the node is enqueued to be added (in new_nodes) local function get_node(cell) return cell and cell.valid and nodes[cell.owner.unit_number] end -- gets the closest cell to position -- we don't just return LuaLogisticNetwork.find_cell_closest_to() because we give priority to cells being served by nodes local function get_closest_cell(position, network) local closest_cell = network.find_cell_closest_to(position) -- short-circuit if there's no cell close to (how?) or if it is already a node (score) if get_node(closest_cell) then return closest_cell end -- so the closest cell is either a node or the one already in closest_cell -- let's find out! -- get cells that are close enough (include position) and are in a node local possible_nodes = table.filter(network.cells, function(cell) return cell.is_in_logistic_range(position) and get_node(cell) end) -- find the closest of these local min = math.huge for _, cell in pairs(possible_nodes) do -- the loop doesn't run if the table's empty local distance = Position.distance_squared(position, cell.owner.position) if distance < min then min = distance; closest_cell = cell end end return closest_cell end -- picks the right display variant between a charger and its target -- 1-9 (1 being 0 rad and 9 2π rad) local function update_display(charger) local vector = Position.subtract(charger.base.position, charger.target.owner.position) -- y axis is reversed -_- local orientation = (math.atan2(-vector.y, vector.x) / math.pi + 1) / 2 charger.display.graphics_variation = math.floor(orientation * 8 + 0.5) % 8 + 2 end local function enqueue_charger(charger) free_chargers[charger.id] = charger -- print("enqueued charger "..charger.id) end -- Removes a charger from a node, if it's there (complexity for debug purposes) -- requeue: if true adds the charger to the free_charger list too local function free_charger(charger, enqueue) local node = get_node(charger.target) if node then node.chargers[charger.id] = nil node.active = false -- print("removed charger "..charger.id.." from node "..node.id) end charger.target = nil if charger.display and charger.display.valid then charger.display.graphics_variation = 1 end if enqueue then enqueue_charger(charger) end end -- adds a cell as a charger's target (and hence pairs it with any respective node) local function target_cell(charger, cell) charger.target = cell -- make the display point at the cell's owner update_display(charger) local node = get_node(cell) if node then node.chargers[charger.id] = charger node.active = false -- print("added charger "..charger.id.." to node "..node.id) else -- new node node = { cell = cell, chargers = {}, id = cell.owner.unit_number, active = false, } node.chargers[charger.id] = charger nodes[node.id] = node local hash = node.id%60 if not hashed_nodes[hash] then hashed_nodes[hash] = {node} else table.insert(hashed_nodes[hash], node) end -- print("new node "..node.id.." with charger "..charger.id) end end -- return: true if a pair node was found local function pair_charger(charger) -- ignore already those with targets if charger.target and charger.target.valid then return end local network = charger.base.surface.find_logistic_network_by_position(charger.base.position, charger.base.force) if not network then return false end local closest = get_closest_cell(charger.base.position, network) if not closest then return false end target_cell(charger, closest) return true end --############################################################################-- -- EVENTS -- --############################################################################-- -- Finalizes building a charger, doing the following: -- Creates the composite unit (radar) -- Tries to find the closest logistic cell (roboport) and register it -- Else, adds it as an unpaired charger local function on_built_charger(event) local entity = event.created_entity if entity.name == "charge_transmission-charger" then local charger = { base = entity, id = entity.unit_number, c_debt = 0, l_debt = 0 } chargers[charger.id] = charger charger.interface = entity.surface.create_entity { name = "charge_transmission-charger_interface", position = entity.position, force = entity.force } charger.interface.destructible = false charger.display = entity.surface.create_entity { name = "charge_transmission-charger_display", position = entity.position, force = entity.force } charger.display.destructible = false charger.display.graphics_variation = 1 -- fixes any overlay issues (not needed any more but it doesn't hurt) entity.teleport(entity.position) if not pair_charger(charger) then enqueue_charger(charger) end end end local function on_mined_charger(event) local entity = event.entity if entity.name:find("charge_transmission%-charger") then if entity.name == "charge_transmission-charger" then local charger = chargers[entity.unit_number] if not charger then log "Attempted to remove already-dismantled charger" -- TODO: making sure the area is *really* clean for _, e in pairs(entity.surface.find_entities_filtered {area = entity.bounding_box}) do if e.name:match("^charge_transmission") then e.destroy() end end return end free_charger(charger) -- remove composite partners for _, component in pairs({charger.interface, charger.display}) do if component and component.valid then component.destroy() end end chargers[charger.id] = nil -- else -- log "Abnormal destruction... what shall we do?" end end end local function on_player_rotated_charger(event) local interface = event.entity if interface.name ~= "charge_transmission-charger_interface" then return end local player = game.players[event.player_index] -- print("rotated charger "..charger.unit_number) local charger_entity = interface.surface.find_entity("charge_transmission-charger", interface.position) local charger = (charger_entity and chargers[charger_entity.unit_number]) or nil -- require a charger with a valid target if not (charger_entity and charger and charger.target and charger.target.valid) then return end -- get all possible targets, under a node or not local cells = table.filter(charger.target.logistic_network.cells, function(cell) return cell.is_in_logistic_range(charger.base.position) end) -- quit if empty list if not next(cells) then return end -- get the next target if not charger.index or not cells[charger.index] then charger.index = next(cells) else charger.index = next(cells, charger.index) end -- avoid hitting the same current target (at least once) if charger.index and cells[charger.index].owner.unit_number == charger.target.owner.unit_number then charger.index = next(cells, charger.index) end -- rewind if there reached the end of the table (nil index) if not charger.index or not cells[charger.index] then charger.index = next(cells) end -- swap charger to the next "node" free_charger(charger) target_cell(charger, cells[charger.index]) -- update arrow player.set_gui_arrow{type="entity", entity=charger.target.owner} end local function on_dolly_moved_entity(event) --[[ player_index = player_index, --The index of the player who moved the entity moved_entity = entity, --The entity that was moved start_pos = position --The position that the entity was moved from --]] if event.moved_entity.name:find("charge_transmission%-charger") then if event.moved_entity.name ~= "charge_transmission-charger" then -- nuh huh, only the base can teleport, put that thing back where it came from, or so help me! event.moved_entity.teleport(event.start_pos) else -- move the rest of the composed entity local charger = chargers[event.moved_entity.unit_number] for _, component in pairs({charger.interface, charger.display}) do if component and component.valid then component.teleport(event.moved_entity.position) end end -- print("teleported charger "..charger.id) -- check if connected roboport is still within range if charger.target and not charger.target.is_in_logistic_range(event.moved_entity.position) then free_charger(charger, true) -- print("freed charger "..charger.id.." because out of reach") end end end end local function on_selected_entity_changed(event) local player = game.players[event.player_index] local current_entity = player.selected if current_entity and current_entity.name == "charge_transmission-charger_interface" then local charger_entity = current_entity.surface.find_entity("charge_transmission-charger", current_entity.position) local charger = (charger_entity and chargers[charger_entity.unit_number]) or nil if charger and charger.target and charger.target.valid then -- player.update_selected_entity(data.cell.owner.position) player.set_gui_arrow{type="entity", entity=charger.target.owner} end elseif event.last_entity and event.last_entity.name:match("charge_transmission%-charger") then player.clear_gui_arrow() end end -------------------------------------------------------------------------------- -- ON TICK -- -------------------------------------------------------------------------------- local function get_charger_consumption(charger) -- returns the consumption bonus/penalty from the charger if not constants.use_modules then return 1.5 else -- 300% max over 60 ticks (factor the 3 out) local consumption = (charger.base.effects and charger.base.effects.consumption and charger.base.effects.consumption.bonus or 0) * constants.distribution_effectivity return math.max(0.2, 1 + consumption) * 3 end end -- TODO: Hey so, consumption is general... can't you globalize it? and maybe even disperse the cost in real time? local function on_tick(event) --[[ Free Charger Reassignment (4c/s) ]] if event.tick%15 == 0 then if not free_chargers[counters.next_charger] then counters.next_charger = nil end local next_charger counters.next_charger, next_charger = next(free_chargers, counters.next_charger) if next_charger then if next_charger.base.valid then if pair_charger(next_charger) then free_chargers[next_charger.id] = nil end else free_chargers[next_charger.id] = nil end end end --[[ Robot Recharging (25?r/10??/tick) ]] local total_robots = constants.robots_limit local step = math.ceil(#active_nodes/constants.nodes_interval) local n_start = #active_nodes - ((event.tick % constants.nodes_interval) * step) local n_stop = n_start - step + 1 for n = n_start, math.max(1, n_stop), -1 do if total_robots <= 0 then goto end_bots end local node = nodes[active_nodes[n]] if node and node.active and node.cell.valid then local beam_position = constants.have_beams and node.cell.owner.position local surface = node.cell.owner.surface local force = node.cell.owner.force.name local bots = node.cell.to_charge_robots for _, bot in pairs(bots) do node.cost = node.cost - bot.energy bot.energy = math.huge node.cost = node.cost + bot.energy bot.force = force -- setting's a bot force (even its own!) makes it recheck its AI total_robots = total_robots - 1 if node.cost >= node.energy then bot.energy = bot.energy - (node.cost - node.energy) -- recoup extra spent energy node.cost = node.energy node.active = false active_nodes[n] = active_nodes[#active_nodes] active_nodes[#active_nodes] = nil break elseif beam_position then surface.create_entity { name = "charge_transmission-beam", position = beam_position, source_position = beam_position, target = bot, duration = 20, } end if total_robots < 1 then goto end_bots end end else if node then node.active = false -- print("deactivated node "..node.id) end active_nodes[n] = active_nodes[#active_nodes] active_nodes[#active_nodes] = nil end end ::end_bots:: --[[ Node Updating (n%60/tick) ]] local tick_nodes = hashed_nodes[event.tick%60] if not tick_nodes then hashed_nodes[event.tick%60] = {} tick_nodes = hashed_nodes[event.tick%60] end for i = #tick_nodes, 1, -1 do local node = tick_nodes[i] -- housecleaning (remove invalid node) if not(node and node.cell.valid and next(node.chargers)) then if node then -- remove node, orphan chargers for _, charger in pairs(node.chargers) do free_charger(charger, true) end if node.warning and node.warning.valid then node.warning.destroy() end node.active = false end nodes[node.id] = nil table.remove(tick_nodes, i) -- print("removed node "..node.id) else local energy = 0 local cost = 0 node.energy = node.energy or 0 node.cost = node.cost or 0 for key, charger in pairs(node.chargers) do if charger.base.valid and charger.interface.valid then -- set cost charger.interface.power_usage = 0 if node.energy > 0 then charger.interface.energy = charger.interface.energy - node.cost * ((charger.fraction or 0) / node.energy) cost = cost + node.cost * ((charger.fraction or 0) / node.energy) end -- reset charger charger.consumption = get_charger_consumption(charger) charger.fraction = charger.interface.energy energy = energy + charger.fraction / charger.consumption else node.chargers[key] = nil -- print("cleaned invalid charger "..key.." (== "..charger.id..") from node "..node.id) end end -- add the warning if necessary if (cost > 0 and not node.active) or (cost/(table_size(node.chargers)*60) > constants.input_flow_limit) then if not (node.warning and node.warning.valid) then node.warning = node.cell.owner.surface.create_entity { name = "charge_transmission-warning", position = node.cell.owner.position, } for _, player in pairs(node.cell.owner.force.players) do player.add_custom_alert(node.warning, {type="item", name="charge_transmission-warning"}, {"custom-alert.charge_transmission-overtaxed"}, true) end else for _, player in pairs(node.cell.owner.force.players) do player.remove_alert{entity=node.warning} player.add_custom_alert(node.warning, {type="item", name="charge_transmission-warning"}, {"custom-alert.charge_transmission-overtaxed"}, true) end end elseif node.warning then if node.warning.valid then node.warning.destroy() end node.warning = nil end -- reset the node for the next second node.energy = energy node.cost = 0 if not node.active and node.energy > 0 then table.insert(active_nodes, node.id) -- print("activated node "..node.id) node.active = true end end end end -------------------------------------------------------------------------------- -- EVENT HOOKS -- -------------------------------------------------------------------------------- Event.register(defines.events.on_built_entity, on_built_charger) .register(defines.events.on_robot_built_entity, on_built_charger) -- TODO: the function is kind of a misnomer now, isn't it Event.register(defines.events.on_entity_died, on_mined_charger) .register(defines.events.on_pre_player_mined_item, on_mined_charger) .register(defines.events.on_robot_pre_mined, on_mined_charger) -- TODO: these two should really be... moved upwards. Event.register(defines.events.on_player_rotated_entity, on_player_rotated_charger) Event.register(defines.events.on_selected_entity_changed, on_selected_entity_changed) script.on_event(defines.events.on_tick, on_tick) --############################################################################-- -- INIT/LOAD/CONFIG -- --############################################################################-- local function update_constants() global.constants = global.constants or {} constants = global.constants constants.distribution_effectivity = game.entity_prototypes["charge_transmission-charger"].distribution_effectivity constants.input_flow_limit = game.entity_prototypes["charge_transmission-charger_interface"].electric_energy_source_prototype.input_flow_limit constants.use_modules = settings.global["charge_transmission-use-modules"].value constants.have_beams = settings.global["charge_transmission-have-beams"].value constants.robots_limit = settings.global["charge_transmission-robots-per-tick"].value if constants.robots_limit == 0 then constants.robots_limit = math.huge end constants.nodes_interval = settings.global["charge_transmission-recharges-per-second"].value constants.nodes_interval = math.floor(60/constants.nodes_interval + 0.5) end local function init_global() global.nodes = {} global.active_nodes = {} global.hashed_nodes = {} global.chargers = {} global.free_chargers = {} global.counters = {} update_constants() global.changed = {} end local function on_load() --[[ setup metatables ]] --[[ subscribe conditional event handlers ]] -- Subscribe to Picker's Dolly event if remote.interfaces["picker"] and remote.interfaces["picker"]["dolly_moved_entity_id"] then script.on_event(remote.call("picker", "dolly_moved_entity_id"), on_dolly_moved_entity) end --[[ init local variables ]] nodes = global.nodes active_nodes = global.active_nodes hashed_nodes = global.hashed_nodes chargers = global.chargers free_chargers = global.free_chargers counters = global.counters constants = global.constants end script.on_init(function () init_global() -- Disable all past migrations for _, ver in pairs(MOD.migrations) do global.changed[ver] = true end on_load() end) script.on_load(on_load) script.on_event(defines.events.on_runtime_mod_setting_changed, function(event) if event.setting:match("^charge_transmission") then update_constants() end end) -------------------------------------------------------------------------------- -- MIGRATIONS -- -------------------------------------------------------------------------------- MOD.migrations = {"0.3.2", "0.5.0"} local Entity = require "stdlib/entity/entity" local migration_scripts = {} migration_scripts["0.3.2"] = function () -- remove is_charged global.is_charged = nil -- make all chargers follow the new spec local function reset_charger(charger) local transmitter = Entity.get_data(charger).transmitter if transmitter then transmitter.electric_input_flow_limit = transmitter.prototype.electric_energy_source_prototype.input_flow_limit end end for _, charger in pairs(global.unpaired) do reset_charger(charger) end for _, node in pairs(global.nodes) do for _, charger in pairs(node.chargers) do reset_charger(charger) end end log("CT 0.3.2 migration applied") return true end migration_scripts["0.5.0"] = function() -- clear global from previous variables global.unpaired = nil global.bot_max = nil -- initiate new ones global.nodes = {} global.active_nodes = {} global.hashed_nodes = {} global.chargers = {} global.free_chargers = {} global.counters = {} global.constants = {} -- init local variables nodes = global.nodes active_nodes = global.active_nodes hashed_nodes = global.hashed_nodes chargers = global.chargers free_chargers = global.free_chargers counters = global.counters constants = global.constants -- reform chargers for _, surface in pairs(game.surfaces) do local entities = surface.find_entities_filtered { name = "charge_transmission-charger" } for _, entity in pairs(entities) do on_built_charger({created_entity = entity}) end end log("CT 0.5.0 migration applied") return true end script.on_configuration_changed(function(event) if event.mod_changes["ChargeTransmission"] then if not global.changed then global.changed = {} end for _, ver in pairs(MOD.migrations) do if not global.changed[ver] and migration_scripts[ver](event) then global.changed[ver] = true end end end update_constants() end) --############################################################################-- -- INTERFACES/COMMANDS -- --############################################################################-- remote.add_interface(MOD.if_name, MOD.interfaces) for name, command in pairs(MOD.commands) do commands.add_command(name, {"command-help."..name}, command) end
local UTILS = require("nes.utils") local band, bor, bxor, bnot, lshift, rshift = bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift local map, rotatePositiveIdx, nthBitIsSet, nthBitIsSetInt = UTILS.map, UTILS.rotatePositiveIdx, UTILS.nthBitIsSet, UTILS.nthBitIsSetInt local Pad = nil local Pads = {} Pads._mt = {__index = Pads} function Pads:new(conf, cpu, apu) local pads = {} setmetatable(pads, Pads._mt) pads:initialize(conf, cpu, apu) return pads end function Pads:initialize(conf, cpu, apu) self.conf = conf self.cpu = cpu self.apu = apu self.pads = {Pad:new(), Pad:new()} end function Pads:reset() self.cpu:add_mappings(0x4016, UTILS.bind(self.peek_401x, self), UTILS.bind(self.poke_4016, self)) self.cpu:add_mappings(0x4017, UTILS.bind(self.peek_401x, self), UTILS.bind(self.apu.poke_4017, self.apu)) -- delegate 4017H to APU self.pads[1]:reset() self.pads[2]:reset() end function Pads:peek_401x(addr) self.cpu:update() return bor(self.pads[addr - 0x4016 + 1]:peek(), 0x40) end function Pads:poke_4016(_addr, data) self.pads[1]:poke(data) self.pads[2]:poke(data) end -- APIs function Pads:keydown(pad, btn) self.pads[pad].buttons = bor(self.pads[pad].buttons, lshift(1, btn)) end function Pads:keyup(pad, btn) self.pads[pad].buttons = band(self.pads[pad].buttons, bnot(lshift(1, btn))) end -- each pad Pad = UTILS.class() Pad.A = 0 Pad.B = 1 Pad.SELECT = 2 Pad.START = 3 Pad.UP = 4 Pad.DOWN = 5 Pad.LEFT = 6 Pad.RIGHT = 7 Pads.Pad = Pad function Pad:initialize() self:reset() end function Pad:reset() self.strobe = false self.buttons = 0 self.stream = 0 end function Pad:poke(data) local prev = self.strobe self.strobe = nthBitIsSetInt(data, 0) == 1 if prev and not self.strobe then self.stream = bxor(lshift(self:poll_state(), 1), -512) end end function Pad:peek() if self.strobe then return band(self:poll_state(), 1) end self.stream = rshift(self.stream, 1) return nthBitIsSetInt(self.stream, 0) end function Pad:poll_state() local state = self.buttons -- prohibit impossible simultaneous keydown (right and left, up and down) -- 0b00110000 if band(state, 0x30) == 0x30 then state = band(state, 0xff - 0x30) end --0b00111111 if band(state, 0xc0) == 0xc0 then state = band(state, 0xff - 0xc0) end return state end return Pads
local languages = {} languages.af = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring("&N<<<ʼn") return collator_obj end languages.am = function(collator_obj) collator_obj:reorder{ "ethiopic" } return collator_obj end languages.ar = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "arabic" } -- these are tailorings from "compat". standard tailorings are huge tailoring "&ت<<ة<<<ﺔ<<<ﺓ" tailoring "&ي<<ى<<<ﯨ<<<ﯩ<<<ﻰ<<<ﻯ<<<ﲐ<<<ﱝ" return collator_obj end languages.as = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "bengali","devanagari","gurmukhi","gujarati","oriya","tamil","telugu","kannada","malayalam","sinhala" } tailoring "&ঔ<ং<ঁ<ঃ" tailoring "&ত<ৎ=ত্\u{200D}" tailoring "&হ<ক্ষ" return collator_obj end languages.az = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "latin", "cyrillic" } tailoring "&C<ç<<<Ç" tailoring "&G<ğ<<<Ğ" tailoring "&i<ı<<<I" tailoring "&i<<<İ" tailoring "&O<ö<<<Ö" tailoring "&S<ş<<<Ş" tailoring "&U<ü<<<Ü" tailoring "&K<q<<<Q" tailoring "&E<ə<<<Ə" tailoring "&H<x<<<X" tailoring "&Z<w<<<W" return collator_obj end languages.be = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder {"cyrillic"} tailoring "&Е<ё<<<Ё" tailoring "&у<ў<<<Ў" return collator_obj end languages.bg = function(collator_obj) collator_obj:reorder {"cyrillic"} return collator_obj end languages.bn = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "bengali","devanagari","gurmukhi","gujarati","oriya","tamil","telugu","kannada","malayalam","sinhala" } tailoring "&ঔ<ং<ঃ<ঁ" return collator_obj end languages.bs = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder {"latin", "cyrillic"} tailoring "&C<č<<<Č<ć<<<Ć" tailoring "&D<dž<<<dž<<<Dž<<<Dž<<<DŽ<<<DŽ<đ<<<Đ" tailoring "&L<lj<<<lj<<<Lj<<<Lj<<<LJ<<<LJ" tailoring "&N<nj<<<nj<<<Nj<<<Nj<<<NJ<<<NJ" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž" return collator_obj end languages.bs_cyrl = function(collator_obj) collator_obj:reorder{ "cyrillic" } return collator_obj end languages.ca = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<ch<<<cH<<<Ch<<<CH" tailoring "&L<ll<<<l·l<<<lL<<<l·L<<<Ll<<<L·l<<<LL<<<L·L" return collator_obj end languages.chr = function(collator_obj) collator_obj:reorder {"cherokee"} return collator_obj end languages.cs = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&c<č<<<Č" tailoring "&h<ch<<<cH<<<Ch<<<CH" tailoring "&R<ř<<<Ř" tailoring "&s<š<<<Š" tailoring "&z<ž<<<Ž" collator_obj:reorder {"others", "digits"} return collator_obj end languages.cy = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<ch<<<Ch<<<CH" tailoring "&D<dd<<<Dd<<<DD" tailoring "&F<ff<<<Ff<<<FF" tailoring "&G<ng<<<Ng<<<NG" tailoring "&L<ll<<<Ll<<<LL" tailoring "&P<ph<<<Ph<<<PH" tailoring "&R<rh<<<Rh<<<RH" tailoring "&T<th<<<Th<<<TH" return collator_obj end languages.da = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:uppercase_first() tailoring("&D<<đ<<<Đ<<ð<<<Ð") tailoring("&th<<<þ") tailoring("&TH<<<Þ") tailoring("&Y<<ü<<<Ü<<ű<<<Ű") tailoring("&ǀ<æ<<<Æ<<ä<<<Ä<ø<<<Ø<<ö<<<Ö<<ő<<<Ő<å<<<Å<<<aa<<<Aa<<<AA") tailoring("&oe<<œ<<<Œ") return collator_obj end languages.de = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:uppercase_first() tailoring "&th<<<þ" tailoring "&TH<<<Þ" tailoring "&Y<<ƿ<<<Ƿ<<ʒ<<<Ʒ<<<ᶾ" tailoring "&A<<ä<<<Ä<<ǟ<<<Ǟ<<á<<<Á<<à<<<À<<ă<<<Ă<<ắ<<<Ắ<<ằ<<<Ằ<<ẵ<<<Ẵ<<ẳ<<<Ẳ<<â<<<Â<<ấ<<<Ấ<<ầ<<<Ầ<<ẫ<<<Ẫ<<ẩ<<<Ẩ<<ǎ<<<Ǎ<<å<<<Å=Å<<ǻ<<<Ǻ<<ã<<<Ã<<ȧ<<<Ȧ<<ǡ<<<Ǡ<<ą<<<Ą<<ā<<<Ā<<ả<<<Ả<<ȁ<<<Ȁ<<ȃ<<<Ȃ<<ạ<<<Ạ<<ặ<<<Ặ<<ậ<<<Ậ<<ḁ<<<Ḁ<<ᷓ<<ᴀ<<ⱥ<<<Ⱥ<<ᶏ<<ɐ<<<Ɐ<<<ᵄ<<ɑ<<<Ɑ<<<ᵅ<<ᶐ<<ɒ<<<Ɒ<<<ᶛ" tailoring "&O<<ö<<<Ö<<ȫ<<<Ȫ<<ó<<<Ó<<ò<<<Ò<<ŏ<<<Ŏ<<ô<<<Ô<<ố<<<Ố<<ồ<<<Ồ<<ỗ<<<Ỗ<<ổ<<<Ổ<<ǒ<<<Ǒ<<ő<<<Ő<<õ<<<Õ<<ṍ<<<Ṍ<<ṏ<<<Ṏ<<ȭ<<<Ȭ<<ȯ<<<Ȯ<<ȱ<<<Ȱ<<ø<<<Ø<<ǿ<<<Ǿ<<ǫ<<<Ǫ<<ǭ<<<Ǭ<<ō<<<Ō<<ṓ<<<Ṓ<<ṑ<<<Ṑ<<ỏ<<<Ỏ<<ȍ<<<Ȍ<<ȏ<<<Ȏ<<ơ<<<Ơ<<ớ<<<Ớ<<ờ<<<Ờ<<ỡ<<<Ỡ<<ở<<<Ở<<ợ<<<Ợ<<ọ<<<Ọ<<ộ<<<Ộ<<ᴏ<<ᴑ<<ᴓ<<ɔ<<<Ɔ <<<ᵓ<<ᴐ<<ᴒ<<ᶗ<<ꝍ<<<Ꝍ<<ᴖ<<<ᵔ<<ᴗ<<<ᵕ<<ⱺ<<ɵ<<<Ɵ<<<ᶱ<<ꝋ<<<Ꝋ<<ɷ<<ȣ<<<Ȣ<<<ᴽ<<ᴕ " tailoring "&U<<ü<<<Ü<<ǘ<<<Ǘ<<ǜ<<<Ǜ<<ǚ<<<Ǚ<<ǖ<<<Ǖ<<ú<<<Ú<<ù<<<Ù<<ŭ<<<Ŭ<<û<<<Û<<ǔ<<<Ǔ<<ů<<<Ů<<ű<<<Ű<<ũ<<<Ũ<<ṹ<<<Ṹ<<ų<<<Ų<<ū<<<Ū<<ṻ<<<Ṻ<<ủ<<<Ủ<<ȕ<<<Ȕ<<ȗ<<<Ȗ<<ư<<<Ư<<ứ<<<Ứ<<ừ<<<Ừ<<ữ<<<Ữ<<ử<<<Ử<<ự<<<Ự<<ụ<<<Ụ<<ṳ<<<Ṳ<<ṷ<<<Ṷ<<ṵ<<<Ṵ<<ᴜ<<<ᶸ<<ᴝ<<<ᵙ<<ᴞ<<ʉ<<<Ʉ<<<ᶶ<<ᵾ<<ᶙ<<ʊ<<<Ʊ<<<ᶷ<<ᵿ" return collator_obj end languages.de_din2 = function(collator_obj) local function tailor(a, b, tbl) local autf = collator_obj:string_to_codepoints(a) local butf = collator_obj:string_to_codepoints(b) collator_obj:tailor(autf,butf, tbl) end local tailoring = function(s) collator_obj:tailor_string(s) end languages.de(collator_obj) tailoring "&Ö=Oe" tailoring "&ö=oe" return collator_obj end languages.dsb = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<č<<<Č<ć<<<Ć" tailoring "&E<ě<<<Ě" tailoring "&H<ch<<<cH<<<Ch<<<CH" tailoring "&L<ł<<<Ł" tailoring "&N<ń<<<Ń" tailoring "&R<ŕ<<<Ŕ" tailoring "&S<š<<<Š<ś<<<Ś" tailoring "&Z<ž<<<Ž<ź<<<Ź" return collator_obj end languages.dz = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder {"tibetan"} -- tons of tailorings ommited return collator_obj end languages.ee = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&̌<<̂" tailoring "&D<dz<<<Dz<<<DZ<ɖ<<<Ɖ" tailoring "&E<ɛ<<<Ɛ" tailoring "&F<ƒ<<<Ƒ" tailoring "&G<gb<<<Gb<<<GB<ɣ<<<Ɣ" tailoring "&H<x<<<X" tailoring "&K<kp<<<Kp<<<KP" tailoring "&N<ny<<<Ny<<<NY<ŋ<<<Ŋ" tailoring "&O<ɔ<<<Ɔ" tailoring "&T<ts<<<Ts<<<TS" tailoring "&V<ʋ<<<Ʋ" return collator_obj end languages.el = function(collator_obj) collator_obj:reorder {"greek"} return collator_obj end languages.en = function(collator_obj) -- default sorting return collator_obj end languages.eo = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<ĉ<<<Ĉ" tailoring "&G<ĝ<<<Ĝ" tailoring "&H<ĥ<<<Ĥ" tailoring "&J<ĵ<<<Ĵ" tailoring "&S<ŝ<<<Ŝ" tailoring "&U<ŭ<<<Ŭ" return collator_obj end languages.es = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&N<ñ<<<Ñ" return collator_obj end languages.et = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&T<š<<<Š<z<<<Z<ž<<<Ž" tailoring "&X<õ<<<Õ<ä<<<Ä<ö<<<Ö<ü<<<Ü" return collator_obj end languages.fa = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&َ<<ِ<<ُ<<ً<<ٍ<<ٌ" tailoring "&ا<آ" tailoring "&ا<<ٱ<ء" tailoring "<<أ<<ٲ<<إ<<ٳ<<ؤ" tailoring "<<یٔ<<<ىٔ<<<ئ" tailoring "&ک<<*ڪګكڬڭڮ" tailoring "&ۏ<ه<<ە<<ہ<<ة<<ۃ<<ۀ<<ھ" tailoring "&ی<<*ىےيېۑۍێ" return collator_obj end languages.fi = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D\u{0335}<<đ<<<Đ" tailoring "&G\u{0335}<<ǥ<<<Ǥ" tailoring "&N\u{0335}<<ŋ<<<Ŋ" tailoring "&T\u{0335}<<ŧ<<<Ŧ" tailoring "&Y<<ü<<<Ü" tailoring "&Z\u{0335}<<ʒ<<<Ʒ" tailoring "&ǀ<å<<<Å<ä<<<Ä<<æ<<<Æ<ö<<<Ö<<ø<<<Ø" return collator_obj end languages.fil = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&N<ñ<<<Ñ<ng<<<Ng<<<NG" return collator_obj end languages.fo = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D<<đ<<<Đ<<ð<<<Ð" tailoring "&t<<<þ/h" tailoring "&T<<<Þ/H" tailoring "&Y<<ü<<<Ü<<ű<<<Ű" tailoring "&ǀ<æ<<<Æ<<ä<<<Ä<<ę<<<Ę<ø<<<Ø<<ö<<<Ö<<ő<<<Ő<<œ<<<Œ<å<<<Å<<<aa<<<Aa<<<AA" end languages.fr = function(collator_obj) -- French uses default sorting rules by default return collator_obj end languages.fr_backward_accents = function(collator_obj) -- alternative sorting for Cannadian French -- reverse search for accents in French: collator_obj.accents_backward = true -- accents: sorting order in French local tailoring = function(s) collator_obj:tailor_string(s) end tailoring("&a<<à<<â") tailoring("&e<<é<<è<<ê<<ë") tailoring("&i<<î<<ï") tailoring("&o<<ô<<ö") tailoring("&u<<ù<<û<<ü") tailoring("&y<<ÿ") tailoring("&ae<æ<<<Æ") tailoring("&oe<œ<<<Œ") tailoring("&th<þ<<<Þ") -- Canadian, see SGQRI004.pdf -- lowercase before uppercase in French --collator_obj:uppercase_first() return collator_obj end languages.ga = function(collator_obj) return collator_obj end languages.gl = languages.es languages.gu = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"gujarati","devanagari", "bengali", "gurmukhi","oriya","tamil","telugu","kannada","malayalam","sinhala" } tailoring "&ૐ<ં<<ઁ<ઃ" return collator_obj end languages.ha = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&B<ɓ<<<Ɓ" tailoring "&D<ɗ<<<Ɗ" tailoring "&K<ƙ<<<Ƙ" tailoring "&S<sh<<<Sh<<<SH" tailoring "&T<ts<<<Ts<<<TS" tailoring "&Y<ƴ<<<ʼy<<<''y<<<Ƴ<<<ʼY<<<''Y" return collator_obj end languages.haw = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&a<e<<<E<i<<<I<o<<<O<u<<<U" tailoring "&w<ʻ" return collator_obj end languages.he = function(collator_obj) collator_obj:reorder{"hebrew"} return collator_obj end languages.hr = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder {"latin", "cyrillic"} tailoring "&C<č<<<Č<ć<<<Ć" tailoring "&D<dž<<<dž<<<Dž<<<Dž<<<DŽ<<<DŽ<đ<<<Đ" tailoring "&L<lj<<<lj<<<Lj<<<Lj<<<LJ<<<LJ" tailoring "&N<nj<<<nj<<<Nj<<<Nj<<<NJ<<<NJ" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž" return collator_obj end languages.hi = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "bengali","devanagari","gurmukhi","gujarati","oriya","tamil","telugu","kannada","malayalam","sinhala" } tailoring "&ॐ<ं<<ँ<ः" return collator_obj end languages.hsb = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<č<<<Č<ć<<<Ć" tailoring "&E<ě<<<Ě" tailoring "&H<ch<<<cH<<<Ch<<<CH" tailoring "&L<ł<<<Ł" tailoring "&R<ř<<<Ř" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž<ź<<<Ź" return collator_obj end languages.hu = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<cs<<<Cs<<<CS" tailoring "&D<dz<<<Dz<<<DZ" tailoring "&DZ<dzs<<<Dzs<<<DZS" tailoring "&G<gy<<<Gy<<<GY" tailoring "&L<ly<<<Ly<<<LY" tailoring "&N<ny<<<Ny<<<NY" tailoring "&S<sz<<<Sz<<<SZ" tailoring "&T<ty<<<Ty<<<TY" tailoring "&Z<zs<<<Zs<<<ZS" tailoring "&O<ö<<<Ö<<ő<<<Ő" tailoring "&U<ü<<<Ü<<ű<<<Ű" tailoring "&cs<<<ccs/cs" tailoring "&Cs<<<Ccs/cs" tailoring "&CS<<<CCS/CS" tailoring "&dz<<<ddz/dz" tailoring "&Dz<<<Ddz/dz" tailoring "&DZ<<<DDZ/DZ" tailoring "&dzs<<<ddzs/dzs" tailoring "&Dzs<<<Ddzs/dzs" tailoring "&DZS<<<DDZS/DZS" tailoring "&gy<<<ggy/gy" tailoring "&Gy<<<Ggy/gy" tailoring "&GY<<<GGY/GY" tailoring "&ly<<<lly/ly" tailoring "&Ly<<<Lly/ly" tailoring "&LY<<<LLY/LY" tailoring "&ny<<<nny/ny" tailoring "&Ny<<<Nny/ny" tailoring "&NY<<<NNY/NY" tailoring "&sz<<<ssz/sz" tailoring "&Sz<<<Ssz/sz" tailoring "&SZ<<<SSZ/SZ" tailoring "&ty<<<tty/ty" tailoring "&Ty<<<Tty/ty" tailoring "&TY<<<TTY/TY" tailoring "&zs<<<zzs/zs" tailoring "&Zs<<<Zzs/zs" tailoring "&ZS<<<ZZS/ZS" return collator_obj end languages.hy = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder {"armenian"} tailoring "&ք<և<<<Եւ" return collator_obj end languages.id = function(collator_obj) return collator_obj end languages.ig = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&B<ch<<<Ch<<<CH" tailoring "&G<gb<<<Gb<<<GB<gh<<<Gh<<<GH<gw<<<Gw<<<GW" tailoring "&I<ị<<<Ị" tailoring "&K<kp<<<Kp<<<KP<kw<<<Kw<<<KW" tailoring "&N<ṅ<<<Ṅ<nw<<<Nw<<<NW<ny<<<Ny<<<NY" tailoring "&O<ọ<<<Ọ" tailoring "&S<sh<<<Sh<<<SH" tailoring "&U<ụ<<<Ụ" return collator_obj end languages.is = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&b<á<<<Á" tailoring "&d<<đ<<<Đ<ð<<<Ð" tailoring "&f<é<<<É" tailoring "&j<í<<<Í" tailoring "&p<ó<<<Ó" tailoring "&v<ú<<<Ú" tailoring "&z<ý<<<Ý" tailoring "&ǀ<æ<<<Æ<<ä<<<Ä<ö<<<Ö<<ø<<<Ø<å<<<Å" return collator_obj end languages.it = function(collator_obj) return collator_obj end languages.ja = function(collator_obj) collator_obj:reorder{"latin", "kana", "han"} -- tons of tailorings ommited return collator_obj end languages.ka = function(collator_obj) collator_obj:reorder{"georgian"} return collator_obj end languages.kk = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "cyrillic" } tailoring "&Е<ё<<<Ё" tailoring "&Ұ<ү<<<Ү" tailoring "&ь<і<<<І" return collator_obj end languages.kl = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D<<đ<<<Đ<<ð<<<Ð" tailoring "&Q<<ĸ<<<K''" tailoring "&t<<<þ/h" tailoring "&T<<<Þ/H" tailoring "&Y<<ü<<<Ü<<ű<<<Ű" tailoring "&ǀ<æ<<<Æ<<ä<<<Ä<<ę<<<Ę<ø<<<Ø<<ö<<<Ö<<ő<<<Ő<<œ<<<Œ<å<<<Å" return collator_obj end languages.km = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "khmer" } tailoring "&។ល។<<<៘" tailoring "&ៈ<<៎<<៏<<៑<<័<<ៈ<<៝<<់<<៉<<៊<<៍" tailoring "&រ<ឫ<ឬ" tailoring "&ល<ឭ<ឮ" tailoring "&រ្ក<<ក៌" tailoring "&រ្ខ<<ខ៌" tailoring "&រ្គ<<គ៌" tailoring "&រ្ឃ<<ឃ៌" tailoring "&រ្ង<<ង៌" tailoring "&រ្ច<<ច៌" tailoring "&រ្ឆ<<ឆ៌" tailoring "&រ្ជ<<ជ៌" tailoring "&រ្ឈ<<ឈ៌" tailoring "&រ្ញ<<ញ៌" tailoring "&រ្ដ<<ដ៌" tailoring "&រ្ឋ<<ឋ៌" tailoring "&រ្ឌ<<ឌ៌" tailoring "&រ្ឍ<<ឍ៌" tailoring "&រ្ណ<<ណ៌" tailoring "&រ្ត<<ត៌" tailoring "&រ្ថ<<ថ៌" tailoring "&រ្ទ<<ទ៌" tailoring "&រ្ធ<<ធ៌" tailoring "&រ្ន<<ន៌" tailoring "&រ្ប<<ប៌" tailoring "&រ្ផ<<ផ៌" tailoring "&រ្ព<<ព៌" tailoring "&រ្ភ<<ភ៌" tailoring "&រ្ម<<ម៌" tailoring "&រ្យ<<យ៌" tailoring "&រ្រ<<រ៌" tailoring "&រ្ឫ<<ឫ៌" tailoring "&រ្ឬ<<ឬ៌" tailoring "&រ្ល<<ល៌" tailoring "&រ្ឭ<<ឭ៌" tailoring "&រ្ឮ<<ឮ៌" tailoring "&រ្វ<<វ៌" tailoring "&រ្ឝ<<ឝ៌" tailoring "&រ្ឞ<<ឞ៌" tailoring "&រ្ស<<ស៌" tailoring "&រ្ហ<<ហ៌" tailoring "&រ្ឡ<<ឡ៌" tailoring "&រ្អ<<អ៌=ឣ៌" tailoring "&អ=ឣ" tailoring "&អា=ឤ" tailoring "&អិ<<ឥ" tailoring "&អី<<ឦ" tailoring "&អុ<<ឧ" tailoring "&អូ<<ឩ" tailoring "&អែ<<ឯ" tailoring "&អៃ<<ឰ" tailoring "&អោ<<ឱ" tailoring "&អៅ<<ឳ" tailoring "&ឧក<<<ឨ" tailoring "&ឩវ<<<ឪ" tailoring "&ឱ<<<ឲ" tailoring "&ៅ<ុំ<ំ<ាំ<ះ<ិះ<ុះ<េះ<ោះ" return collator_obj end languages.kn = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"kannada","devanagari", "bengali", "gurmukhi","gujarati","oriya","tamil","telugu","malayalam","sinhala" } tailoring "&ಔ<ಂ<ಃ<ೱ<ೲ" return collator_obj end languages.ko = function(collator_obj) -- this is pretty incomplete, there are tons of tailorings in the xml file -- we will support them maybe in the future collator_obj:reorder{"hangul", "han"} return collator_obj end languages.kok = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"devanagari", "bengali", "gurmukhi","gujarati","oriya","tamil","telugu","kannada","malayalam","sinhala" } tailoring "&ॐ<ं<<ँ<ः" tailoring "&ह<ळ" tailoring "<क्ष" return collator_obj end languages.ky = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "cyrillic" } tailoring "&е<ё<<<Ё" return collator_obj end languages.lb = function(collator_obj) return collator_obj end languages.lkt = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<č<<<Č" tailoring "&G<ǧ<<<Ǧ" tailoring "&H<ȟ<<<Ȟ" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž" return collator_obj end languages.ln = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&E<ɛ<<<Ɛ" tailoring "&O<<ɔ<<<Ɔ" return collator_obj end languages.lo = function(collator_obj) collator_obj:reorder{ "lao" } return collator_obj end languages.lt = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&̀=̇̀" tailoring "&́=̇́" tailoring "&̃=̇̃" tailoring "&A<<ą<<<Ą" tailoring "&C<č<<<Č" tailoring "&E<<ę<<<Ę<<ė<<<Ė" tailoring "&I<<į<<<Į<<y<<<Y" tailoring "&S<š<<<Š" tailoring "&U<<ų<<<Ų<<ū<<<Ū" tailoring "&Z<ž<<<Ž" return collator_obj end languages.lv = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D<č<<<Č" tailoring "&H<ģ<<<Ģ" tailoring "&I<<y<<<Y" tailoring "&L<ķ<<<Ķ" tailoring "&M<ļ<<<Ļ" tailoring "&O<ņ<<<Ņ" tailoring "&S<ŗ<<<Ŗ" tailoring "&T<š<<<Š" tailoring "&Ʒ<ž<<<Ž" return collator_obj end languages.mk = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{ "cyrillic" } tailoring "&ԃ<ѓ<<<Ѓ" tailoring "&ћ<ќ<<<Ќ" return collator_obj end languages.ml = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"malayalam","latin", "devanagari", "arabic","tamil", "kannada", "telugu", "bengali", "gurmukhi","gujarati","oriya","sinhala" } tailoring "&ഃ<<ഽ" tailoring "&\u{0D4C}<<\u{0D57}" tailoring "&ക്<<ക്\u{200D}<<<ൿ" tailoring "&ണ്<<ണ്\u{200D}<<<ൺ" tailoring "&ന്<<ന്\u{200D}<<<ൻ" tailoring "&ര്<<ര്\u{200D}<<<ർ" tailoring "&ല്<<ല്\u{200D}<<<ൽ" tailoring "&ള്<<ള്\u{200D}<<<ൾ" tailoring "&മ്<<ം" tailoring "&ന്<<<ൻ്" return collator_obj end languages.mn = function(collator_obj) collator_obj:reorder{ "cyrillic", "mongolian" } return collator_obj end languages.mr = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"devanagari", "bengali", "gurmukhi", "gujarati", "oriya", "tamil", "telugu", "kannada", "malayalam", "sinhala"} tailoring "&ॐ<ं<<ँ<ः" tailoring "&ह<ळ" tailoring "<क्ष" tailoring "<ज्ञ" return collator_obj end languages.ms = function(collator_obj) return collator_obj end languages.mt = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:uppercase_first() tailoring "&c<ċ<<<Ċ" tailoring "&g<ġ<<<Ġ" tailoring "&h<għ<<<gĦ<<<Għ<<<GĦ" tailoring "&i<ħ<<<Ħ" tailoring "&z<ż<<<Ż" return collator_obj end languages.my = function(collator_obj) -- there are tons of tailoring in the xml file, at the moment we just reorder collator_obj:reorder{ "myanmar" } return collator_obj end languages.nb = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D<<đ<<<Đ<<ð<<<Ð" tailoring "&t<<<þ/h" tailoring "&T<<<Þ/H" tailoring "&Y<<ü<<<Ü<<ű<<<Ű" tailoring "&ǀ<æ<<<Æ<<ä<<<Ä<<ę<<<Ę<ø<<<Ø<<ö<<<Ö<<ő<<<Ő<<œ<<<Œ<å<<<Å<<aa<<<Aa<<<AA" return collator_obj end languages.ne = function(collator_obj) collator_obj:reorder{ "devanagari" } return collator_obj end languages.nl = function(collator_obj) return collator_obj end -- languages.nn = languages.nb languages.no = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:uppercase_first() tailoring("&D<<đ<<<Đ<<ð<<<Ð") tailoring("&th<<<þ") tailoring("&TH<<<Þ") tailoring("&Y<<ü<<<Ü<<ű<<<Ű") tailoring("&ǀ<æ<<<Æ<<ä<<<Ä<ø<<<Ø<<ö<<<Ö<<ő<<<Ő<å<<<Å<<<aa<<<Aa<<<AA") tailoring("&oe<<œ<<<Œ") return collator_obj end languages.om = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&Z<ch<<<Ch<<<CH<dh<<<Dh<<<DH<kh<<<Kh<<<KH<ny<<<Ny<<<NY<ph<<<Ph<<<PH<sh<<<Sh" return collator_obj end languages["or"] = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"oriya", "devanagari", "bengali", "gurmukhi", "gujarati", "tamil", "telugu", "kannada", "malayalam", "sinhala"} tailoring "&ଔ<ଁ<ଂ<ଃ" tailoring "&ହ<କ୍ଷ" tailoring "&ଯ<<ୟ" return collator_obj end languages.pa = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"gurmukhi", "devanagari", "bengali", "gujarati", "oriya", "tamil", "telugu", "kannada", "malayalam", "sinhala", "arabic"} tailoring "&ੱ<<ੰ<<ਂ<<ਁ<<਼" tailoring "&ੜ<੍" return collator_obj end languages.pl = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&A<ą<<<Ą" tailoring "&C<ć<<<Ć" tailoring "&E<ę<<<Ę" tailoring "&L<ł<<<Ł" tailoring "&N<ń<<<Ń" tailoring "&O<ó<<<Ó" tailoring "&S<ś<<<Ś" tailoring "&Z<ź<<<Ź<ż<<<Ż" return collator_obj end languages.ps = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"arabic"} tailoring "&َ<<ِ<<ُ<<ً<<ٍ<<ٌ" tailoring "&ا<آ" tailoring "&ا<<أ<<ٲ<<ٱ<<إ<<ٳ<ء" tailoring "&ت<ټ<<ٹ" tailoring "&ج<ځ<<حٔ" tailoring "&چ<څ" tailoring "&د<ډ<<ڈ" tailoring "&ر<ړ<<ڑ" tailoring "&ژ<ږ" tailoring "&ک<<*ڪك" tailoring "&ګ<<گ" tailoring "&ڼ<<ڻ" tailoring "&و<<ؤ<<ۇ<<ۉ" tailoring "&ه<<<ۀ<<<هٔ<<*ەہھةۃ" tailoring "&ی<<*ىےيېۍ<<یٔ<<<ىٔ<<<ئ" tailoring "&\u{00A0}<<\u{200C}<<\u{200D}" return collator_obj end languages.pt = function(collator_obj) return collator_obj end languages.ro = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&A<ă<<<Ă<â<<<Â" tailoring "&I<î<<<Î" tailoring "&S<ş=ș<<<Ş=Ș" tailoring "&T<ţ=ț<<<Ţ=Ț" return collator_obj end languages.ru = function(collator_obj) collator_obj:reorder{ "cyrillic" } return collator_obj end languages.se = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&b<á<<<Á" tailoring "&d<č<<<Č<ʒ<<<Ʒ<ǯ<<<Ǯ" tailoring "&e<đ<<<Đ<<ð<<<Ð" tailoring "&h<ǧ<<<Ǧ<ǥ<<<Ǥ" tailoring "&l<ǩ<<<Ǩ" tailoring "&o<ŋ<<<Ŋ<<ń<<<Ń<<ñ<<<Ñ" tailoring "&t<š<<<Š" tailoring "&u<ŧ<<<Ŧ<<þ<<<Þ" tailoring "&y<<ü<<<Ü<<ű<<<Ű" tailoring "&ǀ<ž<<<Ž<ø<<<Ø<<œ<<<Œ<æ<<<Æ<å<<<Å<<ȧ<<<Ȧ<ä<<<Ä<<ã<<<Ã<ö<<<Ö<<ő<<<Ő<<õ<<<Õ<<ô<<<Ô<<ǫ<<<Ǫ" return collator_obj end languages.si = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"sinhala","devanagari", "bengali", "gurmukhi", "gujarati", "oriya", "tamil", "telugu", "kannada", "malayalam"} tailoring "&ඖ<ං<ඃ" tailoring "&ඥ<ඤ" return collator_obj end languages.sk = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&A<ä<<<Ä" tailoring "&C<č<<<Č" tailoring "&H<ch<<<cH<<<Ch<<<CH" tailoring "&O<ô<<<Ô" tailoring "&R<ř<<<Ř" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž" return collator_obj end languages.sl = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<č<<<Č" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž" return collator_obj end languages.smn = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&A<â<<<Â<<à<<<À" tailoring "&C<č<<<Č" tailoring "&D<đ<<<Đ" tailoring "&Ŋ<<ñ<<<Ñ<<ń<<<Ń" tailoring "&S<š<<<Š" tailoring "&Z<ž<<<Ž<æ<<<Æ<ø<<<Ø<å<<<Å<ã<<<Ã<ä<<<Ä<á<<<Á<ö<<<Ö" return collator_obj end languages.sq = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D<ç<<<Ç" tailoring "&E<dh<<<Dh<<<DH" tailoring "&F<ë<<<Ë" tailoring "&H<gj<<<Gj<<<GJ" tailoring "&M<ll<<<Ll<<<LL" tailoring "&O<nj<<<Nj<<<NJ" tailoring "&S<rr<<<Rr<<<RR" tailoring "&T<sh<<<Sh<<<SH" tailoring "&U<th<<<Th<<<TH" tailoring "&Y<xh<<<Xh<<<XH" tailoring "&Ʒ<zh<<<Zh<<<ZH" return collator_obj end languages.sr = function(collator_obj) collator_obj:reorder{ "cyrillic" } return collator_obj end languages.sr_latn = languages.hr languages.sv = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&D<<đ<<<Đ<<ð<<<Ð" tailoring "&t<<<þ/h" tailoring "&T<<<Þ/H" tailoring "&v<<<V<<w<<<W" tailoring "&Y<<ü<<<Ü<<ű<<<Ű" tailoring "&ǀ<å<<<Å<ä<<<Ä<<æ<<<Æ<<ę<<<Ę<ö<<<Ö<<ø<<<Ø<<ő<<<Ő<<œ<<<Œ<<ô<<<Ô" return collator_obj end languages.sw = function(collator_obj) return collator_obj end languages.ta = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"tamil", "devanagari", "bengali", "gurmukhi", "gujarati", "oriya", "telugu", "kannada", "malayalam", "sinhala"} tailoring "&ஔ<ஂ<ஃ" tailoring "&ஹ<க்ஷ" tailoring "&க<க்" tailoring "&ங<ங்" tailoring "&ச<ச்" tailoring "&ஞ<ஞ்" tailoring "&ட<ட்" tailoring "&ண<ண்" tailoring "&த<த்" tailoring "&ந<ந்" tailoring "&ப<ப்" tailoring "&ம<ம்" tailoring "&ய<ய்" tailoring "&ர<ர்" tailoring "&ல<ல்" tailoring "&வ<வ்" tailoring "&ழ<ழ்" tailoring "&ள<ள்" tailoring "&ற<ற்" tailoring "&ன<ன்" tailoring "&ஜ<ஜ்" tailoring "&ஶ<ஶ்" tailoring "&ஷ<ஷ்" tailoring "&ஸ<ஸ்" tailoring "&ஹ<ஹ்" tailoring "&க்ஷ<க்ஷ்" return collator_obj end languages.te = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"telugu", "devanagari", "bengali", "gurmukhi", "gujarati", "oriya", "tamil", "kannada", "malayalam", "sinhala"} tailoring "&ఔ<ఁ<ం<ః" return collator_obj end languages.th = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"thai"} tailoring "&๚<ฯ" tailoring "&๛<ๆ" tailoring "&๎<<์" tailoring "&ะ<ํ" tailoring "&า<<<ๅ" tailoring "&าํ<<<ํา<<<ำ" tailoring "&ๅํ<<<ํๅ" tailoring "&ไ<ฺ" return collator_obj end languages.tk = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<ç<<<Ç" tailoring "&E<ä<<<Ä" tailoring "&J<ž<<<Ž" tailoring "&N<ň<<<Ň" tailoring "&O<ö<<<Ö" tailoring "&S<ş<<<Ş" tailoring "&U<ü<<<Ü" tailoring "&Y<ý<<<Ý" return collator_obj end languages.to = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&n<ng<<<Ng<<<NG<<<ŋ<<<Ŋ" tailoring "&z<ʻ<<<ʽ" tailoring "&a<<á<<<Á<<ā<<<Ā" tailoring "&e<<é<<<É<<ē<<<Ē" tailoring "&i<<í<<<Í<<ī<<<Ī" tailoring "&o<<ó<<<Ó<<ō<<<Ō" tailoring "&u<<ú<<<Ú<<ū<<<Ū" return collator_obj end languages.tr = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&C<ç<<<Ç" tailoring "&G<ğ<<<Ğ" tailoring "&i<ı<<<I" tailoring "&i<<<İ" tailoring "&O<ö<<<Ö" tailoring "&S<ş<<<Ş" tailoring "&U<ü<<<Ü" return collator_obj end languages.ug = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"arabic"} tailoring "&ا<ە<ب" tailoring "&ك<گ<ڭ<ل" tailoring "&ھ<و<ۇ<ۆ<ۈ<ۋ<ې<ى<ي" return collator_obj end languages.uk = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"cyrillic"} tailoring "&Г<ґ<<<Ґ" tailoring "&ꙇ<ї<<<\u{A676}<<<Ї" return collator_obj end languages.ur = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"arabic"} tailoring "&ا<<أ<آ<ب<بھ<پ<پھ<ت<تھ<ٹ<ٹھ<ث<ج<جھ<چ<چھ<ح<خ<د<دھ<ڈ<ڈھ<ذ<ر<رھ<ڑ<ڑھ<ز<ژ<س<ش<ص<ض<ط<ظ <ع<غ<ف<ق<ک<کھ<گ<گھ<ل<لھ<م<مھ<ن<نھ<ں<ںھ<و<<ؤ<وھ<ہ<<ۂ<ھ<ۃ<ء<ی<<ئ<یھ<ے<<ۓ" tailoring "&\u{0652}<<\u{064E}<<\u{0650}<<\u{064F}<<\u{0670}<<\u{0656}<<\u{0657}<<\u{064B}<<\u{064D}<<\u{064C}<<\u{0654}<<\u{0651}<<\u{0658}<<\u{0653}" tailoring "&<<<\u{0610}<<<\u{0611}<<<\u{0613}<<<\u{0612}<<<\u{0614}" return collator_obj end languages.uz = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&[before 1]ʒ<oʻ=o‘=o''<<<Oʻ=O‘=O''" tailoring "<gʻ=g‘=g''<<<Gʻ=G‘=G''" tailoring "<sh<<<Sh<<<SH" tailoring "<ch<<<Ch<<<CH" return collator_obj end languages.vi = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&̀<<̉<<̃<<́<<̣" tailoring "&a<ă<<<Ă<â<<<Â" tailoring "&d<đ<<<Đ" tailoring "&e<ê<<<Ê" tailoring "&o<ô<<<Ô<ơ<<<Ơ" tailoring "&u<ư<<<Ư" return collator_obj end languages.vo = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&A<ä<<<Ä" tailoring "&O<ö<<<Ö" tailoring "&U<ü<<<Ü" return collator_obj end languages.wae = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&á=aa" tailoring "&ã=ää" tailoring "&é=ee" tailoring "&í=ii" tailoring "&ó=oo" tailoring "&õ=öö" tailoring "&č=ch" tailoring "&š=sch" tailoring "&ú=uu" tailoring "&ũ=üü" return collator_obj end languages.wo = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&A<à<<<À" tailoring "&E<é<<<É<ë<<<Ë" tailoring "&N<ñ<<<Ñ<ŋ<<<Ŋ" tailoring "&O<ó<<<Ó" return collator_obj end languages.yi = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"hebrew"} tailoring "&''<<׳" tailoring "&'\"'<<״" tailoring "&ב<בֿ" tailoring "&ו<<וּ<<וו<<וי" tailoring "&י<<יִ<<יי<<ײַ" tailoring "&כ<כּ" tailoring "&פ<פּ" tailoring "&פֿ<<<ף" tailoring "&ש<שׂ" tailoring "&ת<תּ" return collator_obj end languages.yo = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end tailoring "&E<ẹ<<<Ẹ" tailoring "&G<gb<<<Gb<<<GB" tailoring "&O<ọ<<<Ọ" tailoring "&S<ṣ<<<Ṣ" return collator_obj end languages.zj = function(collator_obj) local tailoring = function(s) collator_obj:tailor_string(s) end collator_obj:reorder{"han"} -- tons of tailorings ommited return collator_obj end languages.zu = function(collator_obj) return collator_obj end return languages
test_run = require('test_run').new() REPLICASET_1 = { 'box_1_a', 'box_1_b' } REPLICASET_2 = { 'box_2_a', 'box_2_b' } engine = test_run:get_cfg('engine') test_run:create_cluster(REPLICASET_1, 'rebalancer') test_run:create_cluster(REPLICASET_2, 'rebalancer') util = require('util') test_run:wait_fullmesh(REPLICASET_1) test_run:wait_fullmesh(REPLICASET_2) util.map_evals(test_run, {REPLICASET_1, REPLICASET_2}, 'bootstrap_storage(\'%s\')', engine) -- -- Test configuration: two replicasets. Rebalancer, according to -- its implementation, works on a master with the smallest UUID - -- here it is the box_1_a server. -- Test follows the plan: -- 1) Check the rebalancer does nothing until a cluster is -- bootstraped; -- 2) Rebalance slightly disbalanced cluster (send buckets from a -- rebalancer host); -- 3) Same as 2, but send buckets to a rebalancer host; -- 4) Multiple times rebalanced cluster must became stable and -- balanced after a time; -- 5) Rebalancer can be turned off; -- 6) Rebalancer can not start next rebalancing session, if a -- previous one is not finished yet; -- 7) Garbage collector cleans sent buckets; -- 8) Rebalancer can be moved to another master, if a -- configuration has changed. -- test_run:switch('box_1_a') _bucket = box.space._bucket vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) -- -- Test the rebalancer on not bootstraped cluster. -- (See point (1) in the test plan) -- wait_rebalancer_state('Total active bucket count is not equal to total', test_run) -- -- Fill the cluster with buckets saving the balance 100 buckets -- per replicaset. -- vshard.storage.rebalancer_disable() cfg.rebalancer_max_receiving = 10 vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) for i = 1, 100 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end test_run:switch('box_2_a') _bucket = box.space._bucket for i = 101, 200 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end test_run:switch('box_1_a') vshard.storage.rebalancer_enable() wait_rebalancer_state("The cluster is balanced ok", test_run) -- -- Send buckets to create a disbalance. Wait until the rebalancer -- repairs it. (See point (2) in the test plan) -- vshard.storage.rebalancer_disable() test_run:switch('box_2_a') for i = 1, 100 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end test_run:switch('box_1_a') _bucket:truncate() vshard.storage.rebalancer_enable() vshard.storage.rebalancer_wakeup() wait_rebalancer_state("Rebalance routes are sent", test_run) wait_rebalancer_state('The cluster is balanced ok', test_run) _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) test_run:switch('box_2_a') _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) -- -- Send buckets again, but now from a replicaset with no -- rebalancer. Since the rebalancer is global and single per -- cluster, it must detect disbalance. -- (See point (3) in the test plan) -- test_run:switch('box_1_a') -- Set threshold to 300% cfg.rebalancer_disbalance_threshold = 300 vshard.storage.rebalancer_disable() vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) for i = 101, 200 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end test_run:switch('box_2_a') _bucket:truncate() test_run:switch('box_1_a') -- The cluster is balanced with maximal disbalance = 100% < 300%, -- set above. vshard.storage.rebalancer_enable() wait_rebalancer_state('The cluster is balanced ok', test_run) _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) -- Return 1%. cfg.rebalancer_disbalance_threshold = 0.01 vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) wait_rebalancer_state('Rebalance routes are sent', test_run) wait_rebalancer_state('The cluster is balanced ok', test_run) _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:min({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:max({vshard.consts.BUCKET.ACTIVE}) test_run:switch('box_2_a') _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:min({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:max({vshard.consts.BUCKET.ACTIVE}) -- -- After multiple rebalancing a next rebalance must not change -- anything. -- (See point (4) in the test plan) -- test_run:switch('box_1_a') wait_rebalancer_state("The cluster is balanced ok", test_run) -- -- Test disabled rebalancer. -- (See point (5) in the test plan) -- vshard.storage.rebalancer_disable() wait_rebalancer_state("Rebalancer is disabled", test_run) -- -- Test rebalancer does noting if not all buckets are active or -- sent. -- (See point (6) in the test plan) -- vshard.storage.rebalancer_enable() _bucket:update({150}, {{'=', 2, vshard.consts.BUCKET.RECEIVING}}) wait_rebalancer_state("Some buckets are not active", test_run) _bucket:update({150}, {{'=', 2, vshard.consts.BUCKET.ACTIVE}}) -- -- Test garbage collector deletes sent buckets and their data. -- (See point (7) in the test plan) -- vshard.storage.rebalancer_disable() for i = 91, 100 do _bucket:replace{i, vshard.consts.BUCKET.ACTIVE} end space = box.space.test space:replace{1, 91} space:replace{2, 92} space:replace{3, 93} space:replace{4, 150} space:replace{5, 151} test_run:switch('box_2_a') space = box.space.test for i = 91, 100 do _bucket:delete{i} end test_run:switch('box_1_a') _bucket:get{91}.status vshard.storage.rebalancer_enable() vshard.storage.rebalancer_wakeup() -- -- Now rebalancer makes a bucket SENT. After it the garbage -- collector cleans it and deletes after a timeout. -- while _bucket:get{91}.status ~= vshard.consts.BUCKET.SENT do fiber.sleep(0.01) end while _bucket:get{91} ~= nil do fiber.sleep(0.1) end wait_rebalancer_state("The cluster is balanced ok", test_run) _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:min({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:max({vshard.consts.BUCKET.ACTIVE}) test_run:switch('box_2_a') _bucket.index.status:count({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:min({vshard.consts.BUCKET.ACTIVE}) _bucket.index.status:max({vshard.consts.BUCKET.ACTIVE}) space:select{} -- -- Test reconfiguration. On master change the rebalancer can move -- to a new location. -- (See point (8) in the test plan) -- cfg.rebalancer_max_receiving = 10 switch_rs1_master() vshard.storage.cfg(cfg, util.name_to_uuid.box_2_a) test_run:switch('box_1_a') switch_rs1_master() vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) test_run:switch('box_1_b') switch_rs1_master() vshard.storage.cfg(cfg, util.name_to_uuid.box_1_b) test_run:switch('box_2_b') switch_rs1_master() vshard.storage.cfg(cfg, util.name_to_uuid.box_2_b) while not test_run:grep_log('box_2_a', "rebalancer_f has been started") do fiber.sleep(0.1) end while not test_run:grep_log('box_1_a', "Rebalancer location has changed") do fiber.sleep(0.1) end -- -- gh-40: introduce custom replicaset weights. Weight allows to -- move all buckets out of replicaset with weight = 0. -- test_run:switch('box_1_a') nullify_rs_weight() vshard.storage.cfg(cfg, util.name_to_uuid.box_1_a) test_run:switch('box_1_b') nullify_rs_weight() vshard.storage.cfg(cfg, util.name_to_uuid.box_1_b) test_run:switch('box_2_b') nullify_rs_weight() vshard.storage.cfg(cfg, util.name_to_uuid.box_2_b) test_run:switch('box_2_a') nullify_rs_weight() vshard.storage.cfg(cfg, util.name_to_uuid.box_2_a) vshard.storage.rebalancer_wakeup() _bucket = box.space._bucket test_run:cmd("setopt delimiter ';'") while _bucket.index.status:count{vshard.consts.BUCKET.ACTIVE} ~= 200 do fiber.sleep(0.1) vshard.storage.rebalancer_wakeup() end; test_run:cmd("setopt delimiter ''"); -- gh-152: ensure that rebalancing is possible in case spaces -- have different ids on different replicasets. test_run:switch('box_1_a') box.space.test.id test_run:switch('box_2_a') box.space.test.id _ = test_run:cmd("switch default") test_run:drop_cluster(REPLICASET_2) test_run:drop_cluster(REPLICASET_1)
local localization = { ATT_STR_BUYER = "Käufer", ATT_STR_SELLER = "Verkäufer", ATT_STR_GUILD = "Gilde", ATT_STR_ITEM = "Gegenstand", ATT_STR_EAPRICE = "EP", ATT_STR_PRICE = "Preis", ATT_STR_TIME = "Zeit", ATT_STR_PURCHASES = "Einkäufe", ATT_STR_TODAY = "Heute", ATT_STR_YESTERDAY = "Gestern", ATT_STR_TWO_DAYS_AGO = "Vorgestern", ATT_STR_THIS_WEEK = "Diese Woche", ATT_STR_LAST_WEEK = "Letzte Woche", ATT_STR_PRIOR_WEEK = "Vorletzte Woche", ATT_STR_7_DAYS = "7 Tage", ATT_STR_10_DAYS = "10 Tage", ATT_STR_14_DAYS = "14 Tage", ATT_STR_30_DAYS = "30 Tage", ATT_STR_THIS_MONTH = "Diesen Monat", ATT_STR_LAST_MONTH = "Letzten Monat", ATT_STR_PRIOR_MONTH = "Vorletzter Monat", ATT_STR_ALL_TIME = "Alle Zeit", ATT_STR_KEEP_PURCHASES_FOR_DAYS = "Behalte Einkäufe für x Tage", ATT_STR_FILTER_TEXT_TOOLTIP = "Textsuche nach User-, Gilden- oder Gegenstandsnamen", ATT_STR_FILTER_SUBSTRING_TOOLTIP = "Schalte zwischen Suche nach exaktem String oder Teilstring um. Groß- und Kleinschreibung wird in beiden Fällen ignoriert.", ATT_STR_FILTER_COLUMN_TOOLTIP = "Schließe diese Spalte in die/von der Textsuche ein/aus", } ZO_ShallowTableCopy(localization, ArkadiusTradeTools.Modules.Purchases.Localization)
-- rPlayerFrame: config -- zork, 2019 ----------------------------- -- Variables ----------------------------- local A, L = ... ----------------------------- -- Config ----------------------------- L.C = { textureColor = {0.2,0.2,0.2,0.5}, frameVisibility = "[mod:shift][combat][@target,exists] show; hide", --fader via OnShow trigger fader = { fadeInAlpha = 1, fadeInDuration = 0.3, fadeInSmooth = "OUT", fadeOutAlpha = 0, fadeOutDuration = 0.9, fadeOutSmooth = "OUT", fadeOutDelay = 0, trigger = "OnShow", }, }
----------------------------------- -- Area: Upper Jeuno -- NPC: Shalott -- Optional Involvement in Quest: Save My Son -------------------------------- require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if (player:getQuestStatus(JEUNO, tpz.quest.id.jeuno.SAVE_MY_SON) == QUEST_ACCEPTED) then player:startEvent(101) else player:startEvent(104) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
--[[ -- added by wsh @ 2017-12-01 -- Class单元测试 --]] require "Framework.Common.DataClass" require "Framework.Common.ConstClass" local function TestBaseClassOverride() local var1 = 1 local class1 = BaseClass("class1") class1.__init = function(self) self.var1 = 1 end class1.func1 = function(self) var1 = var1 + 1 self.var1 = self.var1 + 1 assert(var1 == 2) assert(self.var1 == 2) end -- no override local class2 = BaseClass("class2", class1) local class3 = BaseClass("class3", class2) -- override class3.func1 = function(self) class2.func1(self) var1 = var1 + 1 self.var1 = self.var1 + 1 assert(var1 == 3) assert(self.var1 == 3) end -- no override local class4 = BaseClass("class4", class3) local class5 = BaseClass("class5", class4) -- override class5.func1 = function(self) class4.func1(self) var1 = var1 + 1 self.var1 = self.var1 + 1 assert(var1 == 4) assert(self.var1 == 4) end local inst1 = class5.New() inst1:func1() var1 = 1 local inst2 = class4.New() inst2:func1() end local function TestDataClass() local Data = DataClass("Data",{ number = 0, bool = false, string = "", table = {}, func = function() end, }) local inst1 = Data.New() assert(inst1.__cname == "Data") assert(inst1.number == 0) assert(inst1.bool == false) assert(inst1.string == "") assert(#inst1.table == 0) assert(inst1.func() == nil) inst1.number = 12 inst1.bool = true inst1.string = "string" inst1.table["name"] = "table" inst1.func = function() return 12 end assert(inst1.number == 12) assert(inst1.bool == true) assert(inst1.string == "string") assert(inst1.table["name"] == "table") assert(inst1.func() == 12) local inst2 = Data.New() assert(inst2.__cname == "Data") assert(inst2.number == 0) assert(inst2.bool == false) assert(inst2.string == "") assert(#inst2.table == 0) assert(inst2.func() == nil) inst2.number = 122 inst2.bool = false inst2.string = "string222" inst2.table["name"] = "table2222" inst2.func = function() return 122 end assert(inst1.number == 12) assert(inst1.bool == true) assert(inst1.string == "string") assert(inst1.table["name"] == "table") assert(inst1.func() == 12) assert(inst2.number == 122) assert(inst2.bool == false) assert(inst2.string == "string222") assert(inst2.table["name"] == "table2222") assert(inst2.func() == 122) end local function TestDataClassReadErr() local Data = DataClass("Data") Data.aaa = nil local inst1 = Data.New() local bbb = inst1.bbb end local function TestDataClassWriteErr() local Data = DataClass("Data") Data.aaa = nil local inst1 = Data.New() inst1.bbb = 11 end local function TestDataClassNew() local Data = DataClass("Data",{ number = 0, bool = false, string = "", table = {}, func = function() end, __init = function(self, number_value, bool_value, string_value, table_value, func_value) self.number = number_value self.bool = bool_value self.string = string_value self.table = table_value self.func = func_value end }) local tableTest = {1, 2} local funcTest = function() end local inst1 = Data.New(111, true, "111", tableTest, funcTest) assert(inst1.__cname == "Data") assert(inst1.number == 111) assert(inst1.bool == true) assert(inst1.string == "111") assert(inst1.table == tableTest) assert(inst1.table[1] == 1) assert(inst1.table[2] == 2) assert(inst1.func == funcTest) local Data2 = DataClass("Data2", nil, Data) local inst2 = Data2.New(222, true, "222", tableTest, funcTest) assert(inst2.__cname == "Data2") assert(inst2.number == 222) assert(inst2.bool == true) assert(inst2.string == "222") assert(inst2.table == tableTest) assert(inst2.table[1] == 1) assert(inst2.table[2] == 2) assert(inst2.func == funcTest) local Data3 = DataClass("Data3", {}, Data) local inst3 = Data3.New(333, true, "333", tableTest, funcTest) assert(inst3.__cname == "Data3") assert(inst3.number == 333) assert(inst3.bool == true) assert(inst3.string == "333") assert(inst3.table == tableTest) assert(inst3.table[1] == 1) assert(inst3.table[2] == 2) assert(inst3.func == funcTest) local Data4 = DataClass("Data4", { newAdd = "NewAdd", __init = function(self, number_value, bool_value, string_value, table_value, func_value, newAdd_value) self.newAdd = newAdd_value end }, Data) local inst4 = Data4.New(444, true, "444", tableTest, funcTest) assert(inst4.__cname == "Data4") assert(inst4.number == 444) assert(inst4.bool == true) assert(inst4.string == "444") assert(inst4.table == tableTest) assert(inst4.table[1] == 1) assert(inst4.table[2] == 2) assert(inst4.func == funcTest) assert(inst4.newAdd == false) local inst5 = Data4.New(555, true, "555", tableTest, funcTest, "inst5") assert(inst5.__cname == "Data4") assert(inst5.number == 555) assert(inst5.bool == true) assert(inst5.string == "555") assert(inst5.table == tableTest) assert(inst5.table[1] == 1) assert(inst5.table[2] == 2) assert(inst5.func == funcTest) assert(inst5.newAdd == "inst5") end local function TestConstClass() local Const = ConstClass("Const", { aaa = 1 }) assert(Const.__cname == "Const") assert(Const.aaa == 1) end local function TestConstClassWriteErr1() local Const = ConstClass("Const", { aaa = 1 }) Const.aaa = 2 end local function TestConstClassWriteErr2() local Const = ConstClass("Const", { aaa = 1 }) Const.bbb = 2 end local function TestConstClassReadErr() local Const = ConstClass("Const", { aaa = 1 }) local bbb= Const.bbb end local function Run() TestBaseClassOverride() TestDataClass() assert(pcall(TestDataClassReadErr) == false, "TestDataClassReadErr failed!") assert(pcall(TestDataClassWriteErr) == false, "TestDataClassWriteErr failed!") TestDataClassNew() TestConstClass() assert(pcall(TestConstClassWriteErr1) == false, "TestConstClassWriteErr1 failed!") assert(pcall(TestConstClassWriteErr2) == false, "TestConstClassWriteErr2 failed!") assert(pcall(TestConstClassReadErr) == false, "TestConstClassReadErr failed!") print("ClassTest Pass!") end return { Run = Run }
socket = require( "socket") local json = require( "json") client = "" local communication = {} function communication.connect(serverAddress) client = socket.connect(serverAddress,8000) client:settimeout(0) client:setoption("keepalive",true) if not client then print("Error, could not connect to server") return false else return true end end function wait() print("----------------------------------------") end function communication.sendMessage(message) client:send(message) end function communication.sendinfo(player, endturn) local info = {} pawnpositions = '{' for i, pawn in ipairs(player) do if table.indexOf(pawnsOut, i) == nil then pawnpositions = pawnpositions .. '"pawn'.. i ..'":' pawnpositions = pawnpositions .. '{"position":'.. pawn.pos pawnpositions = pawnpositions .. ',"colour":"' .. pawn.colour .. '"' if pawn.lap then pawnpositions = pawnpositions .. ', "lap": true}, ' else pawnpositions = pawnpositions .. ', "lap": false}, ' end end end if player.out then pawnpositions = pawnpositions .. '"out": true' else pawnpositions = pawnpositions .. '"out": false' end if endturn then pawnpositions = pawnpositions .. ', "endturn": true' else pawnpositions = pawnpositions .. ', "updateposition": true' end pawnpositions = pawnpositions .. '}' client:send(pawnpositions) end function communication.receiveInfo() local data, err = client:receive('*l') if data and not err then print("INCOMING:\t",data) return data, true end return nil, false end function communication.sendTime() timestr ='{"hours":' timestr = timestr .. time.hour .. ', ' timestr = timestr .. '"minutes":' .. time.min .. ', ' timestr = timestr .. '"seconds":' .. time.sec ..'}' client:send(timestr) end return communication
--- ============================================================================= -- __ __________ ______ -- / \ / \_____ \ / __ \ -- \ \/\/ // ____/ > < -- \ // \/ -- \ -- \__/\ / \_______ \______ / -- \/ \/ \/ -- lint.lua --- nvim-lint configuration -- Copyright (c) 2021 Sourajyoti Basak -- Author: Sourajyoti Basak < wiz28@protonmail.com > -- URL: https://github.com/wizard-28/dotfiles/ -- License: MIT -- ============================================================================= -- ============================================================================= -- Set linters -- ============================================================================= require('lint').linters_by_ft = { sh = { 'shellcheck' } } -- ============================================================================= -- Set autocmd -- ============================================================================= cmd 'au BufEnter,TextChanged,TextChangedI * lua require(\'lint\').try_lint()' -- =============================================================================
local s = require("null-ls.state") local u = require("null-ls.utils") local c = require("null-ls.config") local methods = require("null-ls.methods") local handlers = require("null-ls.handlers") local lsp = vim.lsp local api = vim.api local schedule = vim.schedule_wrap local function on_init(client) handlers.setup_client(client) s.initialize(client) end local on_exit = function() s.reset() end local start_client = function() s.reset() local client_id = lsp.start_client({ cmd = { c.get().nvim_executable, "--headless", "-u", "NONE", "-c", "set rtp+=" .. s.get_rtp(), "-c", "lua require'null-ls'.start_server()", }, root_dir = vim.fn.getcwd(), -- not relevant yet, but required on_init = on_init, on_exit = on_exit, on_attach = c.get().on_attach, name = "null-ls", flags = { debounce_text_changes = c.get().debounce }, }) -- this completes before the client is initialized -- and signals that start_client should not be called again s.set({ client_id = client_id }) end local try_attach = schedule(function() local bufnr = api.nvim_get_current_buf() if not api.nvim_buf_is_loaded(bufnr) or vim.fn.buflisted(bufnr) == 0 then return end -- the event that triggers this function must fire after the buffer's filetype has been set local ft = api.nvim_buf_get_option(bufnr, "filetype") if ft == "" or not u.filetype_matches(c.get()._filetypes, ft) then return end if not s.get().client_id then start_client() end s.attach(bufnr) end) local M = {} M.start = start_client M.try_attach = try_attach -- triggered after dynamically registering sources M.attach_or_refresh = schedule(function() local uri = vim.uri_from_bufnr(api.nvim_get_current_buf()) -- notify client to get diagnostics from new sources if s.get().attached[uri] then s.notify_client(methods.lsp.DID_CHANGE, { textDocument = { uri = uri } }) return end try_attach() end) return M
--[[ Node class. This class is generally used with edge to add edges into a graph. graph:add(graph.Edge(graph.Node(),graph.Node())) But, one can also easily use this node class to create a graph. It will register all the edges into its children table and one can parse the graph from any given node. The drawback is there will be no global edge table and node table, which is mostly useful to run algorithms on graphs. If all you need is just a data structure to store data and run DFS, BFS over the graph, then this method is also quick and nice. --]] local Node = torch.class('graph.Node') function Node:__init(d,p) self.data = d self.id = 0 self.children = {} self.visited = false self.marked = false end function Node:add(child) local children = self.children if type(child) == 'table' and not torch.typename(child) then for i,v in ipairs(child) do self:add(v) end elseif not children[child] then table.insert(children,child) children[child] = #children end end -- visitor function Node:visit(pre_func,post_func) if not self.visited then if pre_func then pre_func(self) end for i,child in ipairs(self.children) do child:visit(pre_func, post_func) end if post_func then post_func(self) end end end function Node:label() return tostring(self.data) end -- Create a graph from the Node traversal function Node:graph() local g = graph.Graph() local function build_graph(node) for i,child in ipairs(node.children) do g:add(graph.Edge(node,child)) end end self:bfs(build_graph) return g end function Node:dfs_dirty(func) local visitednodes = {} local dfs_func = function(node) func(node) table.insert(visitednodes,node) end local dfs_func_pre = function(node) node.visited = true end self:visit(dfs_func_pre, dfs_func) return visitednodes end function Node:dfs(func) for i,node in ipairs(self:dfs_dirty(func)) do node.visited = false end end function Node:bfs_dirty(func) local visitednodes = {} local bfsnodes = {} local bfs_func = function(node) func(node) for i,child in ipairs(node.children) do if not child.marked then child.marked = true table.insert(bfsnodes,child) end end end table.insert(bfsnodes,self) self.marked = true while #bfsnodes > 0 do local node = table.remove(bfsnodes,1) table.insert(visitednodes,node) bfs_func(node) end return visitednodes end function Node:bfs(func) for i,node in ipairs(self:bfs_dirty(func)) do node.marked = false end end
-- Author Tony Beltramelli www.tonybeltramelli.com - 10/11/2015 local FNN = {} function FNN.get(inputSize, outputSize, layerSize, layerNum) local input = nn.Identity()() local layerInputSize = inputSize local previous = input for i = 1, layerNum do local hidden = nn.Tanh()(nn.Linear(layerInputSize, layerSize)(previous)) layerInputSize = layerSize previous = hidden end local output = nn.SoftMax()(nn.Linear(layerInputSize, outputSize)(previous)) print("Create FNN neural net with "..inputSize.." input neurons, "..outputSize.." output neurons, and "..layerNum.." hidden layers with "..layerSize.." units") local model = nn.gModule({input}, {output}) model.layerSize = layerSize model.layerNum = layerNum model.isRecurrent = false return model end return FNN
--[[ KoZ Rejoin Different Server Script Changed to be a module so I can just loadstring this for my own scripts like so: -- load it to local var. returns func local rj = loadstring(game:HttpGetAsync("https://raw.githubusercontent.com/Kozenomenon/RBX_Pub/main/Misc/Rejoin_Different_Server.lua"))() -- call the func w/ defaults rj() -- or call the func pass in different values rj(5,0.5,30,true,false) -- or you may want use coroutine so rest of your script keeps going until it works coroutine.wrap(rj)() ]] local LoopRetryDelaySeconds = 10 local MaxLoopsThenDoTPSame = 5 local DelaySeconds = 1 local ServerListLimit = 100 local SkipPlayerKick = false local TeleportSameServerIfRequestFails = true function RejoinNewServer(teleportDelay: number,serverLimit: number,skipKick: boolean,teleportSameSvrOnReqFail: boolean) teleportDelay = teleportDelay or 1 serverLimit = serverLimit or 100 serverLimit = math.clamp(serverLimit,1,100) -- rbx api won't allow more than 100 local url = ("https://games.roblox.com/v1/games/%s/servers/Public?sortOrder=Asc&limit=%s"):format(game.PlaceId,tostring(serverLimit)) -- afaik this will only work with: synapse, script-ware, krnl, and protosmasher. or it will default to the rbx http get. local req = (syn and syn.request) or (http and http.request) or http_request or request or function() local resp = {}; resp.Body = game:HttpGetAsync(url); return resp end local Response pcall(function() Response = req({ Url = url, Method = "GET" }) end) if not Response then print("HTTP Request Call Failed"); if not teleportSameSvrOnReqFail then return false end end local currJobId = game.JobId local newJobId local justInCase = 0 local respJson if Response and Response.Body then pcall(function() respJson = game:GetService("HttpService"):JSONDecode(Response.Body) end) if (respJson) then for i,v in pairs(respJson) do if (i == "data" and v and #v > 0) then while (justInCase < serverLimit and (newJobId == nil or newJobId == currJobId)) do justInCase = justInCase + 1 local sel = math.random(1,#v) newJobId = v[sel].id end end end else print("Unexpected Response >>>",Response.StatusCode,Response.StatusMessage,Response.Body) if not teleportSameSvrOnReqFail then return false end end end if (newJobId ~= nil) then local p pcall(function() p = game:GetService("Players").LocalPlayer local msg = ('Rejoining to new server instance in %ss.'):format(tostring(teleportDelay)) if not skipKick then p:Kick(msg) else print(msg) end end) if (teleportDelay > 0) then wait(teleportDelay) end game:GetService('TeleportService'):TeleportToPlaceInstance(game.PlaceId,newJobId,p) print("Teleporting to new server...") return true else print("Failed to get new jobid. Try bigger limit?") if teleportSameSvrOnReqFail then print(('Rejoining in %ss.'):format(tostring(teleportDelay))) if (teleportDelay > 0) then wait(teleportDelay) end game:GetService('TeleportService'):Teleport(game.PlaceId) print("Teleported...") else return false end end end return function(loopRetrySeconds: number,tpDelaySeconds: number,svrListLimit: number,skipKick: boolean,tpSameSvrOnReqFail: boolean, maxLoops: number) LoopRetryDelaySeconds = loopRetrySeconds or LoopRetryDelaySeconds DelaySeconds = tpDelaySeconds or DelaySeconds ServerListLimit = svrListLimit or ServerListLimit if skipKick~=nil then SkipPlayerKick = skipKick end if tpSameSvrOnReqFail~=nil then TeleportSameServerIfRequestFails = tpSameSvrOnReqFail end MaxLoopsThenDoTPSame = maxLoops or MaxLoopsThenDoTPSame local attempts = 0 while attempts < MaxLoopsThenDoTPSame do RejoinNewServer(DelaySeconds,ServerListLimit,SkipPlayerKick,TeleportSameServerIfRequestFails) wait(LoopRetryDelaySeconds) attempts = attempts + 1 end while wait(LoopRetryDelaySeconds) do -- if we get here then just try normal TP game:GetService('TeleportService'):Teleport(game.PlaceId) end end
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") SWEP.PrintName = "Stevens M620" if CLIENT then SWEP.DrawCrosshair = false SWEP.CSMuzzleFlashes = true SWEP.ViewModelMovementScale = 1 SWEP.IconLetter = "k" killicon.Add( "khr_m620", "icons/select/khr_m620", Color(255, 80, 0, 150)) SWEP.SelectIcon = surface.GetTextureID("icons/select/khr_m620") SWEP.EffectiveRange_Orig = 34 * 39.37 SWEP.DamageFallOff_Orig = .48 SWEP.MuzzleEffect = "muzzleflash_m3" SWEP.PosBasedMuz = false SWEP.SnapToGrip = true SWEP.ShellScale = 0.35 SWEP.ShellOffsetMul = 1 SWEP.Shell = "shotshell" SWEP.ShellDelay = 0.4 SWEP.DrawTraditionalWorldModel = false SWEP.WM = "models/khrcw2/w_khri_stevenm62.mdl" SWEP.WMPos = Vector(-1, 1.5, 0) SWEP.WMAng = Vector(-5, 0, 180) SWEP.ShellPosOffset = {x = 1.2, y = -3, z = 0} SWEP.FireMoveMod = 1 SWEP.SightWithRail = true SWEP.IronsightPos = Vector(-1.821, -.5, 1) SWEP.IronsightAng = Vector(.7, 0, 0) SWEP.MicroT1Pos = Vector(-1.821, -1.5, 0.549) SWEP.MicroT1Ang = Vector(0, 0, 0) SWEP.EoTech553Pos = Vector(-1.823, -.5, 0.26) SWEP.EoTech553Ang = Vector(0, 0, 0) SWEP.CSGOACOGPos = Vector(-1.8112, -1.5, 0.465) SWEP.CSGOACOGAng = Vector(0, 0, 0) SWEP.KR_CMOREPos = Vector(-1.821, -1.5, 0.44) SWEP.KR_CMOREAng = Vector(0, 0, 0) SWEP.ShortDotPos = Vector(-1.817, -1.5, 0.5045) SWEP.ShortDotAng = Vector(0, 0, 0) SWEP.FAS2AimpointPos = Vector(-1.818, 0, 0.482) SWEP.FAS2AimpointAng = Vector(0, 0, 0) SWEP.SprintPos = Vector(1.786, 0, -1) SWEP.SprintAng = Vector(-10.778, 27.573, 0) SWEP.CustomizePos = Vector(5.711, -1.482, -1.5) SWEP.CustomizeAng = Vector(16.364, 40.741, 15.277) SWEP.AlternativePos = Vector(-0, 1.2, -.4) SWEP.AlternativeAng = Vector(0, 0, 0) SWEP.CustomizationMenuScale = 0.019 SWEP.ReticleInactivityPostFire = .8 SWEP.AttachmentModelsVM = { ["md_uecw_csgo_acog"] = { type = "Model", model = "models/gmod4phun/csgo/eq_optic_acog.mdl", bone = "body", rel = "", pos = Vector(3.599, 0.029, -.8), angle = Angle(0, 180, 0), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_microt1kh"] = { type = "Model", model = "models/cw2/attachments/microt1.mdl", bone = "body", rel = "", pos = Vector(0.518, 0, 1.565), angle = Angle(0, 90, 0), size = Vector(0.24, 0.24, 0.24), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_aimpoint"] = { type = "Model", model = "models/c_fas2_aimpoint.mdl", bone = "body", rel = "", pos = Vector(-1.4, 0, .97), angle = Angle(0, 180, 0), size = Vector(0.75, 0.75, 0.75), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_rail"] = { type = "Model", model = "models/wystan/attachments/rail.mdl", bone = "body", rel = "", pos = Vector(-1, 0.175, 0.1), angle = Angle(0, 0, 0), size = Vector(0.75, 0.75, 0.75), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["odec3d_cmore_kry"] = { type = "Model", model = "models/weapons/krycek/sights/odec3d_cmore_reddot.mdl", bone = "body", rel = "", pos = Vector(0, -0.051, 1.557), angle = Angle(0, 180, 0), size = Vector(0.16, 0.16, 0.16), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_schmidt_shortdot"] = { type = "Model", model = "models/cw2/attachments/schmidt.mdl", bone = "body", rel = "", pos = Vector(3.099, -.2, -1.535), angle = Angle(0, -180, 0), size = Vector(0.53, 0.53, 0.53), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_eotech"] = { type = "Model", model = "models/c_fas2_eotech.mdl", bone = "body", rel = "", pos = Vector(-1.75, .00, 1.13), angle = Angle(0, 180, 0), size = Vector(0.75, 0.75, 0.75), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_mchoke"] = { type = "Model", model = "models/cw2/attachments/9mmsuppressor.mdl", bone = "body", rel = "", pos = Vector(-16.4, 0.014, 0.529), angle = Angle(0, -90, 0), size = Vector(0.3, 0.3, 0.3), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fchoke"] = { type = "Model", model = "models/cw2/attachments/9mmsuppressor.mdl", bone = "body", rel = "", pos = Vector(-16.4, 0.014, 0.529), angle = Angle(0, -90, 0), size = Vector(0.3, 0.3, 0.3), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.LuaVMRecoilAxisMod = {vert = 1, hor = 1, roll = 1, forward = 0, pitch = 1.5} SWEP.ACOGAxisAlign = {right = 0, up = 0, forward = 0} SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 1.5, forward = 0} end SWEP.MuzzleVelocity = 350 -- in meter/s SWEP.LuaViewmodelRecoil = true SWEP.FullAimViewmodelRecoil = true SWEP.LuaViewmodelRecoilOverride = true SWEP.ADSFireAnim = true SWEP.ForceBackToHipAfterAimedShot = true SWEP.Attachments = {[1] = {header = "Sight", offset = {600, -250}, atts = {"md_microt1kh", "odec3d_cmore_kry", "md_fas2_eotech", "md_fas2_aimpoint", "md_schmidt_shortdot", "md_uecw_csgo_acog"}}, [2] = {header = "Barrel", offset = {-300, -400}, atts = {"md_mchoke", "md_fchoke"}}, ["+reload"] = {header = "Ammo", offset = {-400, 50}, atts = {"am_slugrounds2k", "am_birdshot", "am_flechetterounds2", "am_shortbuck"}}} SWEP.Animations = {fire = {"shoot1"}, reload_start = "start_reload", insert = "insert", reload_end = "after_reload", idle = "idle", draw = "draw"} SWEP.AttachmentExclusions = { ["md_mchoke"] = {"am_slugrounds2k"}, ["md_fchoke"] = {"am_slugrounds2k", "am_birdshot"}, ["am_slugrounds2k"] = {"md_mchoke", "md_fchoke"}, ["am_birdshot"] = {"md_fchoke"} } SWEP.Sounds = {shoot1 = {{time = 0.1, sound = "K620_PUMP"}}, start_reload = {{time = 0.05, sound = "CW_FOLEY_LIGHT"}}, insert = {{time = 0.1, sound = "K620_INSERT"}}, after_reload = {{time = 0.1, sound = "K620_PUMP"}}, draw = {{time = 0.1, sound = "K620_PUMP"}}} SWEP.SpeedDec = 40 SWEP.Slot = 3 SWEP.SlotPos = 0 SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "passive" SWEP.FireModes = {"pump"} SWEP.Base = "cw_base" SWEP.Category = "CW 2.0 - Shotguns" SWEP.Author = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.ViewModelFOV = 75 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/khrcw2/v_khri_stevenm62.mdl" SWEP.WorldModel = "models/khrcw2/w_khri_stevenm62.mdl" SWEP.OverallMouseSens = .9 SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 5 SWEP.Primary.DefaultClip = 5 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "12 Gauge" SWEP.FireDelay = 60/74 SWEP.FireSound = "K620_FIRE" SWEP.Recoil = 5 SWEP.HipSpread = 0.07 SWEP.AimSpread = 0.012 SWEP.VelocitySensitivity = 1.45 SWEP.MaxSpreadInc = 0.08 SWEP.ClumpSpread = .024 SWEP.SpreadPerShot = 0.02 SWEP.SpreadCooldown = 0.75 SWEP.Shots = 9 SWEP.Damage = 13 SWEP.DeployTime = .6 SWEP.ReloadStartTime = 0.5 SWEP.InsertShellTime = 0.8 SWEP.ReloadFinishWait = .9 SWEP.ShotgunReload = true SWEP.Chamberable = true function SWEP:IndividualThink() self.EffectiveRange = 34 * 39.37 self.DamageFallOff = .48 self.ClumpSpread = .024 self.Primary.ClipSize = 5 self.Primary.ClipSize_Orig = 5 if self.ActiveAttachments.am_slugrounds2k then self.EffectiveRange = ((self.EffectiveRange + 8.5 * 39.37)) self.ClumpSpread = nil end if self.ActiveAttachments.am_birdshot then self.ClumpSpread = ((self.ClumpSpread + .01)) self.EffectiveRange = ((self.EffectiveRange - 14.2 * 39.37)) self.DamageFallOff = ((self.DamageFallOff + .42)) self.Shots = 70 end if self.ActiveAttachments.am_flechetterounds2 then self.ClumpSpread = ((self.ClumpSpread - .0092)) self.EffectiveRange = ((self.EffectiveRange - 2.84 * 39.37)) self.DamageFallOff = ((self.DamageFallOff + .048)) end if self.ActiveAttachments.md_mchoke then self.ClumpSpread = ((self.ClumpSpread * .9)) end if self.ActiveAttachments.md_fchoke then self.ClumpSpread = ((self.ClumpSpread * .8)) end if self.ActiveAttachments.am_shortbuck then self.Primary.ClipSize = 7 self.Primary.ClipSize_Orig = 7 end end
local K, C = unpack(select(2, ...)) local Module = K:GetModule("Blizzard") local _G = _G local UIParent = _G.UIParent local AlertFrame = _G.AlertFrame local GroupLootContainer = _G.GroupLootContainer local CreateFrame = _G.CreateFrame local hooksecurefunc = _G.hooksecurefunc local POSITION, ANCHOR_POINT, YOFFSET = "TOP", "BOTTOM", -10 local AlertFrameMover function Module:AlertFrame_UpdateAnchor() local y = select(2, AlertFrameMover:GetCenter()) local screenHeight = UIParent:GetTop() if y > screenHeight/2 then POSITION = "TOP" ANCHOR_POINT = "BOTTOM" YOFFSET = -10 else POSITION = "BOTTOM" ANCHOR_POINT = "TOP" YOFFSET = 10 end self:ClearAllPoints() self:SetPoint(POSITION, AlertFrameMover) end function Module:UpdatGroupLootContainer() local lastIdx = nil for i = 1, self.maxIndex do local frame = self.rollFrames[i] if frame then frame:ClearAllPoints() frame:SetPoint("CENTER", self, POSITION, 0, self.reservedSize * (i - 1 + 0.5) * YOFFSET / 10) lastIdx = i end end if lastIdx then self:SetHeight(self.reservedSize * lastIdx) self:Show() else self:Hide() end end function Module:AlertFrame_SetPoint(relativeAlert) self:ClearAllPoints() self:SetPoint(POSITION, relativeAlert, ANCHOR_POINT, 0, YOFFSET) end function Module:AlertFrame_AdjustQueuedAnchors(relativeAlert) for alertFrame in self.alertFramePool:EnumerateActive() do Module.AlertFrame_SetPoint(alertFrame, relativeAlert) relativeAlert = alertFrame end return relativeAlert end function Module:AlertFrame_AdjustAnchors(relativeAlert) if self.alertFrame:IsShown() then Module.AlertFrame_SetPoint(self.alertFrame, relativeAlert) return self.alertFrame end return relativeAlert end function Module:AlertFrame_AdjustAnchorsNonAlert(relativeAlert) if self.anchorFrame:IsShown() then Module.AlertFrame_SetPoint(self.anchorFrame, relativeAlert) return self.anchorFrame end return relativeAlert end function Module:AlertFrame_AdjustPosition() if self.alertFramePool then self.AdjustAnchors = Module.AlertFrame_AdjustQueuedAnchors elseif not self.anchorFrame then self.AdjustAnchors = Module.AlertFrame_AdjustAnchors elseif self.anchorFrame then self.AdjustAnchors = Module.AlertFrame_AdjustAnchorsNonAlert end end function Module:CreateAlertFrames() if K.CheckAddOnState("MoveAnything") then return end AlertFrameMover = CreateFrame("Frame", "AlertFrameMover", UIParent) AlertFrameMover:SetWidth(180) AlertFrameMover:SetHeight(20) AlertFrameMover:SetPoint("TOP", UIParent, "TOP", 0, -40) K.Mover(AlertFrameMover, "AlertFrameMover", "AlertFrameMover", {"TOP", UIParent, 0, -40}) GroupLootContainer:EnableMouse(false) GroupLootContainer.ignoreFramePositionManager = true for _, alertFrameSubSystem in ipairs(AlertFrame.alertFrameSubSystems) do Module.AlertFrame_AdjustPosition(alertFrameSubSystem) end hooksecurefunc(AlertFrame, "AddAlertFrameSubSystem", function(_, alertFrameSubSystem) Module.AlertFrame_AdjustPosition(alertFrameSubSystem) end) hooksecurefunc(AlertFrame, "UpdateAnchors", Module.AlertFrame_UpdateAnchor) end
return [[na naam naams naan naans naartje naartjes nab nabbed nabber nabbers nabbing nabk nabks nabla nablas nabob nabobs nabs nabses nacarat nacarats nacelle nacelles nach nache naches nacho nachos nacket nackets nacre nacred nacreous nacres nacrite nacrous nada nadir nadirs nae naebody naething naethings naeve naeves naevi naevoid naevus naff naffness nag naga nagana nagari nagas nagged nagger naggers nagging naggy nagmaal nagor nagors nags nahal nahals naiad naiades naiads naiant naif naik naiks nail nailbrush nailed nailer naileries nailers nailery nailing nailings nailless nails nain nainsook naira nairas naissant naive naively naiver naivest naiveties naivety naked nakeder nakedest nakedly nakedness naker nakers nala nalas nallah nallahs naloxone nam namable namaskar namaskars name nameable named nameless namelessly namely namer namers names namesake namesakes nametape nametapes naming namings nams nan nana nanas nance nances nancies nancy nandine nandines nandoo nandoos nandu nanisation nanism nanization nankeen nankeens nankin nankins nanna nannas nannied nannies nanny nannygai nannygais nannying nannyish nanogram nanograms nanometre nanometres nanosecond nans naoi naos naoses nap napa napalm nape naperies napery napes naphtha naphthalic naphthas naphthene naphthenic naphthol naphthols napiform napkin napkins napless napoleon napoleons napoo napooed napooing napoos nappa nappe napped napper nappers nappes nappier nappies nappiest nappiness napping nappy napron naps narc narceen narceine narcissi narcissism narcissist narcissus narco narcolepsy narcos narcoses narcosis narcotic narcotics narcotine narcotise narcotised narcotises narcotism narcotist narcotists narcotize narcotized narcotizes narcs nard narded narding nardoo nardoos nards nare nares narghile narghiles nargile nargileh nargilehs nargiles narial naricorn naricorns narine nark narked narkier narkiest narking narks narky narquois narras narrases narratable narrate narrated narrates narrating narration narrations narrative narratives narrator narrators narratory narre narrow narrowcast narrowed narrower narrowest narrowing narrowings narrowly narrowness narrows narthex narthexes nartjie nartjies narwhal narwhals nary nas nasal nasalise nasalised nasalises nasalising nasality nasalize nasalized nasalizes nasalizing nasally nasals nasard nasards nascence nascency nascent naseberry nashgab nashgabs nasion nasions nastalik nastic nastier nasties nastiest nastily nastiness nasturtium nasty nasute nasutes nat natal natalitial natalities natality natant natation natatoria natatorial natatorium natatory natch natches nates natheless nathemo nathemore nathless natiform nation national nationally nationals nationhood nationless nations nationwide native natively nativeness natives nativism nativist nativistic nativists nativities nativity natrium natrolite natron nats natter nattered natterer natterers nattering natterjack natters nattier nattiest nattily nattiness natty natura natural naturalise naturalism naturalist naturalize naturally naturals nature natured natures naturing naturism naturist naturistic naturists naturopath naught naughtier naughtiest naughtily naughts naughty naumachia naumachiae naumachias naumachies naumachy naunt naunts nauplii nauplioid nauplius nausea nauseant nauseants nauseas nauseate nauseated nauseates nauseating nauseous nauseously nautch nautches nautic nautical nautically nautics nautili nautilus nautiluses navaid navaids naval navalism navarch navarchies navarchs navarchy navarin navarins nave navel navels navelwort navelworts naves navette navettes navew navews navicert navicerts navicula navicular naviculars naviculas navies navigable navigably navigate navigated navigates navigating navigation navigator navigators navvied navvies navvy navvying navy nawab nawabs nay nays nayward nayword naze nazes nazir nazirs ne neafe neafes neaffe neaffes neal nealed nealing neals neanic neap neaped neaping neaps neaptide neaptides near neared nearer nearest nearing nearly nearness nears nearside nearsides neat neaten neatened neatening neatens neater neatest neath neatly neatness neb nebbed nebbich nebbiches nebbing nebbish nebbishe nebbisher nebbishers nebbishes nebbuk nebbuks nebeck nebecks nebek nebeks nebel nebels nebish nebishes nebris nebrises nebs nebula nebulae nebular nebulas nebule nebules nebulise nebulised nebuliser nebulisers nebulises nebulising nebulium nebulize nebulized nebulizer nebulizers nebulizes nebulizing nebulosity nebulous nebulously nebuly necessary necessity neck neckatee neckband neckbands neckcloth neckcloths necked necking neckings necklace necklaces necklet necklets neckline necklines necks necktie neckties neckverse neckwear neckweed neckweeds necrolatry necrologic necrology necromancy necrophile necrophily necropolis necropsy necroscopy necrose necrosed necroses necrosing necrosis necrotic necrotise necrotised necrotises necrotize necrotized necrotizes necrotomy nectar nectareal nectarean nectared nectareous nectarial nectaries nectarine nectarines nectarous nectars nectary nectocalyx ned neddies neddy neds need needed needer needers needful needfully needier neediest needily neediness needing needle needlebook needlecord needled needleful needlefuls needler needlers needles needless needlessly needlework needling needly needment needs needy neeld neele neem neems neep neeps neese neesed neeses neesing neeze neezed neezes neezing nef nefandous nefarious nefast nefs negate negated negates negating negation negations negative negatived negatively negatives negativing negativism negativist negativity negatory negatron negatrons neglect neglected neglecter neglecters neglectful neglecting neglection neglective neglects negligee negligees negligence negligent negligible negligibly negotiable negotiant negotiants negotiate negotiated negotiates negotiator negritude negrohead negroid negroidal negroids negroism negroisms negrophil negrophile negrophils negrophobe negus neguses neif neifs neigh neighbor neighbored neighborly neighbors neighbour neighbours neighed neighing neighs neist neither neive neives nek nekton nektons nellies nelly nelson nelsons nelumbium nelumbiums nelumbo nelumbos nematic nematocyst nematode nematodes nematoid nematology nemertean nemerteans nemertine nemertines nemeses nemesia nemesias nemesis nemophila nemophilas nemoral nene nenes nenuphar nenuphars neoblast neoblasts neoclassic neodymium neogenesis neogenetic neolith neoliths neologian neologians neologic neological neologies neologise neologised neologises neologism neologisms neologist neologists neologize neologized neologizes neology neomycin neon neonatal neonate neonates neonomian neonomians neopagan neopagans neophilia neophiliac neophobia neophobic neophyte neophytes neophytic neoplasm neoplasms neoplastic neoprene neorealism neorealist neoteinia neotenic neotenous neoteny neoteric neoterise neoterised neoterises neoterism neoterist neoterists neoterize neoterized neoterizes nep nepenthe nepenthean nepenthes neper nepers nepeta nephalism nephalist nephalists nepheline nephelite nephew nephews nephogram nephograms nephograph nephology nephoscope nephralgia nephric nephridium nephrite nephritic nephritis nephroid nephrology nephron nephrons nephropexy nephrosis nephrotic nephrotomy nepionic nepit nepits nepotic nepotism nepotist nepotistic nepotists neps neptunium nerd nerds nerdy nereid nereides nereids nerine nerines neritic nerk nerka nerkas nerks neroli nerval nervate nervation nervations nervature nervatures nerve nerved nerveless nervelet nervelets nerver nervers nerves nervier nerviest nervily nervine nervines nerviness nerving nervous nervously nervular nervule nervules nervure nervures nervy nescience nescient nesh neshness ness nesses nest nested nester nesters nestful nesting nestle nestled nestles nestlike nestling nestlings nests net netball nete netes netful netfuls nether nethermore nethermost netherward netiquette netizen netizens nets netsuke netsukes nett netted nettier nettiest netting nettings nettle nettled nettlelike nettlerash nettles nettlesome nettlier nettliest nettling nettly netts netty network networked networker networkers networking networks neuk neuks neum neume neumes neums neural neuralgia neuralgic neurally neuration neurations neurectomy neurilemma neurility neurine neurism neurite neuritic neuritics neuritis neuroblast neurochip neurochips neurogenic neuroglia neurogram neurograms neurolemma neurology neurolysis neuroma neuromas neuromata neuron neuronal neurone neurones neuronic neurons neuropath neuropaths neuropathy neuropil neuroplasm neuroses neurosis neurotic neurotics neurotomy neurotoxic neurotoxin neuston neustons neuter neutered neutering neuters neutral neutralise neutralism neutralist neutrality neutralize neutrally neutrals neutretto neutrettos neutrino neutrinos neutron neutrons neutrophil nevel nevelled nevelling nevels never nevermore neves nevus new newbie newbies newborn newcome newcomer newcomers newed newel newell newelled newels newer newest newfangle newfangled newing newish newly newmarket newmarkets newness news newsagent newsagents newsboy newsboys newscast newscaster newscasts newsdealer newsed newses newsgirl newsgirls newshawk newshawks newshound newshounds newsier newsies newsiest newsiness newsing newsless newsletter newsman newsmen newsmonger newspaper newspapers newspeak newsprint newsreel newsreels newsroom newsrooms newssheet newssheets newsvendor newswoman newswomen newsworthy newsy newt newton newtons newts next nextly nextness nexus nexuses ngaio ngaios ngana ngultrum ngultrums ngwee nhandu nhandus niacin niaiserie nib nibbed nibbing nibble nibbled nibbler nibblers nibbles nibbling nibblingly nibblings niblick niblicks nibs nicad nicads niccolite nice niceish nicely niceness nicer nicest niceties nicety niche niched nicher nichered nichering nichers niches niching nicht nick nickar nickars nicked nickel nickeled nickelic nickeline nickeling nickelise nickelised nickelises nickelize nickelized nickelizes nickelled nickelling nickelous nickels nicker nickered nickering nickers nicking nicknack nicknacks nickname nicknamed nicknames nicknaming nickpoint nickpoints nicks nickstick nicksticks nicol nicols nicotian nicotiana nicotianas nicotians nicotine nicotined nicotinic nicotinism nictate nictated nictates nictating nictation nictitate nictitated nictitates nid nidal nidamental nidation niddering nidderings nide nidering niderings nides nidget nidgets nidi nidicolous nidificate nidified nidifies nidifugous nidify nidifying niding nidor nidorous nidors nids nidulation nidus niece nieces nief niefs niellated nielli niellist niellists niello nielloed nielloing niellos nieve nieves nife niff niffer niffered niffering niffers niffier niffiest niffnaff niffnaffed niffnaffs niffs niffy niftier niftiest niftily niftiness nifty nigella nigellas niggard niggardise niggardize niggardly niggards nigger niggerdom niggered niggering niggerish niggerism niggerisms niggerling niggers niggery niggle niggled niggler nigglers niggles niggling nigglingly nigglings niggly nigh nighly nighness night nightcap nightcaps nightclass nightdress nighted nightfall nightfalls nightfire nightfires nightgown nightgowns nightie nighties nightjar nightjars nightless nightlife nightlong nightly nightmare nightmares nightmary nightpiece nights nightshade nightshirt nightspot nightspots nightstand nightward nightwear nighty nigrescent nigrified nigrifies nigrify nigrifying nigritude nigrosin nigrosine nihil nihilism nihilist nihilistic nihilists nihilities nihility nikau nikaus nil nilgai nilgais nilgau nilgaus nill nilled nils nim nimb nimbed nimbi nimble nimbleness nimbler nimblest nimbly nimbus nimbused nimbuses nimbyism nimiety nimious nimmed nimmer nimmers nimming nimonic nims nincom nincompoop nincoms nine ninefold ninepence ninepences ninepenny ninepins nines nineteen nineteens nineteenth nineties ninetieth ninetieths ninety ninja ninjas ninjitsu ninjutsu ninnies ninny ninon ninons ninth ninthly ninths niobate niobic niobite niobium niobous nip nipped nipper nippered nippering nipperkin nipperkins nippers nippier nippiest nippily nippiness nipping nippingly nipple nippled nipples nipplewort nippling nippy nips nipter nipters nirl nirled nirlie nirlier nirliest nirling nirlit nirls nirly nirvana nirvanas nis nisei niseis nisi nisse nisses nisus nisuses nit nite niter niterie niteries nitery nites nithing nithings nitid nitinol niton nitpick nitpicked nitpicker nitpickers nitpicking nitpicks nitrate nitrated nitrates nitratine nitrating nitration nitrazepam nitre nitric nitride nitrided nitrides nitriding nitridings nitrified nitrifies nitrify nitrifying nitrile nitriles nitrite nitrites nitrogen nitrometer nitrosyl nitrous nitroxyl nitry nitryl nits nittier nittiest nitty nitwit nitwits nitwitted nival niveous nix nixes nixie nixies nixy nizam nizams no nob nobbier nobbiest nobbily nobble nobbled nobbler nobblers nobbles nobbling nobbut nobby nobelium nobiliary nobilitate nobilities nobility noble nobleman noblemen nobleness nobler nobles noblesse noblesses noblest noblewoman noblewomen nobly nobodies nobody nobs nocake nocakes nocent nocents nock nocked nocket nockets nocking nocks noctiluca noctilucae noctua noctuas noctuid noctuids noctule noctules nocturn nocturnal nocturnals nocturne nocturnes nocturns nocuous nocuously nod nodal nodalise nodalised nodalises nodalising nodalities nodality nodally nodated nodation nodations nodded nodder nodders noddies nodding noddingly noddings noddle noddled noddles noddling noddy node nodes nodi nodical nodose nodosities nodosity nodous nods nodular nodulated nodulation nodule noduled nodules nodulose nodulous nodus noels noes noesis noetic nog nogg nogged noggin nogging noggings noggins noggs nogs noh nohow noil noils noint nointed nointing noints noise noised noiseful noiseless noisemaker noises noisette noisettes noisier noisiest noisily noisiness noising noisome noisomely noisy nole nolition nolitions noll nolls noma nomad nomade nomades nomadic nomadise nomadised nomadises nomadising nomadism nomadize nomadized nomadizes nomadizing nomads nomarch nomarchies nomarchs nomarchy nomas nombles nombril nombrils nome nomen nomes nomic nomina nominable nominal nominalise nominalism nominalist nominalize nominally nominals nominate nominated nominately nominates nominating nomination nominative nominator nominators nominee nominees nomism nomistic nomocracy nomogeny nomogram nomograms nomograph nomographs nomography nomoi nomologist nomology nomos nomothete nomothetes nomothetic non nonage nonaged nonages nonagon nonagons nonane nonary nonce nonces nonchalant nondairy nondrinker nondrip none nonentity nonesuch nonesuches nonet nonets nong nongs nonillion nonillions nonionic nonjuror nonjurors nonlethal nonlicet nonnies nonny nonpareil nonpareils nonparous nonplacet nonplaying nonplus nonplused nonpluses nonplusing nonplussed nonplusses nonpolar nonprofit nonracial nonreader nonsense nonsenses nonsexist nonstick nonsuch nonsuches nonsuit nonsuited nonsuiting nonsuits nonswimmer nontoxic nonuple nonuplet nonuplets nonverbal nonvintage nonvoter noodle noodledom noodles nook nookie nookies nooks nooky noology noometry noon noonday noondays nooned nooning noonings noons noontide noontides noontime noop noops noose noosed nooses noosing noosphere nopal nopals nope nopes nor nori noria norias norimon norimons norite nork norks norland norlands norm normal normalcy normalise normalised normalises normality normalize normalized normalizes normally normals norman normanise normanised normanises normanize normanized normanizes normans normative norms norsel north norther northerly northern northerner northerns northers northing northings northland northlands northmost norths northward northwards norward norwards nos nose nosean nosebag nosebags nosecone nosecones nosed nosegay nosegays noseless noselite noser nosering noserings nosers noses nosey noseys nosh noshed nosher nosheries noshers noshery noshes noshing nosier nosies nosiest nosily nosiness nosing nosings nosocomial nosography nosologist nosology nosophobia nostalgia nostalgic nostoc nostocs nostologic nostology nostomania nostril nostrils nostrum nostrums nosy not notabilia notability notable notables notably notaeum notaeums notal notanda notandum notaphilic notaphily notarial notarially notaries notarise notarised notarises notarising notarize notarized notarizes notarizing notary notaryship notate notated notates notating notation notational notations notch notchback notchbacks notched notchel notchelled notchels notcher notchers notches notching notchings notchy note notebook notebooks notecase notecases noted notedly notedness noteless notelet notelets notepad notepads notepaper notepapers noter noters notes noteworthy nothing nothingism nothings notice noticeable noticeably noticed notices noticing notifiable notified notifier notifiers notifies notify notifying noting notion notional notionally notionist notionists notions notitia notitias notochord notochords notodontid notonectal notoriety notorious notornis notornises notour nott notum notums nougat nougats nought noughts nould noule noumena noumenal noumenally noumenon noun nounal nouns noup noups nourice nourish nourished nourisher nourishers nourishes nourishing nouriture nous nousle nousled nousles nousling nouveau nouvelle nova novaculite novae novalia novas novation novations novel noveldom novelese novelette novelettes novelise novelised noveliser novelisers novelises novelish novelising novelism novelist novelistic novelists novelize novelized novelizer novelizers novelizes novelizing novella novellae novellas novelle novels novelties novelty novena novenaries novenary novenas novennial novercal novice novicehood novices noviceship noviciate noviciates novitiate novitiates novity novodamus novum now nowadays noway noways nowed nowhence nowhere nowhither nowise nowness nows nowt nowy noxal noxious noxiously noy noyade noyades noyance noyau noyaus noyes noyous noys nozzer nozzers nozzle nozzles nth nu nuance nuanced nuances nub nubbier nubbiest nubbin nubbins nubble nubbled nubbles nubblier nubbliest nubbling nubbly nubby nubecula nubeculae nubia nubias nubiferous nubiform nubigenous nubile nubility nubilous nubs nucellar nucelli nucellus nucelluses nucha nuchae nuchal nuciferous nucivorous nucleal nuclear nuclearise nuclearize nucleary nuclease nucleases nucleate nucleated nucleates nucleating nucleation nucleator nucleators nuclei nucleide nucleides nuclein nucleolar nucleolate nucleole nucleoles nucleoli nucleolus nucleon nucleonics nucleons nucleoside nucleosome nucleotide nucleus nuclide nuclides nucule nucules nudation nudations nude nudely nudeness nudes nudge nudged nudger nudgers nudges nudging nudibranch nudicaul nudie nudies nudism nudist nudists nudities nudity nudnik nudniks nuff nuffin nugae nugatory nuggar nuggars nugget nuggets nuggety nuisance nuisancer nuisancers nuisances nuke nuked nukes nuking null nulla nullah nullahs nullas nulled nullified nullifier nullifiers nullifies nullify nullifying nulling nullings nullipara nulliparas nullipore nullity nulls numb numbat numbats numbed number numbered numberer numberers numbering numberless numbers numbest numbing numbingly numbles numbly numbness numbs numbskull numbskulls numdah numdahs numen numerable numerably numeracy numeral numerally numerals numerary numerate numerated numerates numerating numeration numerator numerators numeric numerical numerology numerosity numerous numerously numina numinous numismatic nummary nummular nummulary nummulated nummuline nummulite nummulites nummulitic numnah numnahs numskull numskulled numskulls nun nunatak nunataker nunataks nunchaku nunchakus nuncheon nuncheons nunciature nuncio nuncios nuncle nuncupate nuncupated nuncupates nundinal nundine nundines nunhood nunnation nunneries nunnery nunnish nuns nunship nuptial nuptiality nuptials nur nuraghe nuraghi nuraghic nurd nurdle nurdled nurdles nurdling nurds nurhag nurhags nurl nurled nurling nurls nurr nurrs nurs nurse nursed nursehound nurselike nurseling nurselings nursemaid nursemaids nurser nurseries nursers nursery nurseryman nurserymen nurses nursing nursle nursled nursles nursling nurslings nurturable nurtural nurturant nurture nurtured nurturer nurturers nurtures nurturing nut nutant nutarian nutarians nutate nutated nutates nutating nutation nutational nutations nutcase nutcases nutcracker nuthatch nuthatches nuthouse nuthouses nutjobber nutjobbers nutlet nutlets nutlike nutmeg nutmegged nutmegging nutmeggy nutmegs nutpecker nutpeckers nutria nutrias nutrient nutrients nutriment nutriments nutrition nutritions nutritious nutritive nuts nutshell nutshells nutted nutter nutters nuttery nuttier nuttiest nuttily nuttiness nutting nuttings nutty nutwood nuzzer nuzzers nuzzle nuzzled nuzzles nuzzling ny nyaff nyaffed nyaffing nyaffs nyala nyalas nyanza nyanzas nyas nyases nybble nybbles nyctalopes nyctalopia nyctalopic nyctalops nyctinasty nye nyes nyet nylghau nylghaus nylon nylons nymph nymphae nymphaeum nymphaeums nymphal nymphalid nymphalids nymphean nymphet nymphets nymphic nymphical nymphish nymphly nympho nympholept nymphos nymphs nystagmic nystagmus nystatin]]
Robot = class() function Robot:init(x, y) -- position and bounds self.penStart = false self.penStatus = false self.pen = {} self.x = x self.y = y self.oldX = x self.oldY = y self.bounds = Frame(0,0,0,0) self.direction = 0 self.fromDir = 0 self.toDir = 0 -- code related values self.program = {} for i = 1, 30 do self.program[i] = nil end self.step = 1 self.aEntry = 1 self.bEntry = 1 -- sensor values self.bump = false self.radar = false self.treadTick = 0 self.fireLaser = false self.fireRadar = false self.delay = 0 -- tourney-telated values self.hp = 10 self.damage = self.hp self.wins = 0 self.losses = 0 self.heat = 0 self.repeatCounter = 1 self.points = 0 self.redirectValue = 0 self.rf = Frame(0,0,0,0) self.limits = Frame(0,0,0,0) -- design-related values self.name = "Generobot" self.treadColor = 14 self.bodyColor = 14 self.headColor = 15 self.dishColor = 4 self.head = 1 self.dish = 1 self.body = 2 self.tread = 2 self.range = 20 self.speed = 5 self.turnDelay = 5 self.turnTarget = 1 self.flameTimer = 0 self.shield = 0 self.repairRate = 0 self.img = image(60, 60) end function Robot:createImage() -- create an image of the bot for use in menus, etc pushMatrix() strokeWidth(2) translate(30,30) setContext(self.img) self:drawBase() setContext() popMatrix() end function Robot:redirect(v) -- set correct step number depending on board if self.step > 60 then return v + 60 elseif self.step > 30 then return v + 30 else return v end end function Robot:createDetectionFrame(dir) -- used by radar and laser if dir == 1 then -- up self.rf = Frame(self.x + 24, self.y + 36, self.x + 36, self.range * 60) if self.rf.top > self.limits:height() then self.rf.top = self.limits:height() end elseif dir == 2 then -- right self.rf = Frame(self.x + 33, self.y + 24, self.x + self.range * 60, self.y + 36) if self.rf.right > self.limits:width() then self.rf.right = self.limits:width() end elseif dir == 3 then -- down self.rf = Frame(self.x + 24, self.y - self.range * 60, self.x + 36, self.y + 33) if self.rf.bottom < 0 then self.rf.bottom = 0 end elseif dir == 4 then -- left self.rf = Frame(self.x - self.range * 60, self.y + 24, self.x + 33, self.y + 36) if self.rf.left < 0 then self.rf.left = 0 end end end function Robot:drawLaser() -- create the rectangle for laser fire if self.rf == nil then self:createDetectionFrame(self.direction) end noStroke() fill(212, 60, 55, 92) self.rf:draw() sound(SOUND_SHOOT, 9773) end function Robot:drawRadar(dir) -- create the rectangle for radar detection self:createDetectionFrame(dir) --noStroke() --fill(81, 85, 175, 50) --self.rf:draw() --sound(SOUND_JUMP, 9772) end function Robot:run() local p, rf, redirected --displayMode(STANDARD) if self.delay > 0 then self.delay = self.delay - 1 return true end self.hp = self.hp + self.repairRate / 100 if self.hp > 10 then self.hp = 10 end if self.radar then self.step = self.redirectValue --sound(SOUND_HIT, 17131) self.radar = false end -- get executable token p = self.program[self.step] redirected = false if p == nil or p.code == nil then if self.step > 60 then self.step = self.bEntry + 1 elseif self.step > 30 then self.step = self.aEntry + 1 else self.step = 1 end redirected = true return false end -- execute control if p.code.short == "G" then -- Goto self.step = self:redirect(p.value) redirected = true elseif p.code.short == "5" then -- 50/50 random if math.random(2) > 1 then self.step = self:redirect(p.value) redirected = true end elseif p.code.short == "P" then -- repeat if self.repeatCounter < p.value then self.repeatCounter = self.repeatCounter + 1 self.step = self.step - 1 redirected = true else self.repeatCounter = 1 end -- check sensors elseif p.code.short == "D" then -- damage sensor if self.hp < self. damage then self.damage = self.hp self.step = self:redirect(p.value) redirected = true end elseif p.code.short == "H" then -- bump sensor if self.bump then self.step = self:redirect(p.value) sound(SOUND_HIT, 17131) redirected = true end self.bump = false elseif p.code.short == "A" then -- radar sensor self:drawRadar(self.direction) self.delay = 5 self.fireRadar = true self.redirectValue = self:redirect(p.value) elseif p.code.short == "I" then -- radar sensor right i = self.direction + 1 if i > 4 then i = 1 end self:drawRadar(i) self.delay = 5 self.fireRadar = true self.redirectValue = self:redirect(p.value) elseif p.code.short == "T" then -- radar sensor left i = self.direction - 1 if i < 1 then i = 4 end self:drawRadar(i) self.delay = 5 self.fireRadar = true self.redirectValue = self:redirect(p.value) -- take action elseif p.code.short == "F" then -- Forward self.treadTick = self.treadTick + 1 if self.treadTick > 9 then self.treadTick = 0 end if not self.bump then self.oldX = self.x self.oldY = self.y if self.direction == 1 then self.y = self.y + self.speed elseif self.direction == 2 then self.x = self.x + self.speed elseif self.direction == 3 then self.y = self.y - self.speed elseif self.direction == 4 then self.x = self.x - self.speed end if self.penStart then self.pen[#self.pen + 1] = PenPoint(self.x + 30, self.y + 30, self.penStatus) end end elseif p.code.short == "B" then -- Reverse self.treadTick = self.treadTick - 1 if self.treadTick < 0 then self.treadTick = 9 end if not self.bump then self.oldX = self.x self.oldY = self.y if self.direction == 3 then self.y = self.y + self.speed elseif self.direction == 4 then self.x = self.x + self.speed elseif self.direction == 1 then self.y = self.y - self.speed elseif self.direction == 2 then self.x = self.x - self.speed end if self.penStart then self.pen[#self.pen + 1] = PenPoint(self.x + 30, self.y + 30, self.penStatus) end end elseif p.code.short == "L" then self.direction = self.direction - 1 if self.direction == 0 then self.direction = 4 end self.delay = self.delay + self.turnDelay elseif p.code.short == "R" then self.direction = self.direction + 1 if self.direction == 5 then self.direction = 1 end self.delay = self.delay + self.turnDelay elseif p.code.short == "W" then -- fire laser self.delay = self.dish * 15 self.fireLaser = true self:drawLaser() elseif p.code.short == "1" then -- Daughterboard A if self.step < 31 then self.aEntry = self.step end self.step = 31 redirected = true elseif p.code.short == "2" then -- Daughterboard B if self.step < 61 then self.bEntry = self.step end self.step = 61 redirected = true elseif p.code.short == "S" then -- Sound Horn sound(SOUND_RANDOM, 19024) elseif p.code.short == "v" then -- pen down self.penStart = true self.penStatus = true elseif p.code.short == "^" then -- pen up self.penStart = true self.penStatus = false end -- step forward if not redirected then self.step = self.step + 1 end self.treadTick = self.treadTick + 1 if self.treadTick > 9 then self.treadTick = 0 end end function Robot:draw(size) local i -- draw pushMatrix() translate(self.x + 30, self.y + 30) scale(size) if self.direction == 2 then rotate(270) elseif self.direction == 3 then rotate(180) elseif self.direction == 4 then rotate(90) end strokeWidth(1) self:drawBase() popMatrix() self.bounds.left = self.x self.bounds.right = self.x + 60 self.bounds.top = self.y + 60 self.bounds.bottom = self.y if self.heat > 0 then self.heat = self.heat - 0.1 end end function Robot:drawDish(x, y) c1 = colors[self.dishColor] c2 = color(c1.r + self.heat * 22, c1.g, c1.b) stroke(c2) fill(backClr) if self.dish == 1 then line(x - 3, y, x, y + 15) line(x + 3, y, x, y + 15) line(x - 20, y + 7, x - 15, y + 3) line(x - 15, y + 3, x, y) line(x + 20, y + 7, x + 15, y + 3) line(x + 15, y + 3, x, y) line(x, y + 15, x, y + 20) ellipse(x, y + 15, 3) self.range = 20 end if self.dish == 2 then rect(x - 3, y, x + 3, y + 20) line(x - 15, y, x, y) line(x + 15, y, x, y) line(x - 20, y + 10, x, y) line(x + 20, y + 10, x, y) self.range = 7 end if self.dish == 3 then line(x - 15, y, x + 15, y) line(x - 10, y + 3, x + 10, y + 3) line(x - 7, y + 7, x + 7, y + 7) line(x - 3, y + 10, x + 3, y + 10) line(x, y, x, y + 20) ellipse(x, y + 20, 7) self.range = 3 end end function Robot:drawHead(x, y) c1 = colors[self.headColor] c2 = color(c1.r + self.heat * 22, c1.g, c1.b) stroke(c2) fill(backClr) if self.head == 1 then ellipse(x, y, 30) ellipse(x, y, self.treadTick * 2) rect(x - 15, y - 5, x - 15, y + 5) rect(x + 15, y - 5, x + 15, y + 5) line(x - 15, y, x - 20, y) line(x + 15, y, x + 20, y) end if self.head == 2 then ellipse(x, y, 30) ellipse(x, y, 20) rotate(self.treadTick * 9) line(x+6,y+6,x-6,y-6) line(x+6,y-6,x-6,y+6) rotate(self.treadTick * -9) end if self.head == 3 then ellipse(x, y, 30) ellipse(x, y + 10, 20, 10) ellipse(x, y + 10, 15, 5) line(x - 15, y - 5, x - 20, y - 15) line(x + 15, y - 5, x + 20, y - 15) fill(255, 0, 0, 255) ellipse(x, y + 5, 20, self.treadTick * 2) end end function Robot:drawBody(x, y) c1 = colors[self.bodyColor] c2 = color(c1.r + self.heat * 22, c1.g, c1.b) stroke(c2) fill(backClr) if self.body == 1 then ellipse(x, y, 40, 20) ellipse(x - 20, y, 15, 15) ellipse(x + 20, y, 15, 15) end if self.body == 2 then rect(x - 25, y - 10, x + 25, y + 10) ellipse(x - 25, y, 20) ellipse(x + 25, y, 20) rect(x - 15, y - 15, x + 15, y - 10) end if self.body == 3 then ellipse(x - 20, y, 30, 30) ellipse(x + 20, y, 30, 30) rect(x - 20, y - 15, x + 20, y + 15) ellipse(x, y, 40, 30) end end function Robot:drawTreads(x, y) local i c1 = colors[self.treadColor] c2 = color(c1.r + self.heat * 22, c1.g, c1.b) stroke(c2) fill(backClr) if self.tread == 1 then ellipse(20, -20, 20) ellipse(20, -20, 20, 5 + self.treadTick) ellipse(-20, -20, 20) ellipse(-20, -20, 20, 5 + self.treadTick) ellipse(-20, 20, 20) ellipse(-20, 20, 20, 5 + self.treadTick) ellipse(20, 20, 20) ellipse(20, 20, 20, 5 + self.treadTick) line(-20, -11, 0, 2) line(-17, -14, 0, -2) line(20, -11, 0, 2) line(17, -14, 0, -2) line(-20, 11, 0, 2) line(-17, 14, 0, -2) line(20, 11, 0, 2) line(17, 14, 0, -2) end if self.tread == 2 then rect(-30, -30, -15, 30) rect(15, -30, 30, 30) for i = 0,5 do line(-30, i * 10 - 30 + self.treadTick, -15, i * 10 - 30 + self.treadTick) line(15, i * 10 -30 + self.treadTick, 30, i * 10 - 30 + self.treadTick) end end if self.tread == 3 then rect(-30, -30, -15, -15) rect(-27, -33, -17, -12) rect(15, -30, 30, -15) rect(17, -33, 27, -12) rect(-30, 15, -15, 30) rect(-27, 12, -17, 33) rect(15, 15, 30, 30) rect(17, 12, 27, 33) rect(-15, 20, 15, 25) rect(-15, -20, 15, -25) rect(-3, -10, 3, -20) rect(-3, 10, 3, 20) line(-27, self.treadTick - 30 + self.treadTick, -17, self.treadTick - 30 + self.treadTick) line(17, self.treadTick - 30 + self.treadTick, 27, self.treadTick - 30 + self.treadTick) line(17, self.treadTick + 15 + self.treadTick, 27, self.treadTick + 15 + self.treadTick) line(-27, self.treadTick + 15 + self.treadTick, -17, self.treadTick + 15 + self.treadTick) end end function Robot:drawBase() pushStyle() self:drawTreads(0, 0) self:drawBody(0, 0) self:drawHead(0, 0) self:drawDish(0, 10) popStyle() end
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or '' local common = require(current_folder.. ".common") local Path = require(current_folder.. ".Path") local QuadExport = {} QuadExport.export = function(quads, exporter, filepath) assert(quads and type(quads) == "table") assert(exporter and type(exporter) == "table", tostring(type(exporter))) assert(exporter.export and type(exporter.export) == "function") assert(exporter.ext and type(exporter.ext) == "string") assert(exporter.name and type(exporter.name) == "string") -- Use clone of quads table instead of the original one quads = common.clone(quads) local filehandle, open_err = io.open(filepath, "w") if not filehandle then error(open_err) end if not quads._META then quads._META = {} end -- Insert version info into quads quads._META.version = common.get_version() -- Replace the path to the image by a path name relative to the parent dir of -- `filepath`. We use the parent dir since filepath points to the file that -- the quads will be exported to. if quads._META.image_path then assert(Path.is_absolute_path(filepath)) local basepath = Path(filepath):parent() assert(Path.is_absolute_path(quads._META.image_path)) local rel_path = Path(quads._META.image_path):get_relative_to(basepath) quads._META.image_path = rel_path end local writer = common.get_writer(filehandle) local info = { filepath = filepath, } local success, export_err = pcall(exporter.export, writer, quads, info) filehandle:close() if not success then error(export_err, 0) end end return QuadExport
require("fireDrive.lua"); require("rrpg.lua"); require("internet.lua"); --[[ rrpg.messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; fireDrive.getFiles(message.parametro, function(fs) message.chat:escrever("\\\\Lista: "); for i = 1, #fs, 1 do message.chat:escrever(fs[i].name .. " " .. tableToStr(fs[i])); end; message.chat:escrever("//Fim da Lista"); end, function(errorMsg) message.chat:escrever("erro: " .. tostring(errorMsg)); end); end, {comando="fdlist"}); rrpg.messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; fireDrive.createDirectory(message.parametro, function(ret) message.chat:escrever("diretório criado: " .. tableToStr(ret)); end, function(errMsg) message.chat:escrever("Erro ao criar diretório: " .. errMsg); end); end, {comando="fdmkdir"}); rrpg.messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; dialogs.openFile("Selecione arquivos para fazer upload", nil, true, function(files) local f = files[1]; local destName = message.parametro or ""; if destName == "" then detName = f.name; end; fireDrive.uploadFile(detName, f.stream, function(x) message.chat:escrever("Sucesso: " .. (tableToStr(x, true) or "")); end, function(x, i) message.chat:escrever(string.format("Progresso: %d / %d", x, i)); end, function(x) message.chat:escrever("erro: " .. tostring(x)); end); end); end, {comando="fdupload"}); rrpg.messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; fireDrive.delete(message.parametro, function(x) message.chat:escrever("Sucesso ao deletar"); end, function(x) message.chat:escrever("Erro ao deletar: " .. tostring(x)); end, 'text/plain'); end, {comando="fddelete"}); rrpg.messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; fireDrive.refresh(function(x) message.chat:escrever("Refrescado"); end, function(x) message.chat:escrever("Erro ao refrescar: " .. tostring(x)); end, 'text/plain'); end, {comando="fdrefresh"}); rrpg.messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; fireDrive.getFileInfo(message.parametro or "", function(x) if x ~= nil then message.chat:escrever("Informações do arquivo: " .. tableToStr(x)); else message.chat:escrever("Arquivo não existe"); end; end, function(x) message.chat:escrever("Erro ao obter informações do arquivo: " .. tostring(x)); end, 'text/plain'); end, {comando="fdinfo"}); ]] function RRPG_ExibirFireDrive() local frm = GUI.newForm("frmFireDriveExplorer"); frm:show(); end; Firecast.Messaging.listen("HandleChatCommand", function(message) message.response = {handled = true}; RRPG_ExibirFireDrive(); end, {comando="fd"});
return { version = "1.1", luaversion = "5.1", tiledversion = "2015-06-02", orientation = "orthogonal", width = 36, height = 16, tilewidth = 32, tileheight = 32, nextobjectid = 1, properties = {}, tilesets = { { name = "Tiles_32x32", firstgid = 1, tilewidth = 32, tileheight = 32, spacing = 0, margin = 0, image = "tiles/Tiles_32x32.png", imagewidth = 256, imageheight = 256, tileoffset = { x = 0, y = 0 }, properties = {}, terrains = {}, tilecount = 64, tiles = {} } }, layers = { { type = "tilelayer", name = "Tile Layer 1", x = 0, y = 0, width = 36, height = 16, visible = true, opacity = 1, properties = {}, encoding = "lua", data = { 5, 33, 5, 5, 33, 5, 50, 5, 5, 5, 33, 48, 5, 33, 50, 33, 5, 5, 5, 5, 34, 5, 50, 5, 5, 5, 5, 5, 33, 5, 5, 5, 5, 5, 34, 5, 5, 5, 5, 5, 50, 5, 33, 5, 5, 50, 5, 5, 33, 5, 5, 5, 48, 5, 5, 5, 5, 5, 5, 5, 5, 5, 48, 5, 5, 5, 5, 5, 5, 5, 5, 5, 24, 0, 0, 0, 0, 24, 0, 24, 0, 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 24, 24, 0, 24, 0, 0, 0, 0, 0, 24, 0, 0, 24, 0, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 51, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 51, 0, 51, 0, 0, 0, 0, 29, 0, 29, 29, 47, 0, 47, 0, 29, 29, 29, 45, 0, 29, 0, 47, 29, 0, 0, 29, 0, 0, 29, 0, 0, 0, 47, 29, 29, 0, 7, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 34, 50, 5, 34, 5, 34, 50, 5, 33, 33, 5, 34, 50, 5, 49, 5, 5, 34, 5, 5, 4, 34, 49, 5, 50, 50, 33, 5, 34, 49, 5, 5, 49, 5, 34, 5 } } } }
#!/usr/bin/env tarantool test = require("sqltester") test:plan(8) --!./tcltestrunner.lua -- 2012 December 19 -- -- The author disclaims copyright to this source code. In place of -- a legal notice, here is a blessing: -- -- May you do good and not evil. -- May you find forgiveness for yourself and forgive others. -- May you share freely, never taking more than you give. -- ------------------------------------------------------------------------- -- This file implements regression tests for SQLite library. Specifically, -- it tests that ticket [a7b7803e8d1e8699cd8a460a38133b98892d2e17] has -- been fixed. -- -- ["set","testdir",[["file","dirname",["argv0"]]]] -- ["source",[["testdir"],"\/tester.tcl"]] -- ["source",[["testdir"],"\/lock_common.tcl"]] -- ["source",[["testdir"],"\/malloc_common.tcl"]] test:do_test( "tkt-a7b7803e.1", function() return test:execsql [[ CREATE TABLE t1(a INT primary key,b TEXT); INSERT INTO t1 VALUES(0,'first'),(99,'fuzzy'); SELECT (t1.a==0) AS x, b FROM t1 WHERE a=0 OR x; ]] end, { -- <tkt-a7b7803e.1> 1, "first" -- </tkt-a7b7803e.1> }) test:do_test( "tkt-a7b7803e.2", function() return test:execsql [[ SELECT a, (t1.b='fuzzy') AS x FROM t1 WHERE x ]] end, { -- <tkt-a7b7803e.2> 99, 1 -- </tkt-a7b7803e.2> }) test:do_test( "tkt-a7b7803e.3", function() return test:execsql [[ SELECT (a=99) AS x, (t1.b='fuzzy') AS y, * FROM t1 WHERE x AND y ]] end, { -- <tkt-a7b7803e.3> 1, 1, 99, "fuzzy" -- </tkt-a7b7803e.3> }) test:do_test( "tkt-a7b7803e.4", function() return test:execsql [[ SELECT (a=99) AS x, (t1.b='first') AS y, * FROM t1 WHERE x OR y ORDER BY a ]] end, { -- <tkt-a7b7803e.4> 0, 1, 0, "first", 1, 0, 99, "fuzzy" -- </tkt-a7b7803e.4> }) test:do_test( "tkt-a7b7803e.5", function() return test:execsql [[ SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b FROM t1 M, t1 N WHERE x OR y ORDER BY M.a, N.a ]] end, { -- <tkt-a7b7803e.5> 0, "first", 1, "first", 1, "fuzzy", 1, "first", 1, "fuzzy", 0, "fuzzy" -- </tkt-a7b7803e.5> }) test:do_test( "tkt-a7b7803e.6", function() return test:execsql [[ SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b FROM t1 M, t1 N WHERE x AND y ORDER BY M.a, N.a ]] end, { -- <tkt-a7b7803e.6> 1, "fuzzy", 1, "first" -- </tkt-a7b7803e.6> }) test:do_test( "tkt-a7b7803e.7", function() return test:execsql [[ SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b FROM t1 M JOIN t1 N ON x AND y ORDER BY M.a, N.a ]] end, { -- <tkt-a7b7803e.7> 1, "fuzzy", 1, "first" -- </tkt-a7b7803e.7> }) test:do_test( "tkt-a7b7803e.8", function() return test:execsql [[ SELECT (M.a=99) AS x, M.b, (N.b='first') AS y, N.b FROM t1 M JOIN t1 N ON x ORDER BY M.a, N.a ]] end, { -- <tkt-a7b7803e.8> 1, "fuzzy", 1, "first", 1, "fuzzy", 0, "fuzzy" -- </tkt-a7b7803e.8> }) test:finish_test()
-- package geniefile for zstd zstd_script = path.getabsolute(path.getdirectory(_SCRIPT)) zstd_root = path.join(zstd_script, "zstd") zstd_includedirs = { zstd_root, path.join(zstd_root, "lib"), } zstd_defines = { --"ZSTD_LEGACY_SUPPORT=5", } zstd_libdirs = {} zstd_links = {} ---- return { _add_includedirs = function() includedirs { zstd_includedirs } end, _add_defines = function() defines { zstd_defines } end, _add_libdirs = function() libdirs { zstd_libdirs } end, _add_external_links = function() links { zstd_links } end, _add_self_links = function() links { "zstd" } end, _create_projects = function() group "thirdparty" project "zstd" kind "StaticLib" language "C" flags {} configuration {} includedirs { zstd_includedirs, path.join(zstd_root, "lib", "common"), path.join(zstd_root, "lib", "compress"), path.join(zstd_root, "lib", "decompress"), path.join(zstd_root, "lib", "dictBuilder"), path.join(zstd_root, "lib", "legacy"), } defines { zstd_defines, 'XXH_NAMESPACE=ZSTD_', 'ZSTD_LEGACY_SUPPORT=0', 'BACKTRACE_ENABLE=0', 'ZSTD_MULTITHREAD', } files { path.join(zstd_root, "**.h"), path.join(zstd_root, "lib", "common", "*.c"), path.join(zstd_root, "lib", "compress", "*.c"), path.join(zstd_root, "lib", "decompress", "*.c"), path.join(zstd_root, "lib", "dictBuilder", "*.c"), path.join(zstd_root, "lib", "deprecated", "*.c"), --path.join(zstd_root, "lib", "legacy", "*.c"), } build_c11() --- end, -- _create_projects() } ---
local parent, ns = ... local global = GetAddOnMetadata(parent, 'X-oUF') local _VERSION = GetAddOnMetadata(parent, 'version') local function argcheck(value, num, ...) assert(type(num) == 'number', "Bad argument #2 to 'argcheck' (number expected, got "..type(num)..")") for i=1,select("#", ...) do if type(value) == select(i, ...) then return end end local types = strjoin(", ", ...) local name = string.match(debugstack(2,2,0), ": in function [`<](.-)['>]") error(("Bad argument #%d to '%s' (%s expected, got %s"):format(num, name, types, type(value)), 3) end local print = function(...) print("|cff33ff99oUF:|r", ...) end local error = function(...) print("|cffff0000Error:|r "..string.format(...)) end local dummy = function() end -- Colors local colors = { happiness = { [1] = {1, 0, 0}, -- need.... | unhappy [2] = {1, 1, 0}, -- new..... | content [3] = {0, 1, 0}, -- colors.. | happy }, smooth = { 1, 0, 0, 1, 1, 0, 0, 1, 0 }, disconnected = {.6, .6, .6}, tapped = {.6,.6,.6}, class = {}, reaction = {}, } -- We do this because people edit the vars directly, and changing the default -- globals makes SPICE FLOW! if(IsAddOnLoaded'!ClassColors' and CUSTOM_CLASS_COLORS) then local updateColors = function() for eclass, color in next, CUSTOM_CLASS_COLORS do colors.class[eclass] = {color.r, color.g, color.b} end local oUF = ns.oUF or _G[parent] if(oUF) then for _, obj in next, oUF.objects do obj:UpdateAllElements("CUSTOM_CLASS_COLORS") end end end updateColors() CUSTOM_CLASS_COLORS:RegisterCallback(updateColors) else for eclass, color in next, RAID_CLASS_COLORS do colors.class[eclass] = {color.r, color.g, color.b} end end for eclass, color in next, FACTION_BAR_COLORS do colors.reaction[eclass] = {color.r, color.g, color.b} end -- add-on object local oUF = {} local event_metatable = { __call = function(funcs, self, ...) for _, func in next, funcs do func(self, ...) end end, } local styles, style = {} local callback, units, objects = {}, {}, {} local select = select local UnitExists = UnitExists local conv = { ['playerpet'] = 'pet', ['playertarget'] = 'target', } local elements = {} local enableTargetUpdate = function(object) -- updating of "invalid" units. local OnTargetUpdate do local timer = 0 OnTargetUpdate = function(self, elapsed) if(not self.unit) then return elseif(timer >= .5) then self:UpdateAllElements'OnTargetUpdate' timer = 0 end timer = timer + elapsed end end object:SetScript("OnUpdate", OnTargetUpdate) end -- Events local OnEvent = function(self, event, ...) if(not self:IsShown()) then return end return self[event](self, event, ...) end local iterateChildren = function(...) for l = 1, select("#", ...) do local obj = select(l, ...) if(type(obj) == 'table' and obj.isChild) then local unit = SecureButton_GetModifiedUnit(obj) local subUnit = conv[unit] or unit units[subUnit] = obj obj.unit = subUnit obj:UpdateAllElements"PLAYER_ENTERING_WORLD" end end end local OnAttributeChanged = function(self, name, value) if(name == "unit" and value) then units[value] = self if(self.unit and self.unit == value) then return else if(self.hasChildren) then iterateChildren(self:GetChildren()) end self.unit = SecureButton_GetModifiedUnit(self) self.id = value:match"^.-(%d+)" self:UpdateAllElements"PLAYER_ENTERING_WORLD" end end end do local HandleFrame = function(baseName) local frame if(type(baseName) == 'string') then frame = _G[baseName] else frame = baseName end if(frame) then frame:UnregisterAllEvents() frame.Show = dummy frame:Hide() local health = frame.healthbar if(health) then health:UnregisterAllEvents() end local power = frame.manabar if(power) then power:UnregisterAllEvents() end local spell = frame.spellbar if(spell) then spell:UnregisterAllEvents() end end end function oUF:DisableBlizzard(unit, object) if(not unit) then return end local baseName if(unit == 'player') then HandleFrame(PlayerFrame) -- For the damn vehicle support: PlayerFrame:RegisterEvent('UNIT_ENTERING_VEHICLE') PlayerFrame:RegisterEvent('UNIT_ENTERED_VEHICLE') PlayerFrame:RegisterEvent('UNIT_EXITING_VEHICLE') PlayerFrame:RegisterEvent('UNIT_EXITED_VEHICLE') elseif(unit == 'pet') then baseName = PetFrame elseif(unit == 'target') then if(object) then object:RegisterEvent('PLAYER_TARGET_CHANGED', object.UpdateAllElements) end HandleFrame(TargetFrame) return HandleFrame(ComboFrame) elseif(unit == 'mouseover') then if(object) then return object:RegisterEvent('UPDATE_MOUSEOVER_UNIT', object.UpdateAllElements) end elseif(unit == 'focus') then if(object) then object:RegisterEvent('PLAYER_FOCUS_CHANGED', object.UpdateAllElements) end baseName = FocusFrame elseif(unit:match'%w+target') then if(unit == 'targettarget') then baseName = TargetFrameToT end enableTargetUpdate(object) elseif(unit:match'(boss)%d?$' == 'boss') then enableTargetUpdate(object) local id = unit:match'boss(%d)' if(id) then baseName = 'Boss' .. id .. 'TargetFrame' else for i=1, 3 do HandleFrame(('Boss%dTargetFrame'):format(i)) end end elseif(unit:match'(party)%d?$' == 'party') then local id = unit:match'party(%d)' if(id) then baseName = 'PartyMemberFrame' .. id else for i=1, 4 do HandleFrame(('PartyMemberFrame%d'):format(i)) end end end if(baseName) then return HandleFrame(baseName) end end end local frame_metatable = { __index = CreateFrame"Button" } for k, v in pairs{ colors = colors; EnableElement = function(self, name, unit) argcheck(name, 2, 'string') argcheck(unit, 3, 'string', 'nil') local element = elements[name] if(not element) then return end local updateFunc = element.update local elementTable = self[name] if(type(elementTable) == 'table' and elementTable.Update) then updateFunc = elementTable.Update end if(element.enable(self, unit or self.unit)) then table.insert(self.__elements, updateFunc) end end, DisableElement = function(self, name) argcheck(name, 2, 'string') local element = elements[name] if(not element) then return end local updateFunc = element.update local elementTable = self[name] if(type(elementTable) == 'table' and elementTable.Update) then updateFunc = elementTable.Update end for k, update in next, self.__elements do if(update == updateFunc) then table.remove(self.__elements, k) -- We need to run a new update cycle incase we knocked ourself out of sync. -- The main reason we do this is to make sure the full update is completed -- if an element for some reason removes itself _during_ the update -- progress. self:UpdateAllElements('DisableElement', name) break end end return element.disable(self) end, UpdateElement = function(self, name) argcheck(name, 2, 'string') local element = elements[name] if(not element) then return end local updateFunc = element.update local elementTable = self[name] if(type(elementTable) == 'table' and elementTable.Update) then updateFunc = elementTable.Update end updateFunc(self, 'UpdateElement', self.unit) end, Enable = RegisterUnitWatch, Disable = function(self) UnregisterUnitWatch(self) self:Hide() end, UpdateAllElements = function(self, event) local unit = self.unit if(not UnitExists(unit)) then return end for _, func in next, self.__elements do func(self, event, unit) end end, } do frame_metatable.__index[k] = v end do local RegisterEvent = frame_metatable.__index.RegisterEvent function frame_metatable.__index:RegisterEvent(event, func) argcheck(event, 2, 'string') if(type(func) == 'string' and type(self[func]) == 'function') then func = self[func] end local curev = self[event] if(curev and func) then if(type(curev) == 'function') then self[event] = setmetatable({curev, func}, event_metatable) else for _, infunc in next, curev do if(infunc == func) then return end end table.insert(curev, func) end elseif(self:IsEventRegistered(event)) then return else if(func) then self[event] = func elseif(not self[event]) then return error("Handler for event [%s] on unit [%s] does not exist.", event, self.unit or 'unknown') end RegisterEvent(self, event) end end end do local UnregisterEvent = frame_metatable.__index.UnregisterEvent function frame_metatable.__index:UnregisterEvent(event, func) argcheck(event, 2, 'string') local curev = self[event] if(type(curev) == 'table' and func) then for k, infunc in next, curev do if(infunc == func) then curev[k] = nil if(#curev == 0) then table.remove(curev, k) UnregisterEvent(self, event) end break end end else self[event] = nil UnregisterEvent(self, event) end end end local ColorGradient do local inf = math.huge -- http://www.wowwiki.com/ColorGradient function ColorGradient(perc, ...) -- Translate divison by zeros into 0, so we don't blow select. -- We check perc against itself because we rely on the fact that NaN can't equal NaN. if(perc ~= perc or perc == inf) then perc = 0 end if perc >= 1 then local r, g, b = select(select('#', ...) - 2, ...) return r, g, b elseif perc <= 0 then local r, g, b = ... return r, g, b end local num = select('#', ...) / 3 local segment, relperc = math.modf(perc*(num-1)) local r1, g1, b1, r2, g2, b2 = select((segment*3)+1, ...) return r1 + (r2-r1)*relperc, g1 + (g2-g1)*relperc, b1 + (b2-b1)*relperc end end frame_metatable.__index.ColorGradient = ColorGradient oUF.ColorGradient = ColorGradient local initObject = function(unit, style, styleFunc, ...) local num = select('#', ...) for i=1, num do local object = select(i, ...) object.__elements = {} object = setmetatable(object, frame_metatable) -- Attempt to guess what the header is set to spawn. local parent = object:GetParent() if(not unit) then if(parent:GetAttribute'showRaid') then unit = 'raid' elseif(parent:GetAttribute'showParty') then unit = 'party' end end -- Run it before the style function so they can override it. object:SetAttribute("*type1", "target") object.style = style if(num > 1) then if(i == 1) then object.hasChildren = true else object.isChild = true end end -- Register it early so it won't be executed after the layouts PEW, if they -- have one. object:RegisterEvent("PLAYER_ENTERING_WORLD", object.UpdateAllElements) styleFunc(object, unit) local height = object:GetAttribute'initial-height' local width = object:GetAttribute'initial-width' local scale = object:GetAttribute'initial-scale' local suffix = object:GetAttribute'unitsuffix' local combat = InCombatLockdown() if(height) then object:SetAttribute('initial-height', height) if(not combat) then object:SetHeight(height) end end if(width) then object:SetAttribute("initial-width", width) if(not combat) then object:SetWidth(width) end end if(scale) then object:SetAttribute("initial-scale", scale) if(not combat) then object:SetScale(scale) end end local showPlayer if(i == 1) then showPlayer = parent:GetAttribute'showPlayer' or parent:GetAttribute'showSolo' end if(suffix and suffix:match'target' and (i ~= 1 and not showPlayer)) then enableTargetUpdate(object) else object:SetScript("OnEvent", OnEvent) end object:SetScript("OnAttributeChanged", OnAttributeChanged) object:SetScript("OnShow", object.UpdateAllElements) for element in next, elements do object:EnableElement(element, unit) end for _, func in next, callback do func(object) end -- We could use ClickCastFrames only, but it will probably contain frames that -- we don't care about. table.insert(objects, object) _G.ClickCastFrames = ClickCastFrames or {} ClickCastFrames[object] = true end end local walkObject = function(object, unit) local style = object:GetParent().style or style local styleFunc = styles[style] return initObject(unit, style, styleFunc, object, object:GetChildren()) end function oUF:RegisterInitCallback(func) table.insert(callback, func) end function oUF:RegisterMetaFunction(name, func) argcheck(name, 2, 'string') argcheck(func, 3, 'function', 'table') if(frame_metatable.__index[name]) then return end frame_metatable.__index[name] = func end function oUF:RegisterStyle(name, func) argcheck(name, 2, 'string') argcheck(func, 3, 'function', 'table') if(styles[name]) then return error("Style [%s] already registered.", name) end if(not style) then style = name end styles[name] = func end function oUF:SetActiveStyle(name) argcheck(name, 2, 'string') if(not styles[name]) then return error("Style [%s] does not exist.", name) end style = name end do local function iter(_, n) -- don't expose the style functions. return (next(styles, n)) end function oUF.IterateStyles() return iter, nil, nil end end local getCondition do local conditions = { raid40 = '[@raid26,exists] show;', raid25 = '[@raid11,exists] show;', raid10 = '[@raid6,exists] show;', raid = '[group:raid] show;', party = '[group:party,nogroup:raid] show;', solo = '[@player,exists,nogroup:party] show;', } function getCondition(...) local cond = '' for i=1, select('#', ...) do local short = select(i, ...) local condition = conditions[short] if(condition) then cond = cond .. condition end end return cond .. 'hide' end end local generateName = function(unit, ...) local name = 'oUF_' .. style:gsub('[^%a%d_]+', '') local raid, party, groupFilter for i=1, select('#', ...), 2 do local att, val = select(i, ...) if(att == 'showRaid') then raid = true elseif(att == 'showParty') then party = true elseif(att == 'groupFilter') then groupFilter = val end end local append if(raid) then if(groupFilter) then if(groupFilter:match'TANK') then append = 'MainTank' elseif(groupFilter:match'ASSIST') then append = 'MainAssist' else local _, count = groupFilter:gsub(',', '') if(count == 0) then append = groupFilter else append = 'Raid' end end else append = 'Raid' end elseif(party) then append = 'Party' elseif(unit) then append = unit:gsub("^%l", string.upper) end if(append) then name = name .. append end local base = name local i = 2 while(_G[name]) do name = base .. i i = i + 1 end return name end function oUF:SpawnHeader(overrideName, template, visibility, ...) if(not style) then return error("Unable to create frame. No styles have been registered.") end local name = overrideName or generateName(nil, ...) local header = CreateFrame('Frame', name, UIParent, template or 'SecureGroupHeaderTemplate') header.initialConfigFunction = walkObject header.style = style header:SetAttribute("template", "SecureUnitButtonTemplate") for i=1, select("#", ...), 2 do local att, val = select(i, ...) if(not att) then break end header:SetAttribute(att, val) end if(header:GetAttribute'showParty') then self:DisableBlizzard'party' end if(visibility) then local type, list = string.split(' ', visibility, 2) if(list and type == 'custom') then RegisterStateDriver(header, 'visibility', list) else local condition = getCondition(string.split(',', visibility)) RegisterStateDriver(header, 'visibility', condition) end end return header end function oUF:Spawn(unit, overrideName) argcheck(unit, 2, 'string') if(not style) then return error("Unable to create frame. No styles have been registered.") end unit = unit:lower() local name = overrideName or generateName(unit) local object = CreateFrame("Button", name, UIParent, "SecureUnitButtonTemplate") object.unit = unit object.id = unit:match"^.-(%d+)" units[unit] = object walkObject(object, unit) object:SetAttribute("unit", unit) RegisterUnitWatch(object) self:DisableBlizzard(unit, object) return object end do local _QUEUE = {} local _FACTORY = CreateFrame'Frame' _FACTORY:SetScript('OnEvent', OnEvent) _FACTORY:RegisterEvent'PLAYER_LOGIN' _FACTORY.active = true function _FACTORY:PLAYER_LOGIN() if(not self.active) then return end for _, func in next, _QUEUE do func(oUF) end end function oUF:Factory(func) argcheck(func, 2, 'function') table.insert(_QUEUE, func) end function oUF:EnableFactory() _FACTORY.active = true end function oUF:DisableFactory() _FACTORY.active = nil end end function oUF:AddElement(name, update, enable, disable) argcheck(name, 2, 'string') argcheck(update, 3, 'function', 'nil') argcheck(enable, 4, 'function', 'nil') argcheck(disable, 5, 'function', 'nil') if(elements[name]) then return error('Element [%s] is already registered.', name) end elements[name] = { update = update; enable = enable; disable = disable; } end oUF.version = _VERSION oUF.units = units oUF.objects = objects oUF.colors = colors oUF.error = error if(global) then if(parent ~= 'oUF' and global == 'oUF') then error("%s is doing it wrong and setting its global to oUF.", parent) else _G[global] = oUF end end ns.oUF = oUF
local db = dofile 'libs/redis.lua' local tdcli = dofile 'bot/utlis.lua' botid = false local serp = require 'serpent'.block local JSON = dofile 'libs/JSON.lua' local _config = dofile 'data/td_config.lua' local _color = require 'term.colors' require('./bot/utlis') chats = {} day = 86400 bot_id = 322190322 --- You Bot ID sudo_users = {274807882}--Your id function chat_leave(chat_id, user_id) changeChatMemberStatus(chat_id, user_id, "Left") end function add_user(chat_id, user_id, forward_limit) tdcli_function ({ ID = "AddChatMember", chat_id_ = chat_id, user_id_ = user_id, forward_limit_ = forward_limit or 50 }, dl_cb, nil) end local function chat_type(data) local msg = data.message_ if msg.chat_id_:match('^-100(%d+)') then chat_type = 'supergroups' elseif msg.chat_id_:match('^(%d+)') then chat_type = 'private' end return chat_type end function sleep(time) os.execute("sleep " .. tonumber(time)) end function vardump(data) print(serp(data, {comment=false})) end local function tdump(data) return serp(data, {comment=false}) end local function reload() loadfile("./bot/bot.lua")() end local function write_var(var, file_name) file = io.open(file_name, "w") if not file then return false end file:write(tdump(var)) file:close() end local function print_res(arg, data) write_var(data, arg.file_path) end ---- Sudo ---- local function sudo(data) local msg = data.message_ local user_id = msg.sender_user_id_ local chat_id = msg.chat_id_ for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end local function sudo2(user_id) for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end ---- Admin ---- local function admin(data) local msg = data.message_ local user_id = msg.sender_user_id_ local chat_id = msg.chat_id_ local admins = db:sismember('max:adminss',user_id) if admins then return true end for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end local function admin2(user_id) local admins = db:sismember('max:adminss',user_id) if admins then return true end for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end ---- Owner ---- local function owner(data) local msg = data.message_ local user_id = msg.sender_user_id_ local chat_id = msg.chat_id_ local admins = db:sismember('max:adminss',user_id) if admins then return true end local owners = db:sismember('gp:owners:'..chat_id,user_id) if owners then return true end for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end local function owner2(chat_id, user_id) local admins = db:sismember('max:adminss',user_id) if admins then return true end local owners = db:sismember('gp:owners:'..chat_id,user_id) if owners then return true end for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end ----- Mod ----- local function mod(data) local msg = data.message_ local user_id = msg.sender_user_id_ local chat_id = msg.chat_id_ local admins = db:sismember('max:adminss',user_id) if admins then return true end local mod = db:sismember('gp:mods:'..chat_id,user_id) if mod then return true end local owners = db:sismember('gp:owners:'..chat_id,user_id) if owners then return true end for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end local function mod2(chat_id, user_id) local admins = db:sismember('max:adminss',user_id) if admins then return true end local mod = db:sismember('gp:mods:'..chat_id,user_id) if mod then return true end local owners = db:sismember('gp:owners:'..chat_id,user_id) if owners then return true end for k,user in pairs(_config.sudo_users) do if user == user_id then return true end end end ----------------End------------------ ---- CallBack ---- local function delUser(chat_id, user_id) tdcli.changeChatMemberStatus(chat_id, user_id, 'Kicked') end ---- Mute Reply ---- local function mute_reply(extra, result, success) t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if mod2(ch, user) then tdcli.sendMessage(ch, msg_id, 1, "*Error*\n_You Can't Mute Mods/Owners/Admins...!_", 1, 'md') else if db:sismember('mutes:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Already Muted...!_", 1, 'md') else db:sadd('mutes:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n_User ["..user.."] Added To Mute List...!_", 1, 'md') print(user) end end end local function mute_username(extra, result, success) vardump(result) chat_id = db:get('chatid') if mod2(chat_id, result.id_) then tdcli.sendMessage(chat_id,0, 1, "*Error*\n_You Can't Mute Mods/Owners/Admins...!_", 1, 'md') else if db:sismember('mutes:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Already Muted...!_", 1, 'md') else db:sadd('mutes:'..chat_id, result.id_) tdcli.sendMessage(chat_id, 0, 1,'*Done*\n_User ['..result.id_..'] Added To Mute List..!_',0,'md') db:del('chatid') end end end local function unmute_reply(extra, result, success) t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if not db:sismember('mutes:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Not Muted...!_", 1, 'md') else db:srem('mutes:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n_User ["..user.."] Removed From Mute List...!_", 1, 'md') print(user) end end local function unmute_username(extra, result, success) vardump(result) chat_id = db:get('chatid') if not db:sismember('mutes:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Not Muted...!_", 1, 'md') else db:srem('mutes:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Removed From Mute List..!_',0,'md') db:del('chatid') end end ---- Id Reply ---- local function id_reply(extra, result, success) t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ tdcli.sendMessage(ch, msg_id, 1, "*> Chat Id :* [-100"..ch:gsub('-100','').."]\n*> User Id :* ["..user.."]", 1, 'md') print(user) end ---- Delete Messages Reply ---- local function del_reply(extra, result, success) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ --tdcli.deleteMessagesFromUser(ch,user) print(user) end ---- Gban Reply ---- local function gban_reply(extra, result, success) t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if admin2(user) then tdcli.sendMessage(ch, msg_id, 1, "*Error*\n_You Can't GBan /Admins...!_", 1, 'md') else if db:sismember('gbans:user', user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Already_ *Globally Banned..!*", 1, 'md') else db:sadd('gbans:user',user) tdcli.changeChatMemberStatus(ch, user, 'Kicked') tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Globally Banned..!*", 1, 'md') print(user) end end end local function gban_username(extra, result, success) vardump(result) chat_id = db:get('chatid') if mod2(chat_id, result.id_) then tdcli.sendMessage(chat_id,0, 1, "*Error*\n_You Can't Gban Admins...!_", 1, 'md') else if db:sismember('gbans:user:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Already_ *Globally Banned..!*", 1, 'md') else db:sadd('gbans:user:'..chat_id, result.id_) tdcli.changeChatMemberStatus(chat_id, result.id_, 'Kicked') tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Globally Banned..!_',0,'md') db:del('chatid') end end end ---- UnGan Reply ---- local function ungban_reply(extra, result, success) --t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if not db:sismember('gbans:user', user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Not_ *Globally Banned..!*", 1, 'md') else db:srem('gbans:user',user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Unglobally Banned..!*", 1, 'md') print(user) end end local function ungban_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if not db:sismember('gbans:user:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Not_ *Globally Banned..!*", 1, 'md') else db:srem('gbans:user:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..']_ *UnGlobally Banned..!*',0,'md') db:del('chatid') end end ---- Gban Reply ---- local function ban_reply(extra, result, success) --t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if mod2(ch, user) then tdcli.sendMessage(ch, msg_id, 1, "*Error*\n_You Can't Ban Mods/Owners/Admins...!_", 1, 'md') else if db:sismember('bans:gp:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Already_ *Banned..!*", 1, 'md') else db:sadd('bans:gp:'..ch,user) tdcli.changeChatMemberStatus(ch, user, 'Kicked') tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Banned..!*", 1, 'md') print(user) end end end local function ban_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if mod2(chat_id, result.id_) then tdcli.sendMessage(chat_id,0, 1, "*Error*\n_You Can't Ban Mods/Owners/Admins...!_", 1, 'md') else if db:sismember('bans:gp:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Already Banned...!_", 1, 'md') else db:sadd('bans:gp:'..chat_id, result.id_) tdcli.changeChatMemberStatus(chat_id, result.id_, 'Kicked') tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Banned..!_',0,'md') db:del('chatid') end end end ---- UnBan Reply ---- local function unban_reply(extra, result, success) --t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if not db:sismember('bans:gp:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Not_ *Banned..!*", 1, 'md') else db:srem('bans:gp:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *UnBanned..!*", 1, 'md') print(user) end end local function unban_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if not db:sismember('bans:gp:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Not Banned...!_", 1, 'md') else db:srem('bans:gp:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Unbanned..!_',0,'md') db:del('chatid') end end ---- DeAdmin Reply ---- local function deadmin_reply(extra, result, success) --t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if not db:sismember('max:adminss', user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Not_ *Globally Admin..!*", 1, 'md') else db:srem('max:adminss',user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Demoted From Global Admin..!*", 1, 'md') print(user) end end local function deadmin_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if not db:sismember('max:adminss', result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Not Globally Admin...!_", 1, 'md') else db:srem('max:adminss', result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Demoted From Globally Admin.!_',0,'md') db:del('chatid') end end ---- SetAdmin Reply ---- local function setadmin_reply(extra, result, success) --t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if db:sismember('max:adminss', user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Already_ *Globally Admin..!*", 1, 'md') else db:sadd('max:adminss',user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Promoted To Global Admin..!*", 1, 'md') print(user) end end local function setadmin_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if db:sismember('max:adminss', result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Already Globally Admin...!_", 1, 'md') else db:sadd('max:adminss', result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Promoted To Globally Admin..!_',0,'md') db:del('chatid') end end ---- SetOwner Reply ---- local function setowner_reply(extra, result, success) -- = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if db:sismember('gp:owners:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Already_ *Group Owner..!*", 1, 'md') else db:sadd('gp:owners:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Promoted To Group Owner..!*", 1, 'md') print(user) end end local function setowner_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if db:sismember('gp:owners:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Already Group Owner...!_", 1, 'md') else db:sadd('gp:owners:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Promoted To Group Owner..!_',0,'md') db:del('chatid') resolve_username(matches[2],setowner_by_username) end end ---- DeOwner Reply ---- local function deowner_reply(extra, result, success) --t = vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if not db:sismember('gp:owners:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Not_ *Group Owner..!*", 1, 'md') else db:srem('gp:owners:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Demoted From Group Owner..!*", 1, 'md') print(user) end end function inv_reply(extra, result, success) add_user(result.chat_id_, result.sender_user_id_, 5) end local function deowner_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if not db:sismember('gp:owners:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Not Group Owner...!_", 1, 'md') else db:srem('gp:owners:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Demoted From Group Owner..!_',0,'md') db:del('chatid') end end ---- Promote Reply ---- local function promote_reply(extra, result, success) --t =-- vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if db:sismember('gp:mods:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Already_ *Group Mod..!*", 1, 'md') else db:sadd('gp:mods:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Promoted..!*", 1, 'md') print(user) end end local function clean_bots(extra,result) for bots=0 ,#result.members_ do local uid = result.members_[bots].user_id_ tdcli.changeChatMemberStatus(extra.gid, uid, 'Kicked') end end local function promote_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if db:sismember('gp:mods:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Already Group Owner...!_", 1, 'md') else db:sadd('gp:mods:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Promoteded..!_',0,'md') db:del('chatid') end end ---- Promote Reply ---- local function demote_reply(extra, result, success) --t = --vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if not db:sismember('gp:mods:'..ch, user) then tdcli.sendMessage(ch, msg_id, 1, "_User ["..user.."] Is Not_ *Group Mod..!*", 1, 'md') else db:srem('gp:mods:'..ch,user) tdcli.sendMessage(ch, msg_id, 1, "*Done*\n*User* _["..user.."]_ *Demoted..!*", 1, 'md') print(user) end end local function demote_username(extra, result, success) --v--ardump(result) chat_id = db:get('chatid') if not db:sismember('gp:mods:'..chat_id, result.id_) then tdcli.sendMessage(chat_id, 0, 1, "_User ["..result.id_.."] Is Not Group Owner...!_", 1, 'md') else db:srem('gp:mods:'..chat_id, result.id_) tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Demoted..!_',0,'md') db:del('chatid') end end -------- Kick ------- local function kick_reply(extra, result, success) --t = --vardump(result) local msg_id = result.id_ local user = result.sender_user_id_ local ch = result.chat_id_ if mod2(ch, user) then tdcli.sendMessage(ch, msg_id, 1, "*Error*\n_You Can't Kick Mods/Owners/Admins...!_", 1, 'md') else tdcli.changeChatMemberStatus(ch, user, 'Kicked') tdcli.sendMessage(ch, msg_id, 1, "*Done*\n_User ["..user.."] Kicked..!_", 1, 'md') print(user) end end local function kick_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') if mod2(chat_id, result.id_) then tdcli.sendMessage(chat_id,0, 1, "*Error*\n_You Can't Kick Mods/Owners/Admins...!_", 1, 'md') else tdcli.changeChatMemberStatus(chat_id, result.id_, 'Kicked') tdcli.sendMessage(chat_id,0,1,'*Done*\n_User ['..result.id_..'] Kicked..!_',0,'md') db:del('chatid') end end -------- UserName CallBack --------- local function info_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') local function dl_photo(arg,data) tdcli.sendPhoto(chat_id, 0, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,result.id_..'\n'..result.type_.user_.first_name_) end tdcli_function ({ID = "GetUserProfilePhotos",user_id_ = result.id_,offset_ = 0,limit_ = 100000}, dl_photo, nil) db:del('chatid') end local function who_username(extra, result, success) --vardump(result) chat_id = db:get('chatid') tdcli.sendMessage(chat_id,0,1,result.id_..'\n'..result.type_.user_.first_name_,0,'md') --tdcli.sendMessage(chat_id,msg.id_,0,result.id_..'\n'..result.type_.user_.first_name_,0,'md') -- tdcli_function ({ID = "GetUserProfilePhotos",user_id_ = result.id_,offset_ = 0,limit_ = 100000}, dl_photo, nil) db:del('chatid') end local function info_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, info_username, extra) end local function who_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, who_username, extra) end local function setowner_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, setowner_username, extra) end local function deowner_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, deowner_username, extra) end local function setadmin_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, setadmin_username, extra) end local function deadmin_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, deadmin_username, extra) end local function gban_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, gban_username, extra) end local function ungban_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, ungban_username, extra) end local function promote_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, promote_username, extra) end local function demote_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, demote_username, extra) end local function ban_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, ban_username, extra) end local function unban_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, unban_username, extra) end local function mute_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, mute_username, extra) end local function unmute_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, unmute_username, extra) end local function kick_user(username) tdcli_function ({ ID = "SearchPublicChat", username_ = username }, kick_username, extra) end -------- GetMessage ------- local function getMessage(chat_id, message_id,callback) tdcli_function ({ ID = "GetMessage", chat_id_ = chat_id, message_id_ = message_id }, callback, nil) end local function trigger_anti_spam(msg, chat_id, user_id,action) --#NFS tdcli.sendMessage(chat_id,0,0,'دادش داری اشتباه میزنی',1,'md') if action == 'kick' then --deleteMessagesFromUser(chat_id, user_id, cb, cmd) deldelUser(chat_id, user_id) elseif action == 'ban' then --deleteMessagesFromUser(chat_id, user_id, cb, cmd) end msg = nil return end function tdcli_update_callback(data) -------------Get Bot ID----------- if not botid then local function GetBotID(arg,data) botid = data.id_ end tdcli_function ({ ID = "GetMe", }, GetBotID, nil) end --------- Welcome Setp -------- if data.ID == 'UpdateChatTopMessage' then local msg = data.top_message_ local chat = data.chat_id_ if type(msg.reply_markup_) ~= 'boolean' then print('key') if db:get('keyboard:Lock:'..data.top_message_.chat_id_) == 'Lock' then local gid = data.top_message_.chat_id_ tdcli.deleteMessages(data.chat_id_,{[0] = data.top_message_.message_id_}) end end if data.top_message_.via_bot_user_id_ ~= 0 then print('bot') if db:get('inline:Lock:'..data.top_message_.chat_id_) == 'Lock' then local gid = data.top_message_.chat_id_ tdcli.deleteMessages(data.chat_id_,{[0] = data.top_message_.message_id_}) end end if data.message_ and data.message_.content_.members_ and data.message_.content_.members_[0].type_.ID == 'UserTypeBot' then local gid = tonumber(data.message_.chat_id_) local uid = data.message_.sender_user_id_ local aid = data.message_.content_.members_[0].id_ local id = data.message_.id_ if db:get('bot:Lock:'..data.chat_id_) == 'Lock' then tdcli.changeChatMemberStatus(gid, aid, 'Kicked') tdcli.changeChatMemberStatus(gid, uid, 'Kicked') end end local msg = data.top_message_ local chat = data.chat_id_ if data.top_message_.content_.ID == 'MessageChatDeleteMember' and db:get('bye:Enable:'..msg.chat_id_) == 'Enable' then local info = data.top_message_.content_ vardump(data) tdcli.sendMessage(chat,0, 1,'Bye Bye '..info.user_.first_name_, 1, 'md') end if data.top_message_.content_.ID == 'MessageChatAddMembers' or data.top_message_.content_.ID == 'MessageChatJoinByLink' and db:get('wlc:Enable:'..msg.chat_id_) == 'Enable' then local info = data.top_message_.content_ local name = info.members_[0].first_name_ local username = info.members_[0].username_ local chat = data.top_message_.chat_id_ local wlc_msg = db:hget('wlc',chat) print(name) local welcome = wlc_msg:gsub('{username}',username) or "None" local welcome = welcome:gsub('{name}',name) or "None" tdcli.sendMessage(chat,0, 1,welcome, 1, 'md') end --------- End Welcome Step --------- if msg.content_.ID == 'MessagePinMessage' then if db:get('pin:Lock:'..data.top_message_.chat_id_) == 'Lock' and db:get('pin:post:'..data.top_message_.chat_id_) then if msg.sender_user_id_ ~= botid then tdcli.unpinChannelMessage(data.top_message_.chat_id_) tdcli.sendMessage(data.top_message_.chat_id_,0, 1,'Just Reply The Message And Send (pin)...!', 1, 'md') tdcli.pinChannelMessage(data.top_message_.chat_id_,db:get('pin:post:'..data.top_message_.chat_id_),0) else db:set('pin:post:'..data.top_message_.chat_id_,data.top_message_.content_.message_id_) tdcli.sendMessage(data.top_message_.chat_id_,0, 1,'_Pin with Bot_', 1, 'md') end elseif not db:get('pin:post:'..data.top_message_.chat_id_) then db:set('pin:post:'..data.top_message_.chat_id_,data.top_message_.content_.message_id_) tdcli.sendMessage(data.top_message_.chat_id_,0, 1,'Pin msg has been seted', 1, 'md') end end if data.ID == 'UpdateMessageEdited' then if data.ID == 'UpdateMessageEdited' then if db:get('edit:Show:'..data.chat_id_) == 'Show' then text = db:hget('msgs:'..data.chat_id_,data.message_id_) tdcli.sendMessage(data.chat_id_,data.message_id_,0,'خخخ چرا ادیت کردی پیامتو��\nدیدم گفتی:\n'..text,1,'md') db:hset('msgs:'..data.chat_id_,data.message_id_,data.new_content_.text_) --db:hdel('msgs:'..data.sender_user_id,data.message_id_) end if db:get('edit:Lock:'..data.chat_id_) == 'Lock' then tdcli.deleteMessages(data.chat_id_,{[0] = data.message_id_}) end end end end ------- Start Project ------- if (data.ID == "UpdateNewMessage") then local msg = data.message_ if msg.date_ < (os.time() - 30) then return false end local group = db:sismember('gpo',msg.chat_id_) local ch = msg.chat_id_ local user_id = msg.sender_user_id_ if not group and not db:get("bot:enable:"..msg.chat_id_) and not admin(data) then return false end if not db:get("bot:charge:"..msg.chat_id_) then if db:get("bot:enable:"..msg.chat_id_) then db:del("bot:enable:"..msg.chat_id_) for k,v in pairs(sudo_users) do tdcli.sendMessage(v, 0, 1, "شارژ این گروه به اتمام رسید \nLink : "..(db:get("bot:group:link"..msg.chat_id_) or "تنظیم نشده").."\nID : "..msg.chat_id_..'\n\nدر صورتی که میخواهید ربات این گروه را ترک کند از دستور زیر استفاده کنید\n\n/leave'..msg.chat_id_..'\nبرای جوین دادن توی این گروه میتونی از دستور زیر استفاده کنی:\n/join'..msg.chat_id_..'\n_________________\nدر صورتی که میخواهید گروه رو دوباره شارژ کنید میتوانید از کد های زیر استفاده کنید...\n\n<code>برای شارژ 1 ماهه:</code>\n/plan1'..msg.chat_id_..'\n\n<code>برای شارژ 3 ماهه:</code>\n/plan2'..msg.chat_id_..'\n\n<code>برای شارژ نامحدود:</code>\n/plan3'..msg.chat_id_, 1, 'html') end tdcli.sendMessage(msg.chat_id_, 0, 1, 'شارژ این گروه به اتمام رسید و ربات در گروه غیر فعال شد...\nبرای تمدید کردن ربات به @pedaret پیام دهید.\nدر صورت ریپورت بودن میتوانید با ربات زیر با ما در ارتباط باشید:\n @awmin_pvbott', 1, 'html') tdcli.sendMessage(msg.chat_id_, 0, 1, 'ربات به دلایلی گروه را ترک میکند\nبرای اطلاعات بیشتر میتوانید با @pedaret در ارتباط باشید.\nدر صورت ریپورت بودن میتوانید با ربات زیر به ما پیام دهید\n@awminpv_bot', 1, 'html') chat_leave(msg.chat_id_, bot_id) end end local floods = db:get('flood:Lock:'..ch) or 'off' local max_msg = db:get('flood-spam:'..ch) or 20 local max_time = db:get('flood-time:'..ch) or 20 if floods == 'Lock' and not mod(data) then local post_count = 'floodc:' .. msg.sender_user_id_ .. ':' .. msg.chat_id_ db:incr(post_count) local post_count = 'user:' .. msg.sender_user_id_ .. ':floodc' local msgs = tonumber(db:get(post_count) or 0) if tonumber(msgs) > tonumber(max_msg) then trigger_anti_spam(msg, msg.chat_id_, msg.sender_user_id_,'kick') end db:setex(post_count, tonumber(max_time), tonumber(msgs)+1) end local edit_id = data.text_ or 'nil' --------Bot Settings------- if msg.forward_info_ and db:get('fwd:Lock:'..msg.chat_id_) == 'Lock' and not mod(data) then tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}) end if msg.forward_info_ and db:get('userid:'..msg.sender_user_id_) then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'Post Views => `'..msg.views_..'`', 1, 'md') db:del('userid:'..msg.sender_user_id_) end if msg.content_.voice_ or msg.content_.audio_ or msg.content_.video_ or msg.content_.photo_ or msg.content_.animation_ or msg.content_.document_ or msg.content_.contact_ or msg.content_.sticker_ or msg.content_.text_ or msg.content_.location_ or msg.content_.caption_ then if db:get('user_id:'..msg.sender_user_id_) then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'File Caption => ['..msg.content_.caption_..']', 1,'html') db:del('user_id:'..msg.sender_user_id_) end if not mod(data) then if msg.content_.photo_ and db:get('photo:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.voice_ and db:get('voice:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.contact_ and db:get('contact:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.audio_ and db:get('audio:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.location_ and db:get('location:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.video_ and db:get('video:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.animation_ and db:get('animation:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.sticker_ and db:get('sticker:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.document_ and db:get('document:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.location_ and db:get('location:Lock:'..msg.chat_id_) == 'Lock' then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if msg.content_.caption_ then text_cheack = msg.content_.caption_ else text_cheack = msg.content_.text_ end if db:get('arabic:Lock:'..msg.chat_id_) == 'Lock' and text_cheack:match('[\216-\219][\128-\191]') then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if db:get('en:Lock:'..msg.chat_id_) == 'Lock' and text_cheack:find('[ASDFGHJKLQWERTYUIOPZXCVBNMasdfghjklqwertyuiopzxcvbnm]')then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if db:get('tag:Lock:'..msg.chat_id_) == 'Lock' and text_cheack:lower():find('#') then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end ------------BadWord----------- if not mod(data) then local hash = 'badwords:'..msg.chat_id_..":badword" local names = db:hkeys(hash) for i=1, #names do if string.match(msg.content_.text_:lower(), names[i]) then return tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}) end end if msg.content_.caption_ then for i=1, #names do if string.match(msg.content_.text_:lower(), names[i]) then return tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}) end end end end if db:get('emoji:Lock:'..msg.chat_id_) == 'Lock' and text_cheack:lower():match("[😀😃😄😁😆😅😂☺️😊😇🙂🙃😉😌😍😘😗😙😚😋😜😝😛🤑🤗🤓😎😏😒😞😔😟😕🙁☹️😣😖😫😩😤😠😡😶😐😑😯😦😧😮😲😵😳😱😨😰😢😥😭😓😪😴🙄🤔😬🤐😷🤒🤕😈👿👽☠💀👻💩👹👺👾🤖🎃😺😸😹😻🙌👐😾😿🙀😽😼👏🙏👍👎👊✊👈👌🤘✌️👉👆👇☝️✋🖐✍🖕💪👋🖖💅💍💄💋👄👅👂👥👤🗣👀👁👣👃👶👦👧👨👩👱‍👱👮👮‍👳👳‍👲👵👴👷‍👷💂‍💂🕵‍🕵👩‍⚕👨‍🎓👩‍🎓👨‍🍳👩‍🍳👨‍🌾👩‍🌾👨‍⚕👩‍🎤👨‍🎤👩‍🏫👨‍🏫👩‍🏭👨‍🏭👩‍💻👨‍🔬👩‍🔬👨‍🔧👩‍🔧👨‍💼👩‍💼👨‍💻👩‍🎨👨‍🎨👩‍🚒👨‍🚒👩‍✈️👨‍✈️👩‍🚀👸🎅👨‍⚖👩‍⚖👨‍🚀👰👼🙇🙇💁🙋‍🙋🙆‍🙆🙅‍🙅💁🙎🙎🙍💃🕴💆‍💆💇‍💇🙍👯👯‍🚶🚶🏃🏃💏👨‍❤️‍👨👩‍❤️‍👩💑👬👭👫👩‍❤️‍💋‍👩👨‍❤️‍💋‍👨👪👨‍👩‍👧👨‍👩‍👧‍👦👨‍👩‍👦‍👦👨‍👩‍👧‍👧👨‍👨‍👧👨‍👨‍👦👩‍👩‍👧‍👧👩‍👩‍👦‍👦👩‍👩‍👧‍👦👩‍👩‍👧👩‍👩‍👦👨‍👨‍👧‍👦👨‍👨‍👦‍👦👨‍👨‍👧‍👧👩‍👦👩‍👧👩‍👧‍👦👩‍👦‍👦👚👨‍👧‍👧👨‍👦‍👦👨‍👧‍👦👨‍👧👨‍👦👩‍👧‍👧👕👖👔👗👙👘👠🎓🎩👒👟👞👢👡👑⛑🎒👝👛👜💼💛❤️☂🌂🕶👓💙💜💔❣💕💞💝💘💖💗💓]") then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end local mute = db:sismember('mutes:'..ch,user_id) if mute then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) end if db:get('muteall:Lock:'..msg.chat_id_) == 'Lock' then tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}) end end if msg.content_.text_ then db:hset('msgs:'..msg.chat_id_,msg.id_,msg.content_.text_) local text = msg.content_.text_:lower():gsub('^[#!/]','') local link = msg.content_.text_:match('(https?://telegram.me/joinchat/%S+)') or msg.content_.text_:match('(https?://t.me/joinchat/%S+)') if link and tostring(db:get('link:wait:'..msg.chat_id_)) == tostring(msg.sender_user_id_) then local link = msg.content_.text_:match('(https?://telegram.me/joinchat/%S+)') or msg.content_.text_:match('(https?://t.me/joinchat/%S+)') db:set('link:gp:'..msg.chat_id_,link) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Done*\n_Link Has Been Set...!_', 1, 'md') db:del('link:wait:'..msg.chat_id_) end if db:get('md:Lock:'..msg.chat_id_ ) == 'Lock' and msg.content_.entities_[0] then if not mod(data) then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end end local text_cheack = text_cheack or msg.content_.text_ if db:get('links:Lock:'..msg.chat_id_ ) == 'Lock' and text_cheack:lower():match('https://') or text:lower():match('https://telegram.me/') or text_cheack:lower():match('https://telegram.me/joinchat/') or text_cheack:find('https://') or text_cheack:find('https://telegram.me/') or text_cheack:find('https://telegram.me/joinchat/') or text_cheack:find('www') then if not mod(data) then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end end if db:get('username:Lock:'..msg.chat_id_ ) == 'Lock' and text_cheack:lower():match('@') or text_cheack:find('@') then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end if db:get('spam:Lock:'..msg.chat_id_) == 'Lock' then local chare = tonumber(db:get('chare:'..msg.chat_id_) or 0) if string.len(msg.content_.text_) >= chare and not mod(data) then if db:get('security:'..msg.chat_id_) == 'del' then tdcli.deleteMessages(msg.chat_id_,{[0] = msg.id_}) else tdcli.changeChatMemberStatus(msg.chat_id_, msg.sender_user_id_, 'Kicked') end end end -----------Locals---------- local text = msg.content_.text_:lower():gsub('[#!/]','') local chat_id = msg.chat_id_ local msg_id = msg.id_ local reply_msg = msg.reply_to_message_id_ local user_id = msg.sender_user_id_ if db:get('cmd:Lock:'..chat_id) == 'Lock' and not mod(data) then return end --------Commands ------ if msg.content_.text_:match("^getpro") then local matches = { msg.content_.text_:match("(getpro) (%d+)") } if not matches[2] then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '/getpro 1-100', 1,'md') else local function dl_photo(arg,data) tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,''..msg.sender_user_id_..'') end tdcli_function ({ID = "GetUserProfilePhotos",user_id_ = msg.sender_user_id_,offset_ = matches[2],limit_ = 100000}, dl_photo, nil) end end if text:lower() == "ping" then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'Ping...!', 1,'md') elseif text:match('setend (.*)') and sudo(data) then local endmsg = msg.content_.text_:match('setend (.*)') db:set('endmsg',endmsg) tdcli.sendMessage(msg.chat_id_,msg.id_,0,'set to:\n\n'..endmsg,0,'html') elseif text:lower() == 'reload' and sudo(data) then reload() tdcli.sendMessage(chat_id,msg.id_,0,'Reloaded...!',0,'md') elseif text:lower() == 'help' and mod(data) then local text = [[ ��*Help list :* ➖➖➖➖➖➖ �� برای دریافت راهنمای قفل ها : �� !lockhelp �� برای دریافت راهنمای میوت ها : �� !mutehelp ⚄1�7 برای دریافت راهنمای مدیریت گروه : �� !manghelp ➖➖➖➖➖➖ ]] tdcli.sendMessage(msg.chat_id_,0,1,text,0,'md') elseif text:lower() == 'lockhelp' and mod(data) then local text = [[ ��*Help LockList :* ➖➖➖➖➖➖ ◾️قفل/بازکردن لینک : ▪️!lock/unlock *links* ◽️قفل/بازکردن ادیت : ▫️!lock/unlock *edit* ◾️قفل/بازکردن فوروارد : ▪️!lock/unlock *fwd* ◽️ قفل/بازکردن ریپلای : ▫️!lock/unlock *reply* ◾️ قفل/باز کردن فارسی/عربی : ▪️!lock/unlock *arabic* ◽️ قفل/باز کردن انگلیسی : ▫️!lock/unlock *english* ⬛️ قفل/باز کردن فلود : ▪️!lock/unlock *flood* ◽️ قفل/بازکردن خوش آمد گویی : ▫️!*welcome* enable/disable ➖➖➖➖➖➖ ]] tdcli.sendMessage(msg.chat_id_,0,1,text,0,'md') elseif text:lower() == 'mutehelp' and mod(data) then local text = [[ ��*Help MuteList :* ➖➖➖➖➖➖ ◾️میوت/بازکردن چت : ▪️!mute/unmute *all* ◽️میوت/بازکردن عکس : ▫️!mute/unmute *photo* ◾️میوت/بازکردن مدیا : ▪️!mute/unmute *audio* ◽️میوت/بازکردن لوکیشن : ▫️!mute/unmute *location* ◾️میوت/بازکردن استیکر : ▪️!mute/unmute *sticker* ◽️میوت/بازکردن گیف : ▫️!mute/unmute *gif* ⬛️میوت/بازکردن فایل : ▪️!mute/unmute *document* ◽️میوت/بازکردن فیلم : ▫️!mute/unmute *video* ⬛️میوت/بازکردن شماره : ▪️!mute/unmute *contact* ➖➖➖➖➖➖ ]] tdcli.sendMessage(msg.chat_id_,0,1,text,0,'md') elseif text:lower() == 'manghelp' and mod(data) then local text = [[ ⚄1�7*Help Management :* ➖➖➖➖➖➖ ◾️برای حذف کردن فردی از گروه : ▪️!kick [UserName|reply] ◽️برای بن/آنبن کردن فردی از گروه : ▫️!ban/unban [UserName|reply] ◾️برای انتخاب/حذف مدیر : ▪️!promote/demote [UserName|reply] ◽️برای اضافه/حذف کردن کلمه برای فیلتر : ▫️!addword/remword [text] ◾️برای دیدن لیست کلمات فیلتر شده : ▪️!badwords ◽️برای دریافت تنظیمات : ▫️!settings ◾️برای سایلنت/آنسایلنت کردن فردی : ▪️!silent/unsilent ◽️برای دیدن لیست مدیران : ▫️!modlist ◾️برای پین/آنپین کردن یک پیام : ▪️!pin/unpin [reply] ◽️برای دیدن بن لیست : ▫️!banlist ◾️برای دیدن ایدی عددی خود/دیگران : ▪️!id [reply] ◽️برای تغییر امنیت گروه به حذف پیام/حذف کاربر : ▫️!security [del|kick] ◾️برای تنطیم متن خوش آمد گویی : ▪️!setwelcome [text] ➖➖➖➖➖➖ ]] tdcli.sendMessage(msg.chat_id_,0,1,text,0,'md') elseif msg.content_.text_:match('^setwelcome (.*)$') or msg.content_.text_:match('^[/!#]setwelcome (.*)$') then local wlc = msg.content_.text_:match('setwelcome (.*)') db:hset('wlc',chat_id, wlc) tdcli.sendMessage(chat_id, msg_id, 0, '*Done*\n_Welcome Has Been Set..!_',1,'md') elseif msg.content_.text_:match('info (.*)$') then local matches = { msg.content_.text_:match("[!/#](info) (.*)") } info_user(matches[2]:gsub('@','')) db:set('chatid',chat_id) elseif msg.content_.text_:match('whois (.*)$') then local matches = { msg.content_.text_:match("(whois) (.*)") } who_user(matches[2]:gsub('@','')) db:set('chatid',chat_id) elseif text:lower() == 'reload' and sudo(data) then print(_color.green..'Done Bot Reloaded By => ['..user_id..']') reload() tdcli.sendMessage(msg.chat_id_,msg.id_,0,'Reloaded',0,'md') elseif text:lower() == 'add' and admin(data) then if db:sismember('gpo', chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '_SuperGroup Is Already_ *Added*!', 1, 'md') else db:sadd('gpo', chat_id) db:set('flood-spam:'..chat_id,10) db:set('chare:'..chat_id, 500) db:set('flood-time:'..chat_id,5) db:set("bot:enable:"..chat_id,true) db:set("bot:charge:"..chat_id,30) for k,v in pairs(sudo_users) do tdcli.sendMessage(v, 0, 1, "*User"..msg.sender_user_id_.." Added bot to new group*" , 1, 'md') end tdcli.sendMessage(chat_id, msg_id , 1, '*Done*\n_Group Has Been Added To Group List..!_', 1, 'md') end elseif text:lower() == 'rem' and admin(data) then if not db:sismember('gpo', chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '_SuperGroup Is Not_ *Added*!', 1, 'md') else db:srem('gpo', chat_id) db:del("bot:charge:"..msg.chat_id_) db:del("bot:enable:"..msg.chat_id_) tdcli.sendMessage(chat_id, msg_id , 1, '*Done*\n_Group Has Been Removed From Group List..!_', 1, 'md') end elseif text:lower() == "id" then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*> Chat Id :* [-100"..chat_id:gsub('-100','').."]\n*> Your Id :* ["..user.."]", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_, id_reply,nil) end elseif text:lower() == 'pin' and mod(data) then if msg.reply_to_message_id_ == 0 then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*What Should I Pin..?!*', 1,'md') end tdcli.pinChannelMessage(msg.chat_id_,msg.reply_to_message_id_,0) elseif text:lower() == 'unpin' and mod(data) then tdcli.unpinChannelMessage(msg.chat_id_) elseif msg.content_.text_:lower():match('edit (.*)') and admin(data) then local text2 = msg.content_.text_:lower():match('edit (.*)') tdcli.editMessageText(msg.chat_id_,msg.reply_to_message_id_,nil,text2,1,'md') elseif msg.content_.text_:match('echo (.*)') then local text2 = msg.content_.text_:match('echo (.*)' ) tdcli.sendMessage(msg.chat_id_,msg.id_,1,text2,1,'md') elseif text:lower() == 'views' then db:set('userid:'..user_id, true) tdcli.sendMessage(chat_id, msg_id , 1, '*OK*\n_Now Forward Your Message...!_', 1, 'md') ------------ GBan Step ---------- elseif text:lower() == "gban" and admin(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,gban_reply,nil) end elseif text:match('^(gban) (.*)$') and admin(data) then local matches = {text:match("(gban) (.*)")} local gban = matches[2]:gsub('@','') db:set('chatid',chat_id) gban_user(gban) ------------- UnGban ------------- elseif text:lower() == "ungban" and admin(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,ungban_reply,nil) end elseif text:match('^(ungban) (.*)$') and admin(data) then local matches = {text:match("(ungban) (.*)")} local ungban = matches[2]:gsub('@','') db:set('chatid',chat_id) ungban_user(ungban) ------------ End GBan Step ----------- ------------ Kick User ------------ elseif text:lower() == "kick" and mod(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,kick_reply,nil) end elseif text:match('^(kick) (.*)$') and mod(data) then local matches = {text:match("(kick) (.*)")} local kick = matches[2]:gsub('@','') db:set('chatid',chat_id) kick_user(kick) ----------- End Kick Step ------------ ------------ Ban/Un Step ----------- elseif text:lower() == "ban" and mod(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,ban_reply,nil) end elseif text:match('^(ban) (.*)$') and mod(data) then local matches = {text:match("(ban) (.*)")} local ban = matches[2]:gsub('@','') db:set('chatid',chat_id) ban_user(ban) ---------- UnBan Step ---------- elseif text:lower() == "unban" and owner(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,unban_reply,nil) end elseif text:match('^(unban) (.*)$') and mod(data) then local matches = {text:match("(unban) (.*)")} local unban = matches[2]:gsub('@','') db:set('chatid',chat_id) unban_user(unban) ------------ End Ban/UN Step ----------- --------- Mod List Step -------- elseif text:lower() == "demote" and owner(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,demote_reply,nil) end elseif text:match('^(demote) (.*)$') and owner(data) then local matches = {text:match("(demote) (.*)")} local demote = matches[2]:gsub('@','') db:set('chatid',chat_id) demote_user(demote) ------------ Promote Step ------------ elseif text:lower() == "promote" and owner(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,promote_reply,nil) end elseif text:match('^(promote) (.*)$') and owner(data) then local matches = {text:match("(promote) (.*)")} local promote = matches[2]:gsub('@','') db:set('chatid',chat_id) promote_user(promote) ------------ End Mod List Step ----------- -------- Admin Step --------- elseif text:lower() == "setadmin" and sudo(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,setadmin_reply,nil) end elseif text:match('^(setadmin) (.*)$') and sudo(data) then local matches = {text:match("(setadmin) (.*)")} local admin = matches[2]:gsub('@','') db:set('chatid',chat_id) setadmin_user(admin) ------------- De Admin -------------- elseif text:lower() == "deadmin" and sudo(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,deadmin_reply,nil) end elseif text:match('^(deadmin) (.*)$') and sudo(data) then local matches = {text:match("(deadmin) (.*)")} local deadmin = matches[2]:gsub('@','') db:set('chatid',chat_id) deadmin_user(deadmin) ------------ End Admin Step ----------- ------- SetOwner ------- elseif text:lower() == "setowner" and admin(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,setowner_reply,nil) end elseif text:match('^(setowner) (.*)$') and admin(data) then local matches = {text:match("(setowner) (.*)")} local owner = matches[2]:gsub('@','') db:set('chatid',chat_id) setowner_user(owner) ---------- De Owner ---------- elseif text:lower() == "deowner" and admin(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,deowner_reply,nil) end elseif text:match('^(deowner) (.*)$') and admin(data) then local matches = {text:match("(deowner) (.*)")} local deowner = matches[2]:gsub('@','') db:set('chatid',chat_id) deowner_user(deowner) ------------ End Owner Step ----------- ----------------------------------------------------------------------------------------------- elseif text:match("^charge (%d+)$") and admin(data) then local a = {string.match(text, "^(charge) (%d+)$")} tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_Group Charged for_ *'..a[2]..'* _Days_', 1, 'md') local time = a[2] * day db:setex("bot:charge:"..msg.chat_id_,time,true) db:set("bot:enable:"..msg.chat_id_,true) ----------------------------------------------------------------------------------------------- elseif text:match("^stats charge") and mod(data) then local ex = db:ttl("bot:charge:"..msg.chat_id_) if ex == -1 then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_نامحدود!_', 1, 'md') else local d = math.floor(ex / day ) + 1 tdcli.sendMessage(msg.chat_id_, msg.id_, 1, d.." روز تا انقضا گروه باقی مانده", 1, 'md') end ----------------------------------------------------------------------------------------------- elseif text:match("^charge stats (-%d+)") and admin(data) then local txt = {string.match(text, "^(charge stats) (-%d+)$")} local ex = db:ttl("bot:charge:"..txt[2]) if ex == -1 then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_نامحدود!_', 1, 'md') else local d = math.floor(ex / day ) + 1 tdcli.sendMessage(msg.chat_id_, msg.id_, 1, d.." روز تا انقضا گروه باقی مانده", 1, 'md') end ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- elseif text:match("^(leave) (-%d+)") and admin(data) then local txt = {string.match(text, "^(leave) (-%d+)$")} tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'ربات با موفقیت از گروه '..txt[2]..' خارج شد.', 1, 'md') tdcli.sendMessage(txt[2], 0, 1, 'ربات به دلایلی گروه را ترک میکند\nبرای اطلاعات بیشتر میتوانید با @pedaret در ارتباط باشید.\nدر صورت ریپورت بودن میتوانید با ربات زیر به ما پیام دهید\n@awmin_pvbot', 1, 'html') chat_leave(txt[2], bot_id) ----------------------------------------------------------------------------------------------- elseif text:match('^(plan1) (-%d+)') and admin(data) then local txt = {string.match(text, "^(plan1) (-%d+)$")} local timeplan1 = 2592000 db:setex("bot:charge:"..txt[2],timeplan1,true) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'پلن 1 با موفقیت برای گروه '..txt[2]..' فعال شد\nاین گروه تا 30 روز دیگر اعتبار دارد! ( 1 ماه )', 1, 'md') tdcli.sendMessage(txt[2], 0, 1, 'ربات با موفقیت فعال شد و تا 30 روز دیگر اعتبار دارد!', 1, 'md') for k,v in pairs(sudo_users) do tdcli.sendMessage(v, 0, 1, "*User"..msg.sender_user_id_.." Added bot to new group*" , 1, 'md') end db:set("bot:enable:"..txt[2],true) ----------------------------------------------------------------------------------------------- elseif text:match('^(plan2) (-%d+)') and admin(data) then local txt = {string.match(text, "^(plan2) (-%d+)$")} local timeplan2 = 7776000 db:setex("bot:charge:"..txt[2],timeplan2,true) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'پلن 2 با موفقیت برای گروه '..txt[2]..' فعال شد\nاین گروه تا 90 روز دیگر اعتبار دارد! ( 3 ماه )', 1, 'md') tdcli.sendMessage(txt[2], 0, 1, 'ربات با موفقیت فعال شد و تا 90 روز دیگر اعتبار دارد!', 1, 'md') for k,v in pairs(sudo_users) do tdcli.sendMessage(v, 0, 1, "*User"..msg.sender_user_id_.." Added bot to new group*" , 1, 'md') end db:set("bot:enable:"..txt[2],true) ----------------------------------------------------------------------------------------------- elseif text:match('^(plan3) (-%d+)') and admin(data) then local txt = {string.match(text, "^(plan3) (-%d+)$")} db:set("bot:charge:"..txt[2],true) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, 'پلن 3 با موفقیت برای گروه '..txt[2]..' فعال شد\nاین گروه به صورت نامحدود شارژ شد!', 1, 'md') tdcli.sendMessage(txt[2], 0, 1, 'ربات بدون محدودیت فعال شد ! ( نامحدود )', 1, 'md') for k,v in pairs(sudo_users) do tdcli.sendMessage(v, 0, 1, "*User"..msg.sender_user_id_.." Added bot to new group*" , 1, 'md') end db:set("bot:enable:"..txt[2],true) ----------------------------------------------------------------------------------------------- elseif text:lower() == "rules" then if db:get("rules:" .. msg.chat_id_) then local text = db:get("rules:"..msg.chat_id_) tdcli.sendMessage(chat_id,msg.id_,1,text,1,'md') else tdcli.sendMessage(chat_id,msg.id_,1,'*Chat rules:*\n`>` No Flood.\n`>` No Spam.\n`>` Try to stay on topic.\n`>` Forbidden any racist, sexual, gore content...\n\n_Repeated failure to comply with these rules will cause ban._',1,'md') end elseif text:match("^setrules (.*)$") and mod(data) then local txt = {string.match(text, "^(setrules) (.*)$")} db:set("rules:" .. msg.chat_id_, txt[2]) tdcli.sendMessage(chat_id,msg.id_,1,'`>` *New rules* have been *created.*',1,'md') ----------------------------------------------------------------------------------------------- elseif text:match("^inv$") and msg.reply_to_message_id_ and sudo(data) then getMessage(msg.chat_id_, msg.reply_to_message_id_,inv_reply) elseif text:lower() == 'modlist' then local mod = db:scard('gp:mods:'..msg.chat_id_) if mod == 0 then tdcli.sendMessage(chat_id,msg.id_,1,'No Mod Users In This Group',1,'md') else local hash = 'gp:mods:'..msg.chat_id_ local list = db:smembers(hash) local text = "Mod List:\n" for k,v in pairs(list) do text = text.."<b>"..k.."</b> - <i>["..v.."]</i>\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') end elseif text:lower() == 'ownerlist' then local owner = db:scard('gp:owners:'..msg.chat_id_) if owner == 0 then tdcli.sendMessage(chat_id,msg.id_,1,'No Owner Users In This Group',1,'md') else local hash = 'gp:owners:'..msg.chat_id_ local list = db:smembers(hash) local text = "Owners:\n" for k,v in pairs(list) do text = text.."<b>"..k.."</b> - <i>["..v.."]</i>\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') end elseif text:lower() == "banlist" and owner(data) then local owner = db:scard('bans:gp:'..msg.chat_id_) if owner == 0 then tdcli.sendMessage(chat_id,msg.id_,1,'No Ban Users In This Group',1,'md') else local hash = 'bans:gp:'..msg.chat_id_ local list = db:smembers(hash) local text = "Ban List:\n" for k,v in pairs(list) do text = text.."<b>"..k.."</b> - <i>["..v.."]</i>\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') end elseif text:lower() == 'adminlist' and sudo(data) then --result.sender_user_id_ local admins = db:scard('max:adminss') if admins == 0 then tdcli.sendMessage(chat_id,msg.id_,1,"I Can't Find Admins",1,'md') end local hash = 'max:adminss' local list = db:smembers(hash) local text = "Admins List:\n" for k,v in pairs(list) do text = text.."<b>"..k.."</b> - <i>["..v.."]</i>\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') elseif text:lower() == 'gbanlist' and sudo(data) then --result.sender_user_id_ local admins = db:scard('gbans:user') if admins == 0 then tdcli.sendMessage(chat_id,msg.id_,1,"I Can't Find gbans",1,'md') end local hash = 'gbans:user' local list = db:smembers(hash) local text = "Gban List:\n" for k,v in pairs(list) do text = text.."<b>"..k.."</b> - <i>["..v.."]</i>\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') elseif text:lower() == 'silentlist' and mod(data) then local silents = db:scard('mutes:'..msg.chat_id_) if silents == 0 then tdcli.sendMessage(chat_id,msg.id_,1,"I Can't Find Silents",1,'md') else local hash = 'mutes:'..msg.chat_id_ local list = db:smembers(hash) local text = "Silent List:\n" for k,v in pairs(list) do text = text.."<b>"..k.."</b> - <i>["..v.."]</i>\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') end elseif msg.content_.text_:lower():match('^[!/#]addword (.*)$') or msg.content_.text_:lower():match('^addword (.*)$') and mod(data) then local text = msg.content_.text_:match('^[!/#]addword (.*)$') local bad = db:hget('badwords:'..chat_id..":badword", text) if bad then tdcli.sendMessage(chat_id, msg_id, 1, '*This Word* _['..text..']_ *Is Already Locked..!*', 1, 'md') else db:hset('badwords:'..chat_id..":badword", text, "newword") tdcli.sendMessage(chat_id, msg_id , 1, '*Done Word* _['..text..']_ *Added To Badword List..!*', 1, 'md') end elseif msg.content_.text_:lower():match('^[!/#]rw (.*)$') or msg.content_.text_:lower():match('^rw (.*)$') and mod(data) then local text = msg.content_.text_:match('^[!/#]rw (.*)$') local bad = db:hget('badwords:'..chat_id..":badword", text) if not bad then tdcli.sendMessage(chat_id, msg_id, 1, '*This Word* _['..text..']_ *Is Not Locked..!*', 1, 'md') else db:hdel('badwords:'..chat_id..":badword", text) tdcli.sendMessage(chat_id, msg_id , 1, '*Done Word* _['..text..']_ *Removed From Badword List..!*', 1, 'md') end elseif text:lower() == 'badwords' and mod(data) then local owner = 1 if owner == 0 then tdcli.sendMessage(chat_id,msg.id_,1,'No Badwords Users In This Group',1,'md') else local hash = 'badwords:'..chat_id..":badword" local list = db:hkeys(hash) local text = "Badwords:\n" for i=1, #list do text = text.."> "..list[i].."\n" end tdcli.sendMessage(chat_id,msg.id_,1,text,1,'html') end elseif text:lower():match('^spam (.*)$') and sudo(data) then local text = text:match('^spam (.*)$') for i=1,100 do tdcli.sendMessage(chat_id,0, 1, text, 1, 'html') end elseif text:lower() == 'setpro' and sudo(data) then local file = '/data/bot.jpg' tdcli.load_file(msg.id_,file,msg) tdcli.setProfilePhoto('data/bot.jpg') tdcli.sendMessage(chat_id, msg_id, 1, '*Done*\n*Profile Photo Successful Changed..!*', 1, 'md') elseif text:match('^setbotname (.*)$') and sudo(data) then local text = text:match('^setbotname (.*)$') tdcli.changeName(text) tdcli.sendMessage(chat_id, msg_id, 1, '*Done*\n*Profile Name Successful Changed..!*', 1, 'md') elseif text:lower():match('^setbotabout (.*)$') and sudo(data) then local text = text:match('^setbotabout (.*)$') tdcli.changeAbout(text) tdcli.sendMessage(chat_id, msg_id, 1, '*Done*\n*Profile About Successful Changed..!*', 1, 'md') tdcli.sendMessage(chat_id, msg_id, 1,t,1,'md') elseif text:lower() == 'settings' and mod(data) then local link = db:get('links:Lock:'..chat_id) local fwd = db:get('fwd:Lock:'..chat_id) local reply = db:get('reply:'..chat_id) local cmd = db:get('cmd:Lock:'..chat_id) local mute = db:get('muteall:Lock:'..chat_id) local inline = db:get('inline:Lock:'..chat_id) local keyboard = db:get('keyboard:Lock:'..chat_id) local photo = db:get('photo:Lock:'..chat_id) local video = db:get('video:Lock:'..chat_id) local dc = db:get('document:Lock:'..chat_id) local sticker = db:get('sticker:Lock:'..chat_id) local gif = db:get('animation:Lock:'..chat_id) local contact = db:get('contact:Lock:'..chat_id) local audio = db:get('audio:Lock:'..chat_id) local voice = db:get('voice:Lock:'..chat_id) local emoji = db:get('emoji:Lock:'..chat_id) local location = db:get('location:Lock:'..chat_id) local edit = db:get('edit:Lock:'..chat_id) local md = db:get('md:Lock:'..chat_id) local arabic = db:get('arabic:Lock:'..chat_id) local english = db:get('en:Lock:'..chat_id) local bot = db:get('bot:Lock:'..chat_id) local pin = db:get('pin:Lock:'..chat_id) local tag = db:get('tag:Lock:'..chat_id) local user = db:get('username:Lock:'..chat_id) local chare = tonumber(db:get('chare:'..chat_id)) local flood = tonumber(db:get('flood-spam:'..chat_id)) local wlc = db:get('wlc:Enable:'..chat_id) local bye = db:get('bye:Enable:'..chat_id) local floods = db:get('flood:Lock:'..chat_id) local spam = db:get('spam:Lock:'..chat_id) local time = tonumber(db:get('flood-time:'..chat_id)) local sec = db:get('security:'..chat_id) local ex = db:ttl("bot:charge:"..msg.chat_id_) if ex == -1 then exp_dat = 'Unlimited' else exp_dat = math.floor(ex / 86400) + 1 end local settings = '*Group Settings:*\n-----------------------\nLock Bots => _'..(bot or 'Unlock')..'_\nLock Emoji => _'..(emoji or 'Unlock')..'_\nLock Markdown => _'..(md or 'Unlock')..'_\nLock Tag => _'..(tag or 'Unlock')..'_\nLock Link => _'..(link or 'Unlock')..'_\nLock Username => _'..(user or 'Unlock')..'_\nLock Pin => _'..(pin or 'Unlock')..'_\nLock Forward => _'..(fwd or 'Unlock')..'_\nLock Reply => _'..(reply or 'Unlock')..'_\nLock Cmd => _'..(cmd or 'Unlock')..'_\nLock Flood => _'..(floods or 'Unlock')..'_\nLock Spam => _'..(spam or 'Unlock')..'_\nLock Arabic => _'..(arabic or 'Unlock')..'_\nLock English => _'..(english or 'Unlock')..'_\nLock Edit => _'..(edit or 'Unlock')..'_\nWelcome Status: _'..(wlc or 'Disable')..'_\nBye Status: _'..(bye or 'Diaable')..'_\n-----------------------\n*Mute Settings:*\nMute All => _'..(mute or 'Unlock')..'_\nMute Photo => _'..(photo or 'Unlock')..'_\nMute Inline => _'..(inline or 'Unlock')..'_\nMute keyboard => _'..(keyboard or 'Unlock')..'_\nMute Audio => _'..(audio or 'Unlock')..'_\nMute Voice => _'..(voice or 'Unlock')..'_\nMute Location => _'..(location or 'Unlock')..'_\nMute Sticker => _'..(sticker or 'Unlock')..'_\nMute GIFs => _'..(gif or 'Unlock')..'_\nMute Document => _'..(dc or 'Unlock')..'_\nMute Video => _'..(video or 'Unlock')..'_\nMute Contact => _'..(contact or 'Unlock')..'_\n-----------------------\n*More Settings:*\nChar Sensitivity => _'..(chare or '0')..'_\nFlood Sensitivity => _'..(flood or '0')..'_\nFlood Time => _'..(time or '0')..'_\nSecurity Setting => _'..(sec or 'Kick')..'_\nExpire Time : => _'..exp_dat..'_' tdcli.sendMessage(chat_id, msg_id, 1, settings, 1, 'md') elseif text:lower() == 'link' and mod(data) then if db:get('link:gp:'..msg.chat_id_) == nil then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Error*\n_Please Set Some Link...!_', 1, 'md') else local link = db:get('link:gp:'..msg.chat_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '<b>Group Link:</b>\n'..link:gsub("_","\\_"), 1, 'html') end --<a href=..link:gsub("_","\\_")>Group Link</a elseif text:lower() == 'setlink' and mod(data) then db:set('link:wait:'..msg.chat_id_,msg.sender_user_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*OK*\n_Now Send Me Any Shit...!_', 1, 'md') elseif text:lower() == "silent" and mod(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,mute_reply,nil) end --------------------------------------------- elseif text:lower() == 'rank' and sudo(data) then tdcli.sendMessage(msg.chat_id_, 0, 1, 'You are My <b>Sudo</b>', 1, 'html') elseif text:lower() == 'rank' and admin(data) then tdcli.sendMessage(msg.chat_id_, 0, 1, 'You are My <b>Admin</b>', 1,'html') elseif text:lower() == 'rank' and owner(data) then tdcli.sendMessage(msg.chat_id_, 0, 1, 'You are Gp <b>Owner</b>', 1,'html') elseif text:lower() == 'rank' and mod(data) then tdcli.sendMessage(msg.chat_id_, 0, 1, 'You are Gp <b>Moderator</b>', 1,'html') elseif text:lower() == 'rank' then tdcli.sendMessage(msg.chat_id_, 0, 1, 'You are <b>Member</b>', 1,'html') elseif text:match('^(silent) (.*)$') and admin(data) then local matches = {text:match("(silent) (.*)")} local mute = matches[2]:gsub('@','') db:set('chatid',chat_id) mute_user(mute) elseif text:lower() == "unsilent" and mod(data) then if msg.reply_to_message_id_ == 0 then local user = msg.sender_user_id_ tdcli.sendMessage(msg.chat_id_, msg.id_, 1, "*Please Reply Someone..!*", 1, 'md') else getMessage(chat_id,msg.reply_to_message_id_,unmute_reply,nil) end elseif text:match('^(unsilent) (.*)$') and admin(data) then local matches = {text:match("(unsilent) (.*)")} local unmute = matches[2]:gsub('@','') db:set('chatid',chat_id) unmute_user(unmute) elseif text:lower() == 'mute all' and mod(data) then if db:get('muteall:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Mute All Is Already* _Enabled!_', 1, 'md') else db:set('muteall:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Mute All Has Been* _Enabled!_', 1, 'md') end elseif text:lower() == 'unmute all' and mod(data) then if not db:get('muteall:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Mute All Is Not* _Enable!_', 1, 'md') else db:del('muteall:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Mute All Has Been* _Disabled!_', 1, 'md') end elseif text:lower() == 'security del' and mod(data) then db:set('security:'..chat_id,'del') tdcli.sendMessage(chat_id,msg.id_,1,'*Done*\n_Security Settings Has Been Changed..!_',0,'md') elseif text:lower() == 'security kick' and mod(data) then db:del('security:'..chat_id) tdcli.sendMessage(chat_id,msg.id_,1,'*Done*\n_Security Settings Has Been Changed..!_',0,'md') elseif text:lower() == 'show edit' and mod(data) then if db:get('edit:Show:'..chat_id) == 'Show' then db:del('edit:Show:'..chat_id) tdcli.sendMessage(chat_id,msg.id_,0,'Show Edit Was Disabled..!',1,'md') else db:set('edit:Show:'..chat_id,'Show') tdcli.sendMessage(chat_id,msg.id_,0,'Show Edit Was Enable..!',1,'md') end elseif text:lower() == 'lock links' and mod(data) then if db:get('links:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Link Posting Is Already* _Locked!_', 1, 'md') else db:set('links:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Links Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock links' and mod(data) then if not db:get('links:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Link Posting Is Not * _Locked!_', 1, 'md') else db:del('links:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Links Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock bot' and mod(data) then if db:get('bot:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*bot Is Already* _Locked!_', 1, 'md') else db:set('bot:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*bot Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock bot' and mod(data) then if not db:get('bot:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*bot Is Not * _Locked!_', 1, 'md') else db:del('bot:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*bot Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock markdown' and mod(data) then if db:get('md:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*markdown Posting Is Already* _Locked!_', 1, 'md') else db:set('md:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*markdown Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock markdown' and mod(data) then if not db:get('md:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*markdown Posting Is Not * _Locked!_', 1, 'md') else db:del('md:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*markdown Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock tag' and mod(data) then if db:get('tag:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*tag Is Already* _Locked!_', 1, 'md') else db:set('tag:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*tag Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock tag' and mod(data) then if not db:get('tag:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*tag Is Not * _Locked!_', 1, 'md') else db:del('tag:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*tag Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock flood' and mod(data) then if db:get('flood:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Flood Is Already* _Locked!_', 1, 'md') else db:set('flood:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Flood Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock flood' and mod(data) then if not db:get('flood:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Flood Is Not * _Locked!_', 1, 'md') else db:del('flood:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Flood Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock english' and mod(data) then if db:get('en:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*English Is Already* _Locked!_', 1, 'md') else db:set('en:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*English Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock english' and mod(data) then if not db:get('en:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*English Is Not * _Locked!_', 1, 'md') else db:del('en:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*English Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'welcome enable' and mod(data) then if db:get('wlc:Enable:'..chat_id) == 'Enable' then tdcli.sendMessage(chat_id, msg_id , 1, '*Welcome Is Already* _Enabled!_', 1, 'md') else db:set('wlc:Enable:'..chat_id, 'Enable') tdcli.sendMessage(chat_id, msg_id , 1, '*Welcome Has Been* _Enabled!_', 1, 'md') end elseif text:lower() == 'welcome disable' and mod(data) then if not db:get('wlc:Enable:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Welcome Is Not * _Enabled!_', 1, 'md') else db:del('wlc:Enable:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Welcome Has Been* _Disabled!_', 1, 'md') end elseif text:lower() == 'bye enable' and mod(data) then if db:get('bye:Enable:'..chat_id) == 'Enable' then tdcli.sendMessage(chat_id, msg_id , 1, '*Bye Is Already* _Enabled!_', 1, 'md') else db:set('bye:Enable:'..chat_id, 'Enable') tdcli.sendMessage(chat_id, msg_id , 1, '*Bye Has Been* _Enabled!_', 1, 'md') end elseif text:lower() == 'bye disable' and mod(data) then if not db:get('bye:Enable:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Bye Is Not * _Enabled!_', 1, 'md') else db:del('bye:Enable:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Bye Has Been* _Disabled!_', 1, 'md') end elseif text:lower() == 'lock username' and mod(data) then if db:get('username:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*username Is Already* _Locked!_', 1, 'md') else db:set('username:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*username Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock username' and mod(data) then if not db:get('username:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*username Is Not * _Locked!_', 1, 'md') else db:del('username:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*username Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock fwd' and mod(data) then if db:get('fwd:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Forward Is Already* _Locked!_', 1, 'md') else db:set('fwd:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Forward Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock fwd' and mod(data) then if not db:get('fwd:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Forward Is Not * _Locked!_', 1, 'md') else db:del('fwd:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Forward Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock arabic' and mod(data) then if db:get('arabic:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Arabic Is Already* _Locked!_', 1, 'md') else db:set('arabic:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Arabic Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock arabic' and mod(data) then if not db:get('arabic:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Arabic Is Not * _Locked!_', 1, 'md') else db:del('arabic:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Arabic Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock pin' and mod(data) then if db:get('pin:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Pin Is Already* _Locked!_', 1, 'md') else db:set('pin:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Pin Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock pin' and mod(data) then if not db:get('pin:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Pin Is Not * _Locked!_', 1, 'md') else db:del('pin:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Pin Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock spam' and mod(data) then if db:get('spam:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Spam Is Already* _Locked!_', 1, 'md') else db:set('spam:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Spam Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock spam' and mod(data) then if not db:get('spam:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Spam Is Not * _Locked!_', 1, 'md') else db:del('spam:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Spam Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock reply' and mod(data) then if db:get('reply:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Reply Is Already* _Locked!_', 1, 'md') else db:set('reply:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Reply Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock reply' and mod(data) then if not db:get('reply:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Reply Is Not * _Locked!_', 1, 'md') else db:del('reply:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Reply Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock emoji' and mod(data) then if db:get('emoji:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*emoji Is Already* _Locked!_', 1, 'md') else db:set('emoji:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*emoji Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock emoji' and mod(data) then if not db:get('emoji:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*emoji Is Not * _Locked!_', 1, 'md') else db:del('emoji:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*emoji Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock cmd' and mod(data) then if db:get('cmd:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*cmd Is Already* _Locked!_', 1, 'md') else db:set('cmd:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*cmd Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock cmd' and mod(data) then if not db:get('cmd:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*cmd Is Not * _Locked!_', 1, 'md') else db:del('cmd:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*cmd Has Been* _Unlocked!_', 1, 'md') end elseif text:lower() == 'lock edit' and mod(data) then if db:get('edit:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Edit Is Already* _Locked!_', 1, 'md') else db:set('edit:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Edit Has Been* _Locked!_', 1, 'md') end elseif text:lower() == 'unlock edit' and mod(data) then if not db:get('edit:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Edit Is Not * _Locked!_', 1, 'md') else db:del('edit:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Edit Has Been* _Unlocked!_', 1, 'md') end -------Mute Settings------- elseif text:lower() == 'mute photo' and mod(data) then if db:get('photo:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Photo Is Already* _Muted!_', 1, 'md') else db:set('photo:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Photo Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute photo' and mod(data) then if not db:get('photo:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Photo Is Not * _Muted!_', 1, 'md') else db:del('photo:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Photo Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute video' and mod(data) then if db:get('video:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Video Is Already* _Muted!_', 1, 'md') else db:set('video:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Video Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute video' and mod(data) then if not db:get('video:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Video Is Not * _Muted!_', 1, 'md') else db:del('video:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Video Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute document' and mod(data) then if db:get('document:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Document Is Already* _Muted!_', 1, 'md') else db:set('document:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Document Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute document' and mod(data) then if not db:get('document:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Document Is Not * _Muted!_', 1, 'md') else db:del('document:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Document Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute inline' and mod(data) then if db:get('inline:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*inline Is Already* _Muted!_', 1, 'md') else db:set('inline:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*inline Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute inline' and mod(data) then if not db:get('inline:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*inline Is Not * _Muted!_', 1, 'md') else db:del('inline:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*inline Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute keyboard' and mod(data) then if db:get('keyboard:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*keyboard Is Already* _Muted!_', 1, 'md') else db:set('keyboard:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*keyboard Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute keyboard' and mod(data) then if not db:get('keyboard:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*keyboard Is Not * _Muted!_', 1, 'md') else db:del('keyboard:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*keyboard Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute sticker' and mod(data) then if db:get('sticker:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Sticker Is Already* _Muted!_', 1, 'md') else db:set('sticker:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Sticker Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute sticker' and mod(data) then if not db:get('sticker:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Sticker Is Not * _Muted!_', 1, 'md') else db:del('sticker:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Sticker Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute voice' and mod(data) then if db:get('voice:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*voice Is Already* _Muted!_', 1, 'md') else db:set('voice:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*voice Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute voice' and mod(data) then if not db:get('voice:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*voice Is Not * _Muted!_', 1, 'md') else db:del('voice:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*voice Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute audio' and mod(data) then if db:get('audio:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Audio Is Already* _Muted!_', 1, 'md') else db:set('audio:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Audio Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute audio' and mod(data) then if not db:get('audio:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Audio Is Not * _Muted!_', 1, 'md') else db:del('audio:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Audio Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute location' and mod(data) then if db:get('location:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*location Is Already* _Muted!_', 1, 'md') else db:set('location:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*location Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute location' and mod(data) then if not db:get('location:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*location Is Not * _Muted!_', 1, 'md') else db:del('location:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*location Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute contact' and mod(data) then if db:get('contact:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*Contact Is Already* _Muted!_', 1, 'md') else db:set('contact:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*Contact Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute contact' and mod(data) then if not db:get('contact:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*Conatct Is Not * _Muted!_', 1, 'md') else db:del('contact:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*Contact Has Been* _Unmuted!_', 1, 'md') end elseif text:lower() == 'mute gif' and mod(data) then if db:get('animation:Lock:'..chat_id) == 'Lock' then tdcli.sendMessage(chat_id, msg_id , 1, '*GIFs Is Already* _Muted!_', 1, 'md') else db:set('animation:Lock:'..chat_id, 'Lock') tdcli.sendMessage(chat_id, msg_id , 1, '*GIFs Has Been* _Muted!_', 1, 'md') end elseif text:lower() == 'unmute gif' and mod(data) then if not db:get('animation:Lock:'..chat_id) then tdcli.sendMessage(chat_id, msg_id , 1, '*GIFs Is Not * _Muted!_', 1, 'md') else db:del('animation:Lock:'..chat_id) tdcli.sendMessage(chat_id, msg_id , 1, '*GIFs Has Been* _Unmuted!_', 1, 'md') end elseif text == 'gcap' then db:set('user_id:'..user_id,true) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*OK*\n_Now Send Me Your File_', 1,'md') elseif text:match('^setchar (%d+)$') and mod(data) then local chare = text:match('^setchar (%d+)$') if tonumber(chare) < 10 or tonumber(chare) > 10000 then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Error*\n_Wrong Number ,Range Is [10-10000]_', 1,'md') else tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Done*\n_Char Has Been Set To '..chare..'_', 1,'md') db:set('chare:'..chat_id,chare) end elseif text == 'setviews' then db:set('sviews:'..user_id,true) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*OK*\n_Now Send Me Anything..!_', 1,'md') elseif text:match('^setflood (%d+)$') and mod(data) then local chare = text:match('^setflood (%d+)$') if tonumber(chare) < 3 or tonumber(chare) > 20 then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Error*\n_Wrong Number ,Range Is [3-20]_', 1,'md') else tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Done*\n_Flood Has Been Set To '..chare..'_', 1,'md') db:set('flood-spam:'..chat_id,chare) end elseif text:match("^clean (.*)$") then local txt = {string.match(text, "^(clean) (.*)$")} if txt[2] == 'banlist' and mod(data) then db:del('bans:gp:'..msg.chat_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_> Banlist has been_ *Cleaned*', 1, 'md') end if txt[2] == 'modlist' and owner(data) then db:del('gp:mods:'..msg.chat_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_> Modlist has been_ *Cleaned*', 1, 'md') end if txt[2] == 'ownerlist' and admin(data) then db:del('gp:owners:'..msg.chat_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_> ownerlist has been_ *Cleaned*', 1, 'md') end if txt[2] == 'silentlist' and mod(data) then db:del('mutes:'..msg.chat_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_> Silentlist has been_ *Cleaned*', 1, 'md') end if txt[2] == 'rules' and owner(data) then db:del('rules:'..msg.chat_id_) tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_> Rules has been_ *Cleaned*', 1, 'md') end if txt[2] == 'gbanlsit' and sudo(data) then db:del('gbans:user:') tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '_> Gbanlist has been_ *Cleaned*', 1, 'md') end elseif text:match('^clean bots$') and mod(data) then tdcli_function ({ ID = "GetChannelMembers", channel_id_ = getChatId(chat_id).ID, filter_ = { ID = "ChannelMembersBots" }, offset_ = '', limit_ = 200}, clean_bots, {gid=chat_id}) tdcli.sendMessage(chat_id, msg.id_ , 1, '*kick bots soon*', 1, 'md') elseif text:match('^setfloodtime (%d+)$') and mod(data) then local chare = text:match('^setfloodtime (%d+)$') if tonumber(chare) < 1 or tonumber(chare) > 5 then tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Error*\n_Wrong Number ,Range Is [1-5]_', 1,'md') else tdcli.sendMessage(msg.chat_id_, msg.id_, 1, '*Done*\n_Flood Has Been Set To '..chare..'_', 1,'md') db:set('flood-time:'..chat_id,chare) end end end end end end
-- ~~~~~~~~~~ -- base.lua -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Bases to land on for Mars Lander -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ local Base = {} -- ~~~~~~~~~~~~~~~~ -- Local Variables -- ~~~~~~~~~~~~~~~~ local landingLights = Assets.getImageSet("landingLights") landingLights.animation = Assets.newAnimation("landingLights", landingLights.image, 64, 8, 1, '1-4', 0.5) local baseOn = Assets.getImageSet("fuelbaseOn") local baseOff = Assets.getImageSet("fuelbaseOff") -- ~~~~~~~~~~~~~~~~~ -- Public functions -- ~~~~~~~~~~~~~~~~~ function Base.init() end -- TODO: Move base related functions from lander.lua function Base.update(dt) landingLights.animation:update(dt) end function Base.draw() for k,v in pairs(OBJECTS) do local xvalue = v.x local objectvalue = v.objecttype -- check if on-screen if (xvalue > WORLD_OFFSET - SCREEN_WIDTH) and (xvalue < WORLD_OFFSET + SCREEN_WIDTH) then -- draw image based on object type if objectvalue == Enum.basetypeFuel then local baseX = xvalue - WORLD_OFFSET local baseY = GROUND[xvalue] - baseOn.height -- draw gas tank -- draw the 'fuel level' before drawing the tank over it -- draw the whole gauge red then overlay the right amount of green love.graphics.setColor(1, 0, 0, 1) love.graphics.rectangle("fill", baseX + 40, baseY + 84, 5, 40) -- draw green gauge -- pixel art gauge is 36 pixels high local gaugeheight = v.totalFuel / Enum.baseMaxFuel * 36 local gaugebottom = 120 love.graphics.setColor(0, 1, 0, 1) love.graphics.rectangle("fill", baseX + 40, baseY + gaugebottom - gaugeheight, 5, gaugeheight) -- set colour based on ACTIVE status love.graphics.setColor(1, 1, 1, 1) if v.active then love.graphics.draw(baseOn.image, baseX, baseY) else love.graphics.draw(baseOff.image, baseX, baseY) end -- draw landing lights -- the image is white so the colour can be controlled here at runtime if v.paid then love.graphics.setColor(1, 0, 0, 1) else love.graphics.setColor(0, 1, 0, 1) end local x = baseX + baseOn.width - 10 local y = baseY + baseOn.height landingLights.animation:draw(x, y) love.graphics.setColor(1, 1, 1, 1) end end end end return Base
local dat = {} local ver, info local datread = require("data/load_dat") datread, ver = datread.open("sysinfo.dat", "# This file was generated on") function dat.check(set, softlist) if softlist or not datread then return nil end local status status, info = pcall(datread, "bio", "info", set) if not status or not info then return nil end return _p("plugin-data", "Sysinfo") end function dat.get() return info end function dat.ver() return ver end return dat
local Shopkeeper, super = Class(Object) function Shopkeeper:init() super:init(self) -- Whether the shopkeeper slides -- out of the way in the buy menu. self.slide = false -- Whether the shopkeeper's sprite -- should be animated by talking. self.talk_sprite = true self.actor = nil self.sprite = nil end function Shopkeeper:getActor() return self.actor or (self.sprite and self.sprite.actor) end function Shopkeeper:setActor(actor) if type(actor) == "string" then actor = Registry.createActor(actor) end if self.sprite then self.sprite:remove() end self.sprite = ActorSprite(actor) self.sprite:setScale(2, 2) self.sprite:setOrigin(0.5, 1) self:addChild(self.sprite) return self.sprite end function Shopkeeper:setSprite(sprite) if self.sprite then self.sprite:setSprite(sprite) else self.sprite = Sprite(sprite) self.sprite:setScale(2, 2) self.sprite:setOrigin(0.5, 1) self:addChild(self.sprite) end return self.sprite end function Shopkeeper:setAnimation(animation) if self.sprite then self.sprite:setAnimation(animation) else error("Attempt to set animation with no sprite") end end function Shopkeeper:onEmote(emote) if self.sprite then self.sprite:set(emote) else self:setSprite(emote) end end return Shopkeeper
-- -- hmmer 3.3.1 modulefile -- -- "URL: https://www.psc.edu/resources/software" -- "Category: Biological Sciences" -- "Description: hmmer is a software used to identify homologous protein or nucleotide sequences, and to perform sequence alignments." -- "Keywords: singularity bioinformatics" whatis("Name: hmmer") whatis("Version: 3.3.1") whatis("Category: Biological Sciences") whatis("URL: https://www.psc.edu/resources/software") whatis("Description: hmmer infers approximately-maximum-likelihood phylogenetic trees from alignments of nucleotide or protein sequences.") help([[ hmmer infers approximately-maximum-likelihood phylogenetic trees from alignments of nucleotide or protein sequences. To load the module type > module load hmmer/3.3.1 To unload the module type > module unload hmmer/3.3.1 Documentation ------------- For help, type > hmmer --help Tools included in this module are * hmmer ]]) local package = "hmmer" local version = "3.3.1" local base = pathJoin("/opt/packages",package,version) prepend_path("PATH", base)
local mmver = offsets.MMVersion local function mmv(...) return select(mmver - 5, ...) end const = const or {} Const = const local _KNOWNGLOBALS const.Novice = 1 const.Expert = 2 const.Master = 3 if mmver ~= 6 then const.GM = 4 end const.MapLimit = 22528 const.Minute = 256 const.Second = const.Minute/60 const.Hour = const.Minute*60 const.Day = const.Hour*24 const.Week = const.Day*7 const.Month = const.Week*4 const.Year = const.Month*12 local function MakeBitsDefiner(name) internal[name] = function(define) for n, b in pairs(const[name]) do define.bit(n, b) end return define end end MakeBitsDefiner("FacetBits") const.FacetBits = { IsPortal = 0x00000001, IsWater = 0x00000010, Invisible = 0x00002000, AnimatedTFT = 0x00004000, MoveByDoor = 0x00040000, -- 0x4000 - untextured?? --TriggerByTouch = 0x00080000, -- don't work anymore IsEventJustHint = 0x00100000, -- [MM7+] AlternativeSound = 0x00200000, IsSky = 0x00400000, -- outdoor: horizontal flow FlipU = 0x00800000, FlipV = 0x01000000, TriggerByClick = 0x02000000, TriggerByStep = 0x04000000, Untouchable = 0x20000000, IsLava = 0x40000000, HasData = 0x80000000, } if mmver > 6 then table.copy({ IsSecret = 0x00000002, -- show in red with Perception ScrollDown = 0x00000004, -- moving texture ScrollUp = 0x00000020, ScrollLeft = 0x00000040, ScrollRight = 0x00000800, AlignTop = 0x00000008, -- align door texture in D3D AlignLeft = 0x00001000, AlignRight = 0x00008000, AlignBottom = 0x00020000, }, const.FacetBits, true) end if mmver < 8 then table.copy({ TriggerByMonster = 0x08000000, -- happens even if there's no event assigned TriggerByObject = 0x10000000, -- happens even if there's no event assigned }, const.FacetBits, true) else table.copy({ DisableEventByCtrlClick = 0x08000000, -- indoor only: click event gets disabled by Ctrl+Click EventDisabledByCtrlClick = 0x10000000, }, const.FacetBits, true) end MakeBitsDefiner("SpriteBits") const.SpriteBits = { TriggerByTouch = 0x0001, -- triggered when a player comes into TriggerRadius TriggerByMonster = 0x0002, -- triggered when a monster comes into TriggerRadius TriggerByObject = 0x0004, -- triggered when an object gets into TriggerRadius ShowOnMap = 0x0008, IsChest = 0x0010, Invisible = 0x0020, IsObeliskChest = 0x0040, } MakeBitsDefiner("ChestBits") const.ChestBits = { Trapped = 1, ItemsPlaced = 2, Identified = 4, } MakeBitsDefiner("MonsterBits") const.MonsterBits = { Active = 0x00000400, -- inside the active radius? ShowOnMap = 0x00008000, -- monster was once seen by party Invisible = 0x00010000, NoFlee = 0x00020000, Hostile = 0x00080000, OnAlertMap = 0x00100000, TreasureGenerated = 0x00800000, -- treasure is in Items[0] and Items[1], gold is in Items[3] ShowAsHostile = 0x01000000, -- show as hostile on map } const.AIState = { Stand = 0, Active = 1, MeleeAttack = 2, RangedAttack = 3, Dying = 4, Dead = 5, Pursue = 6, Flee = 7, Stunned = 8, Fidget = 9, Interact = 10, Removed = 11, RangedAttack2 = 12, RangedAttack3 = 13, Stoned = 14, Paralyzed = 15, Resurrect = 16, Summoned = 17, RangedAttack4 = 18, Invisible = 19, } const.MonsterBonus = { Curse = 1, Weak = 2, Asleep = 3, Drunk = 4, Insane = 5, Poison1 = 6, Poison2 = 7, Poison3 = 8, Disease1 = 9, Disease2 = 10, Disease3 = 11, Paralyze = 12, Uncon = 13, Dead = 14, Stone = 15, Errad = 16, Brkitem = 17, Brkarmor = 18, Brkweapon = 19, Steal = 20, Age = 21, Drainsp = 22, Afraid = 23, } MakeBitsDefiner("MonsterPref") if mmver == 6 then const.MonsterPref = { Knight = 0x0001, Paladin = 0x0002, Archer = 0x0004, Druid = 0x0008, Cleric = 0x0010, Sorcerer = 0x0020, Male = 0x0040, Female = 0x0080, } elseif mmver == 7 then const.MonsterPref = { Knight = 0x0001, Paladin = 0x0002, Archer = 0x0004, Druid = 0x0008, Cleric = 0x0010, Sorcerer = 0x0020, Ranger = 0x0040, Thief = 0x0080, Monk = 0x0100, Male = 0x0200, Female = 0x0400, Human = 0x0800, Elf = 0x1000, Dwarf = 0x2000, Goblin = 0x4000, } else const.MonsterPref = { Necro = 0x0001, Cleric = 0x0002, Knight = 0x0004, Troll = 0x0008, Minotaur = 0x0010, DarkElf = 0x0020, Vampire = 0x0040, Dragon = 0x0080, Male = 0x0100, Female = 0x0200, } end if mmver == 8 then const.MonsterImmune = 65000 else const.MonsterImmune = 200 end const.MonsterKind = { Undead = 1, Demon = 2, Dragon = 3, Elf = 4, Swimmer = 5, Immobile = 6, Titan = 7, NoArena = 8, } const.ObjectRefKind = { Nothing = 0, Door = 1, Object = 2, Monster = 3, Party = 4, -- Index is player index (1-4 or 0 for whole party ???) Sprite = 5, Facet = 6, -- outdoors Index = ModelId*64 + FaceId Light = 7, } const.Keys = { LBUTTON = 1, RBUTTON = 2, CANCEL = 3, MBUTTON = 4, -- NOT contiguous with L & RBUTTON XBUTTON1 = 5, XBUTTON2 = 6, BACK = 8, BACKSPACE = 8, TAB = 9, CLEAR = 12, RETURN = 13, SHIFT = 16, CONTROL = 17, CTRL = 17, MENU = 18, ALT = 18, PAUSE = 19, CAPITAL = 20, CAPSLOCK = 20, KANA = 21, HANGUL = 21, JUNJA = 23, FINAL = 24, HANJA = 25, KANJI = 25, CONVERT = 28, NONCONVERT = 29, ACCEPT = 30, MODECHANGE = 31, ESCAPE = 27, SPACE = 32, PRIOR = 33, PGUP = 33, NEXT = 34, PGDN = 34, END = 35, HOME = 36, LEFT = 37, UP = 38, RIGHT = 39, DOWN = 40, SELECT = 41, PRINT = 42, EXECUTE = 43, SNAPSHOT = 44, INSERT = 45, DELETE = 46, HELP = 47, LWIN = 91, RWIN = 92, APPS = 93, SLEEP = 95, NUMPAD0 = 96, NUMPAD1 = 97, NUMPAD2 = 98, NUMPAD3 = 99, NUMPAD4 = 100, NUMPAD5 = 101, NUMPAD6 = 102, NUMPAD7 = 103, NUMPAD8 = 104, NUMPAD9 = 105, MULTIPLY = 106, ADD = 107, SEPARATOR = 108, SUBTRACT = 109, DECIMAL = 110, DIVIDE = 111, F1 = 112, F2 = 113, F3 = 114, F4 = 115, F5 = 116, F6 = 117, F7 = 118, F8 = 119, F9 = 120, F10 = 121, F11 = 122, F12 = 123, F13 = 124, F14 = 125, F15 = 126, F16 = 127, F17 = 128, F18 = 129, F19 = 130, F20 = 131, F21 = 132, F22 = 133, F23 = 134, F24 = 135, NUMLOCK = 144, SCROLL = 145, -- VK_L & VK_R - left and right Alt, Ctrl and Shift virtual keys. -- Used only as parameters to GetAsyncKeyState() and GetKeyState(). -- No other API or message will distinguish left and right keys in this way. LSHIFT = 160, RSHIFT = 161, LCONTROL = 162, RCONTROL = 163, LMENU = 164, RMENU = 165, BROWSER_BACK = 166, BROWSER_FORWARD = 167, BROWSER_REFRESH = 168, BROWSER_STOP = 169, BROWSER_SEARCH = 170, BROWSER_FAVORITES = 171, BROWSER_HOME = 172, VOLUME_MUTE = 173, VOLUME_DOWN = 174, VOLUME_UP = 175, MEDIA_NEXT_TRACK = 176, MEDIA_PREV_TRACK = 177, MEDIA_STOP = 178, MEDIA_PLAY_PAUSE = 179, LAUNCH_MAIL = 180, LAUNCH_MEDIA_SELECT = 181, LAUNCH_APP1 = 182, LAUNCH_APP2 = 183, OEM_1 = 186, OEM_PLUS = 187, OEM_COMMA = 188, OEM_MINUS = 189, OEM_PERIOD = 190, OEM_2 = 191, OEM_3 = 192, OEM_4 = 219, OEM_5 = 220, OEM_6 = 221, OEM_7 = 222, OEM_8 = 223, OEM_102 = 226, PACKET = 231, PROCESSKEY = 229, ATTN = 246, CRSEL = 247, EXSEL = 248, EREOF = 249, PLAY = 250, ZOOM = 251, NONAME = 252, PA1 = 253, OEM_CLEAR = 254, } -- VK_0 thru VK_9 are the same as ASCII '0' thru '9' (0x30 - 0x39) for i = 0x30, 0x39 do const.Keys[string.char(i)] = i end -- VK_A thru VK_Z are the same as ASCII 'A' thru 'Z' (0x41 - 0x5A) for i = 0x41, 0x5A do const.Keys[string.char(i)] = i end if mmver == 6 then const.Skills = { Staff = 0, Sword = 1, Dagger = 2, Axe = 3, Spear = 4, Bow = 5, Mace = 6, Blaster = 7, Shield = 8, Leather = 9, Chain = 10, Plate = 11, Fire = 12, Air = 13, Water = 14, Earth = 15, Spirit = 16, Mind = 17, Body = 18, Light = 19, Dark = 20, IdentifyItem = 21, Merchant = 22, Repair = 23, Bodybuilding = 24, Meditation = 25, Perception = 26, Diplomacy = 27, Thievery = 28, DisarmTraps = 29, Learning = 30, } elseif mmver == 7 then const.Skills = { Staff = 0, Sword = 1, Dagger = 2, Axe = 3, Spear = 4, Bow = 5, Mace = 6, Blaster = 7, Shield = 8, Leather = 9, Chain = 10, Plate = 11, Fire = 12, Air = 13, Water = 14, Earth = 15, Spirit = 16, Mind = 17, Body = 18, Light = 19, Dark = 20, IdentifyItem = 21, Merchant = 22, Repair = 23, Bodybuilding = 24, Meditation = 25, Perception = 26, Diplomacy = 27, Thievery = 28, DisarmTraps = 29, Dodging = 30, Unarmed = 31, IdentifyMonster = 32, Armsmaster = 33, Stealing = 34, Alchemy = 35, Learning = 36, } else const.Skills = { Staff = 0, Sword = 1, Dagger = 2, Axe = 3, Spear = 4, Bow = 5, Mace = 6, Blaster = 7, Shield = 8, Leather = 9, Chain = 10, Plate = 11, Fire = 12, Air = 13, Water = 14, Earth = 15, Spirit = 16, Mind = 17, Body = 18, Light = 19, Dark = 20, DarkElfAbility = 21, VampireAbility = 22, DragonAbility = 23, IdentifyItem = 24, Merchant = 25, Repair = 26, Bodybuilding = 27, Meditation = 28, Perception = 29, Regeneration = 30, DisarmTraps = 31, Dodging = 32, Unarmed = 33, IdentifyMonster = 34, Armsmaster = 35, Stealing = 36, Alchemy = 37, Learning = 38, } end const.Condition = { Cursed = 0, Weak = 1, Asleep = 2, Afraid = 3, Drunk = 4, Insane = 5, Poison1 = 6, Disease1 = 7, Poison2 = 8, Disease2 = 9, Poison3 = 10, Disease3 = 11, Paralyzed = 12, Unconscious = 13, Dead = 14, Stoned = 15, Eradicated = 16, } if mmver > 6 then const.Condition.Zombie = 17 end const.ItemType = { Any = 0, Weapon = 1, Weapon2H = 2, Missile = 3, Armor = 4, Shield = 5, Helm = 6, Belt = 7, Cloak = 8, Gountlets = 9, Boots = 10, Ring = 11, Amulet = 12, Wand = 13, -- weaponw Reagent = 14, -- herb Potion = 15, -- bottle Scroll = 16, -- sscroll Book = 17, MScroll = 18, -- always creates item 001 Gold = 19, Weapon_ = 20, Armor_ = 21, Misc = 22, Sword = 23, Dagger = 24, Axe = 25, Spear = 26, Bow = 27, Mace = 28, Club = 29, Staff = 30, Leather = 31, Chain = 32, Plate = 33, Shield_ = 34, Helm_ = 35, Belt_ = 36, Cloak_ = 37, Gountlets_ = 38, Boots_ = 39, Ring_ = 40, Amulet_ = 41, Wand_ = 42, Scroll_ = 43, Potion = 44, Reagent = 45, Gems = 46, Gems2 = 47, Gold = 50, } if mmver == 6 then const.Damage = { Phys = 0, Magic = 1, Fire = 2, Elec = 3, Cold = 4, Poison = 5, Energy = 6, } else const.Damage = { Fire = 0, Air = 1, Water = 2, Earth = 3, Phys = 4, Magic = 5, Spirit = 6, Mind = 7, Body = 8, Light = 9, Dark = 10, Dragon = 50, } end if mmver == 6 then const.Class = { Knight = 0, Cavalier = 1, Champion = 2, Cleric = 3, Priest = 4, HighPriest = 5, Sorcerer = 6, Wizard = 7, ArchMage = 8, Paladin = 9, Crusader = 10, Hero = 11, Archer = 12, BattleMage = 13, WarriorMage = 14, Druid = 15, GreatDruid = 16, ArchDruid = 17, } elseif mmver == 7 then const.Class = { Knight = 0, Cavalier = 1, Champion = 2, BlackKnight = 3, Thief = 4, Rogue = 5, Spy = 6, Assassin = 7, Monk = 8, Initiate = 9, Master = 10, Ninja = 11, Paladin = 12, Crusader = 13, Hero = 14, Villain = 15, Archer = 16, WarriorMage = 17, MasterArcher = 18, Sniper = 19, Ranger = 20, Hunter = 21, RangerLord = 22, BountyHunter = 23, Cleric = 24, Priest = 25, PriestLight = 26, PriestDark = 27, Druid = 28, GreatDruid = 29, ArchDruid = 30, Warlock = 31, Sorcerer = 32, Wizard = 33, ArchMage = 34, Lich = 35, } else const.Class = { Necromancer = 0, Lich = 1, Cleric = 2, PriestLight = 3, Knight = 4, Champion = 5, Troll = 6, WarTroll = 7, Minotaur = 8, MinotaurLord = 9, DarkElf = 10, Patriarch = 11, Vampire = 12, Nosferatu = 13, Dragon = 14, GreatWyrm = 15, } end if mmver == 7 then const.Race = { Human = 0, Elf = 1, Goblin = 2, Dwarf = 3, } end if mmver == 6 then const.Stats = { Might = 0, Intellect = 1, Personality = 2, Endurance = 3, Accuracy = 4, Speed = 5, Luck = 6, HP = 7, HitPoints = 7, SP = 8, SpellPoints = 8, ArmorClass = 9, FireResistance = 10, ElecResistance = 11, ColdResistance = 12, PoisonResistance = 13, Level = 14, MeleeAttack = 15, MeleeDamageBase = 16, MeleeDamageMin = 17, MeleeDamageMax = 18, RangedAttack = 19, RangedDamageBase = 20, RangedDamageMin = 21, RangedDamageMax = 22, MagicResistance = 23, } else const.Stats = { Might = 0, Intellect = 1, Personality = 2, Endurance = 3, Accuracy = 4, Speed = 5, Luck = 6, HP = 7, HitPoints = 7, SP = 8, SpellPoints = 8, ArmorClass = 9, FireResistance = 10, AirResistance = 11, WaterResistance = 12, EarthResistance = 13, MindResistance = 14, BodyResistance = 15, Alchemy = 16, Stealing = 17, DisarmTraps = 18, IdentifyItem = 19, IdentifyMonster = 20, Armsmaster = 21, Dodging = 22, Unarmed = 23, Level = 24, MeleeAttack = 25, MeleeDamageBase = 26, MeleeDamageMin = 27, MeleeDamageMax = 28, RangedAttack = 29, RangedDamageBase = 30, RangedDamageMin = 31, RangedDamageMax = 32, SpiritResistance = 33, FireMagic = 34, AirMagic = 35, WaterMagic = 36, EarthMagic = 37, SpiritMagic = 38, MindMagic = 39, BodyMagic = 40, LightMagic = 41, DarkMagic = 42, Meditation = 43, Bow = 44, Shield = 45, Learning = 46, } end if mmver == 8 then table.copy({ DarkElf = 47, Vampire = 48, Dragon = 49, }, const.Stats, true) end const.Screens = { Game = 0, Manu = 1, Controls = 2, Info = 3, -- quests, map, autonotes NPC = 4, Rest = 5, Query = 6, -- like with hotkeys in Chinese debug MM6 Inventory = 7, SpellBook = 8, NewGameBreefing = 9, Chest = 10, SaveGame = 11, LoadGame = 12, House = 13, MainManu = 16, -- or movie WalkToMap = 17, MapEntrance = 18, -- or evt.Question SimpleMessage = 19, -- 20 is some sort of rendered screen CreateParty = 21, EscMessage = 22, KeyConfig = 26, VideoOptions = 28, QuickReference = 104, } const.FaceAnimation = { KillSmallEnemy = 1, KillBigEnemy = 2, StoreClosed = 3, DisarmTrap = 4, TrapWillBlow = 5, -- it's gonna blow! AvoidTrapDamage = 6, -- sit down IdentifyUseless = 7, IdentifyGreat = 8, IdentifyFail = 9, RepairItem = 10, RepairFail = 11, SetQuickSpell = 12, CantRestHere = 13, SmileRandom = 14, CantCarry = 15, MixPotion = 16, PotionExplode = 17, DoorLocked = 18, Strain = 19, -- like pulling sword out of stone in MM6 CantLearnSpell = 20, LearnSpell = 21, Hello = 22, HelloNight = 23, Damaged = 24, Weak = 25, Afraid = 26, Poisoned = 27, Deseased = 28, Insane = 29, Cursed = 30, Drunk = 31, Unconsious = 32, Death = 33, Stoned = 34, Eradicated = 35, Smile = 36, ReadScoll = 37, NotEnoughGold = 38, CantEquip = 39, ItemBrokenStolen = 40, SPDrained = 41, Aged = 42, SpellFailed = 43, DamagedParty = 44, Tired = 45, EnterDungeon = 46, -- come on let's go in LeaveDungeon = 47, -- let's get out of here AlmostDead = 48, CastSpell = 49, Shoot = 50, AttackHit = 51, AttackMiss = 52, Beg = 53, BegFail = 54, ThreatFail = 56, SmileHuge = 57, BribeFail = 58, NPCDontTalk = 59, SmileRandom2 = 60, LookUp = 63, LookDown = 64, Yell = 65, Falling = 66, ShakeHeadNo = 67, -- shakes head TavernGotDrunk = 69, TavernTip = 70, ShakeHeadYes = 71, ShopIdentify = 73, ShopRepair = 74, ShopAlreadyIdentified = 76, ShopWrongShop = 79, ShopRude = 80, BankDeposit = 81, SmileBig = 82, TempleDonate = 83, HelloHouse = 84, AfraidSilent = 98, InPrison = 100, ChooseMe = 102, Awaken = 103, IdMonsterWeak = 104, IdMonsterBig = 105, IdMonsterFail = 106, LastManStanding = 107, Hungry = 108, } const.Season = { Automn = 0, Summer = 1, Fall = 2, Winter = 3, } if mmver == 6 then const.PartyBuff = { FireResistance = 0, ColdResistance = 1, ElecResistance = 2, MagicResistance = 3, PoisonResistance = 4, FeatherFall = 5, WaterWalk = 6, Fly = 7, GuardianAngel = 8, WizardEye = 10, TorchLight = 11, } const.PlayerBuff = { Bless = 0, Heroism = 1, Haste = 2, Shield = 3, Stoneskin = 4, TempLuck = 5, TempIntellect = 6, TempPersonality = 7, TempAccuracy = 8, TempSpeed = 9, TempMight = 10, TempEndurancy = 11, } const.MonsterBuff = { Null = 0, Charm = 1, Curse = 2, ShrinkingRay = 3, Fear = 4, Stoned = 5, Paralyze = 6, Slow = 7, Feeblemind = 8, -- unknown: 9 - 13 } elseif mmver == 7 then const.PartyBuff = { AirResistance = 0, BodyResistance = 1, DayOfGods = 2, DetectLife = 3, EarthResistance = 4, FeatherFall = 5, FireResistance = 6, Fly = 7, Haste = 8, Heroism = 9, Immolation = 10, Invisibility = 11, MindResistance = 12, ProtectionFromMagic = 13, Shield = 14, Stoneskin = 15, TorchLight = 16, WaterResistance = 17, WaterWalk = 18, WizardEye = 19, } const.PlayerBuff = { AirResistance = 0, Bless = 1, BodyResistance = 2, EarthResistance = 3, Fate = 4, FireResistance = 5, Hammerhands = 6, Haste = 7, Heroism = 8, MindResistance = 9, PainReflection = 10, Preservation = 11, Regeneration = 12, Shield = 13, Stoneskin = 14, TempAccuracy = 15, TempEndurance = 16, TempIntellect = 17, TempLuck = 18, TempMight = 19, TempPersonality = 20, TempSpeed = 21, WaterResistance = 22, WaterBreathing = 23, } const.MonsterBuff = { Null = 0, Charm = 1, Summoned = 2, ShrinkingRay = 3, Fear = 4, Stoned = 5, Paralyze = 6, Slow = 7, ArmorHalved = 8, Berserk = 9, MassDistortion = 10, Fate = 11, Enslave = 12, DayOfProtection = 13, HourOfPower = 14, Shield = 15, StoneSkin = 16, Bless = 17, Heroism = 18, Haste = 19, PainReflection = 20, Hammerhands = 21, } else const.PartyBuff = { AirResistance = 0, BodyResistance = 1, DayOfGods = 2, DetectLife = 3, EarthResistance = 4, FeatherFall = 5, FireResistance = 6, Fly = 7, Haste = 8, Heroism = 9, Immolation = 10, Invisibility = 11, MindResistance = 12, ProtectionFromMagic = 13, Shield = 14, Stoneskin = 15, TorchLight = 16, WaterResistance = 17, WaterWalk = 18, WizardEye = 19, } const.PlayerBuff = { AirResistance = 0, Bless = 1, BodyResistance = 2, EarthResistance = 3, Fate = 4, FireResistance = 5, Hammerhands = 6, Haste = 7, Heroism = 8, MindResistance = 9, PainReflection = 10, Preservation = 11, Regeneration = 12, Shield = 13, Stoneskin = 14, TempAccuracy = 15, TempEndurance = 16, TempIntellect = 17, TempLuck = 18, TempMight = 19, TempPersonality = 20, TempSpeed = 21, WaterResistance = 22, WaterBreathing = 23, Glamour = 24, Levitate = 25, Misform = 26, } const.MonsterBuff = { Null = 0, Charm = 1, Summoned = 2, ShrinkingRay = 3, Fear = 4, Stoned = 5, Paralyze = 6, Slow = 7, Berserk = 8, MassDistortion = 9, Fate = 10, Enslave = 11, DayOfProtection = 12, HourOfPower = 13, Shield = 14, StoneSkin = 15, Bless = 16, Heroism = 17, Haste = 18, PainReflection = 19, Hammerhands = 20, ArmorHalved = 21, MeleeOnly = 22, -- (part of Blind and Dark Grasp) DamageHalved = 23, Wander = 24, -- monster wanders aimlessly (part of Blind) Mistform = 25, } end const.GameActions = { Exit = 113, } const.HouseTypeInv = { "Weapon Shop", "Armor Shop", "Magic Shop", (mmver == 6 and "General Store" or "Alchemist"), "Fire Guild", "Air Guild", "Water Guild", "Earth Guild", "Spirit Guild", "Mind Guild", "Body Guild", "Light Guild", "Dark Guild", (mmver == 6 and "Element Guild" or "Elemental Guild"), "Self Guild", nil, -- 16 - "mir..." - planned, but not realized Mirrored Path Guild of Light and Dark (mmver ~= 6 and "Town Hall" or "Thieves Guild"), -- everything else in MM6 "Merc Guild", mmv("Town Hall"), "Throne", "Tavern", "Bank", "Temple", "Castle Entrance", "Dungeon Ent", "Seer", "Stables", "Boats", "House", "Training", "Jail", "Circus", nil, -- 33 nil, -- 34 "The Adventurer's Inn", } const.HouseType = table.invert(const.HouseTypeInv) const.HouseType["Element Guild"] = 14 -- MM6 const.HouseType["Elemental Guild"] = 14 -- MM7,8 const.HouseType["The Seer"] = 26 -- MM6, MM7 const.HouseType["The Oracle"] = 26 -- MM6 const.HouseType["Seer Good"] = 26 -- MM7 const.HouseType["Seer Evil"] = 26 -- MM7 const.HouseType["Spell Shop"] = 14 -- MM8 const.HouseType["Castle Ent"] = 24 -- consistancy const.HouseType["Dungeon Entrance"] = 25 -- consistancy if mmver == 6 then const.NPCProfession = { Smith = 1, Armorer = 2, Alchemist = 3, Scholar = 4, Guide = 5, Tracker = 6, Pathfinder = 7, Sailor = 8, Navigator = 9, Healer = 10, ExpertHealer = 11, MasterHealer = 12, Teacher = 13, Instructor = 14, ArmsMaster = 15, WeaponsMaster = 16, Apprentice = 17, Mystic = 18, SpellMaster = 19, Trader = 20, Merchant = 21, Scout = 22, Counselor = 23, Barrister = 24, Tinker = 25, Locksmith = 26, Fool = 27, ChimneySweep = 28, Porter = 29, QuarterMaster = 30, Factor = 31, Banker = 32, Cook = 33, Chef = 34, Horseman = 35, Bard = 36, Enchanter = 37, Cartographer = 38, WindMaster = 39, WaterMaster = 40, GateMaster = 41, Acolyte = 42, Piper = 43, Explorer = 44, Pirate = 45, Squire = 46, Psychic = 47, Gypsy = 48, Negotiator = 49, Duper = 50, Burglar = 51, Peasant = 52, Serf = 53, Tailor = 54, Laborer = 55, Farmer = 56, Cooper = 57, Potter = 58, Weaver = 59, Cobbler = 60, DitchDigger = 61, Miller = 62, Carpenter = 63, StoneCutter = 64, Jester = 65, Trapper = 66, Beggar = 67, Rustler = 68, Hunter = 69, Scribe = 70, Missionary = 71, Clerk = 72, Guard = 73, FollowerofBaa = 74, Noble = 75, Gambler = 76, Child = 77, } elseif mmver == 7 then const.NPCProfession = { Smith = 1, Armorer = 2, Alchemist = 3, Scholar = 4, Guide = 5, Tracker = 6, Pathfinder = 7, Sailor = 8, Navigator = 9, Healer = 10, ExpertHealer = 11, MasterHealer = 12, Teacher = 13, Instructor = 14, ArmsMaster = 15, WeaponsMaster = 16, Apprentice = 17, Mystic = 18, SpellMaster = 19, Trader = 20, Merchant = 21, Scout = 22, Herbalist = 23, Apothecary = 24, Tinker = 25, Locksmith = 26, Fool = 27, ChimneySweep = 28, Porter = 29, QuarterMaster = 30, Factor = 31, Banker = 32, Cook = 33, Chef = 34, Horseman = 35, Bard = 36, Enchanter = 37, Cartographer = 38, WindMaster = 39, WaterMaster = 40, GateMaster = 41, Chaplain = 42, Piper = 43, Explorer = 44, Pirate = 45, Squire = 46, Psychic = 47, Gypsy = 48, Diplomat = 49, Duper = 50, Burglar = 51, FallenWizard = 52, Acolyte = 53, Initiate = 54, Prelate = 55, Monk = 56, Sage = 57, Hunter = 58, } end
----------------------------------- -- Area: Mamook -- Mob: Poroggo Casanova -- ToAU Quest: Prince and the Hopper ----------------------------------- local ID = require("scripts/zones/Mamook/IDs") function onMobSpawn(mob) end function onMobDeath(mob, player, isKiller) if player:getQuestStatus(AHT_URHGAN, tpz.quest.id.ahtUrhgan.THE_PRINCE_AND_THE_HOPPER) == QUEST_ACCEPTED and player:getCharVar("princeandhopper") == 4 then player:setCharVar("princeandhopper", 5) end for i = ID.mob.POROGGO_CASANOVA + 1, ID.mob.POROGGO_CASANOVA + 5 do DespawnMob(i) end end function onMobDespawn(mob) for i = ID.mob.POROGGO_CASANOVA + 1, ID.mob.POROGGO_CASANOVA + 5 do DespawnMob(i) end end
-- gcRobotGlobals-Signature.lua -- Author: Gaticus Hax -- License: Public Domain require("Scripts.HaxablesMonitor") local mbinFile = "GCROBOTGLOBALS.MBIN" local dataSignature = "00 00 A0 42 00 00 40 3F 00 00 00 3F CD CC CC 3D 01 00 00 00 33 33 B3 3F 00 00 00 40 00 00 40 40" local dataOffset = 0x0000 defineMBIN(mbinFile, dataSignature, dataOffset)
package.path = "./luckynet/lnlib/?.lua;" .. package.path package.path = "./luckyproto/?.lua;" .. package.path package.path = "./luckynet/game/?.lua;" .. package.path require "debug_proto_defines" require "game_define"
function init() self.sounds = config.getParameter("sounds", {}) animator.setSoundPool("noise", self.sounds) object.setInteractive(true) end function onInteraction() if #self.sounds > 0 then animator.playSound("noise") end end function onNpcPlay(npcId) local interact = config.getParameter("npcToy.interactOnNpcPlayStart") if interact == nil or interact ~= false then onInteraction() end end
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <hadriel@128technology.com> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end local Settings = require "settings" local dprint = Settings.dprint local dprint2 = Settings.dprint2 local dassert = Settings.dassert local derror = Settings.derror local dsummary = Settings.dsummary local AstFactory = require "ast.factory" local StatementBase = require "ast.statement_base" local Identifier = require "ast.identifier" local FieldStatement = require "ast.field" local ProtocolDispatch = require "protocol.dispatch" local protocol_dispatcher = ProtocolDispatch.dispatcher -------------------------------------------------------------------------------- -- MessageStatement class, for "Message" statements -- local MessageStatement = {} local MessageStatement_mt = { __index = MessageStatement } setmetatable( MessageStatement, { __index = StatementBase } ) -- make it inherit from StatementBase AstFactory:registerClass("MESSAGE", "MessageStatement", MessageStatement, true) function MessageStatement.preParse(st) dassert(AstFactory.verifyTokenTTypes("Message", st, "MESSAGE", "IDENTIFIER", "BRACE_BLOCK")) return Identifier.new(st, 2) end function MessageStatement:postParse(st, id, namespace) local ns = namespace:addDeclaration(id, self) local value = {} for _,tokens in ipairs(st[3].value) do -- XXX not canBeIdentifier(); that covers too much if tokens[1] and (tokens[1]:isNativeType() or tokens[1].ttype == "IDENTIFIER") then value[#value+1] = FieldStatement.new(ns, tokens) else value[#value+1] = AstFactory:dispatchBodyStatement(ns, tokens) end end return ns, value end function MessageStatement.new(namespace, st) local id = MessageStatement.preParse(st) local new_class = StatementBase.new("MESSAGE", id) setmetatable( new_class, MessageStatement_mt ) -- call postParse on the new instance local ns, value = new_class:postParse(st, id, namespace) new_class:setNamespace(ns) new_class:setValue(value) return new_class end local ignore_types = { IGNORE = true, OPTION = true, SYNTAX = true, -- the ONEOF will add its fields to the Message before being ignored ONEOF = true, -- remove these, so they end up only being in their namespace's -- declaration tables MESSAGE = true, ENUM = true, MAP = true, } function MessageStatement:analyze() local fields = {} -- temporary tags table to verify no duplicate tags local tags = {} for _, object in ipairs(self.value) do object:analyze(fields, tags) if not ignore_types[object:getType()] then dassert(not tags[object:getTag()], "Two fields with same tag number '", object:getTag(), "' in Message: ", self:getName()) tags[object:getTag()] = object fields[#fields+1] = object end end self.value = fields end -------------------------------------------------------------------------------- -- functions for the back_end local Prefs = require "prefs" local Decoder = require "back_end.decoder" local MessageDecoder = require "back_end.message" local PacketDecoder = require "back_end.packet" function MessageStatement:createTagTable() if not self.tag_table then local tags, pfields = {}, {} for _, field in ipairs(self.value) do local pfield = field:getProtoField(pfields) pfields[#pfields+1] = pfield tags[field:getTag()] = field:getDecoder(pfield, field:getTag(), field:getName()) end self.tag_table = tags self.pfields = pfields end return self.tag_table end -- this is invoked by both the Field class and the Message class; for -- the Field class it's done to get a decoder for the Message as a field -- inside another Message/Group; when done by the Message class, it's to -- get a decoder to use as the initial one when dissecting a top-level -- Message (i.e., dissect itself), in which case the tag will be 0 and -- the name will be the same as the Proto object's protocol name function MessageStatement:getDecoder(pfield, tag, name, label, oneof_name) self:createProto() self:createTagTable() dassert(self.proto, "Programming error: Proto not created") return MessageDecoder.new(pfield, tag, name, self.proto, self:getName(), self.tag_table, label, oneof_name) end -- this creates the wireshark Proto.dissector function, used if this -- Message is the top-level Message of a packet function MessageStatement:createDissector() -- this gets a decoder for the Proto object only, not a field local packet_decoder = PacketDecoder.new(self.proto, self:getName(), self.tag_table) -- this creates a new function, so local variables are saved as upvalues -- and do not need to be stored in the self/proto object self.proto.dissector = function(tvbuf,pktinfo,root) -- XXX this can return nil if the packet has no protobuf payload local message_decoder = Decoder.new(tvbuf, pktinfo, root) if message_decoder then message_decoder:decode(packet_decoder) -- dsummary("MessageStatement:createDissector", "packet_decoder", packet_decoder) -- dsummary("proto.dissector (" .. self:getName() .. ")", "message_decoder", -- message_decoder) end end end -- createProto() is called to create a full dissector implementation for a -- Message - i.e., it creates the Proto object and Prefs and so on: things -- done only once for a given Message object, to make it a fully stand-alone -- Protocol dissector. To accomplish that, it invokes getDecoder() for -- everything in it, including other Message objects, but unlike this -- createProto() function, the getDecoder() only creates the stuff needed to -- be fields within a Massage - essentially the ProtoFields and such. function MessageStatement:createProto() --dassert(not self.proto, "Programming error: MessageStatement:createProto() called more than once") if not self.proto then dprint("Creating Proto for", self.namespace:getFullName(), "with name:", self:getName()) self.proto = Proto.new(self.namespace:getFullName(), self.namespace:getFullName()) -- this is called for each new capture file -- XXX it's called once for each Proto object, but no matter! self.proto.init = function() protocol_dispatcher:reset() end self:createTagTable() -- register the ProtoFields self.proto.fields = self.pfields self:createDissector() Prefs:create(self.proto) -- add it for port 0 so it can be used in "Decode As..." DissectorTable.get("udp.port"):add(0, self.proto) DissectorTable.get("tcp.port"):add(0, self.proto) end return self.proto end function MessageStatement:createProtocol() local t = {} t.proto = self:createProto() t.tag_table = self:createTagTable() return t end return MessageStatement