content
stringlengths 5
1.05M
|
|---|
return {
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 500,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 720,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 940,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 1160,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 1380,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 1600,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 1820,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 2040,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 2260,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
{
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 2500,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
},
time = 0,
name = "祥瑞御免",
init_effect = "jinengchufablue",
color = "blue",
picture = "",
desc = "",
stack = 1,
id = 11241,
icon = 11240,
last_effect = "",
blink = {
0,
0.7,
1,
0.3,
0.3
},
effect_list = {
{
type = "BattleBuffFixDamage",
trigger = {
"onTakeDamage"
},
arg_list = {
value = 1,
rant = 500,
target = "TargetSelf",
time = 0
}
},
{
type = "BattleBuffAddAttr",
trigger = {
"onAttach"
},
arg_list = {
attr = "luck",
target = "TargetSelf",
number = 5
}
}
}
}
|
local Ans = select(2, ...);
local Leather = {};
Leather.children = {
{
name = "BFA",
ids = "i:152541,i:154164,i:154165,i:153050,i:153051,i:154722,i:152542,i:168649",
useMaxPPU = true,
useMinLevel = false,
useQuality = true,
useMinStack = true,
usePercent = true,
exactMatch = true,
priceFn = "",
types = "",
subtypes = ""
},
{
name = "Legion",
ids = "i:124116,i:136533,i:136534,i:110609,i:110611,i:124113,i:124115",
useMaxPPU = true,
useMinLevel = false,
useQuality = true,
useMinStack = true,
usePercent = true,
exactMatch = true,
priceFn = "",
types = "",
subtypes = ""
},
{
name = "Pre-Legion",
ids = "i:110610,i:72163,i:112157,i:79101,i:72120,i:72162,i:52982,i:112155,i:112156,i:52979,i:52976,i:52977,i:38557,i:38561,i:112158,i:44128,i:33567,i:33568,i:38558,i:112182,i:25707,i:15410,i:15414,i:17012,i:21887,i:25649,i:25699,i:25700,i:25708,i:29539,i:29547,i:29548,i:112185,i:15408,i:15416,i:8171,i:15412,i:15415,i:15417,i:8170,i:15419,i:8154,i:8165,i:4304,i:8169,i:8167,i:4234,i:4235,i:2319,i:4232,i:783,i:2318,i:2934,i:6470,i:6471,i:7286,i:7392",
useMaxPPU = true,
useMinLevel = false,
useQuality = true,
useMinStack = true,
usePercent = true,
exactMatch = true,
priceFn = "",
types = "",
subtypes = ""
}
};
Leather.name = "Leather";
Leather.ids = "";
Leather.useMaxPPU = true;
Leather.useMinLevel = false;
Leather.useQuality = true;
Leather.useMinStack = true;
Leather.usePercent = true;
Leather.priceFn = "";
Leather.types = "";
Leather.subtypes = "";
tinsert(Ans.Data, Leather);
|
local transitioning_out = false
local Update = function(self, dt)
if not transitioning_out then
SL.Global.MenuTimer.ScreenSelectMusic = SCREENMAN:GetTopScreen():GetChild("Timer"):GetSeconds()
end
end
return Def.ActorFrame{
InitCommand=function(self)
-- if the MenuTimer is being used, save the current number of seconds remaining
-- before transitioning to the next screen. In this manner, we can reinstate this
-- value if the player opts to return to ScreenSelectMusic from ScreenPlayerOptions.
if PREFSMAN:GetPreference("MenuTimer") then
self:SetUpdateFunction(Update)
end
-- SL.Global.DiscordPresence.smalltext = GAMESTATE:IsEventMode() and "Event Mode" or GAMESTATE:GetCoins().." credits remaining..."
-- SL.Global.DiscordPresence.state = GAMESTATE:IsCourseMode() and "Playing ".. SL.Global.GameMode.." "..GAMESTATE:GetCurrentStyle():GetName().. "s marathon" or "Playing ".. SL.Global.GameMode.." "..GAMESTATE:GetCurrentStyle():GetName().. "s"
-- if not transitioning_out then
-- GAMESTATE:UpdateDiscordPresenceDetails("Stage: "..(GAMESTATE:GetCurrentStageIndex()+1) .." || "..GAMESTATE:GetNumSidesJoined().." Player",SL.Global.DiscordPresence.smalltext,"default","selectmusic","Selecting Music...",SL.Global.DiscordPresence.state, SL.Global.DiscordPresence.startTime)
-- else
-- SL.Global.DiscordPresence.startTime = os.time()
-- GAMESTATE:UpdateDiscordPresenceDetails("Stage: "..(GAMESTATE:GetCurrentStageIndex()+1) .." || "..GAMESTATE:GetNumSidesJoined().." Player",SL.Global.DiscordPresence.smalltext,"default","selectmusic","Selecting Music...",SL.Global.DiscordPresence.state, SL.Global.DiscordPresence.startTime)
-- end
end,
ViewGalleryCommand=function(self)
transitioning_out = true
end,
ShowPressStartForOptionsCommand=function(self)
transitioning_out = true
end
}
|
-- Mask.lua
-- Contains the cMask class representing blocks that can be replaced. Used for example in masks and the replace command.
cMask = {}
local function ParseBlockArray(a_BlockArray)
-- Make from the array a table with the blocktypes as keys.
-- In there create a table a boolean value called TypeOnly, and a table containing blockmetas
-- If TypeOnly is set to true the Contains function will only check if the blocktype exists. Else it will look if the blockmeta exists in the BlockMetas table.
local BlockTable = {}
for Idx, Block in ipairs(a_BlockArray) do
local BlockInfo = BlockTable[Block.BlockType] or {TypeOnly = false, BlockMetas = {}}
BlockInfo.TypeOnly = BlockInfo.TypeOnly or Block.TypeOnly
if (not BlockInfo.TypeOnly) then
BlockInfo.BlockMetas[Block.BlockMeta] = true
end
-- Save the blockinfo in the table with the blocktype as key.
BlockTable[Block.BlockType] = BlockInfo
end
return BlockTable;
end
local function Contains(a_BlockTable, a_BlockType, a_BlockMeta)
local BlockInfo = a_BlockTable[a_BlockType]
if (not BlockInfo) then
return false
end
if (BlockInfo.TypeOnly) then
-- The block is marked to only check the blocktype, so we don't have to check the meta.
-- Since the block exists in the blocktable we can just return true
return true
end
-- Check if the meta exists. If it exists it has the value true, so we either return that or return false.
return BlockInfo.BlockMetas[a_BlockMeta] or false
end
function cMask:new(a_PositiveBlocks, a_NegativeBlocks)
-- Get all the different blocks from the string
local Obj = {}
setmetatable(Obj, cMask)
self.__index = self
Obj.m_PositiveBlockTable = {}
Obj.m_NegativeBlockTable = nil
if (a_PositiveBlocks ~= nil) then
local BlockArray, ErrorBlock = RetrieveBlockTypes(a_PositiveBlocks)
if (not BlockArray) then
return false, ErrorBlock
end
Obj.m_PositiveBlockTable = ParseBlockArray(BlockArray)
end
if (a_NegativeBlocks ~= nil) then
local BlockArray, ErrorBlock = RetrieveBlockTypes(a_NegativeBlocks)
if (not BlockArray) then
return false, ErrorBlock
end
Obj.m_NegativeBlockTable = ParseBlockArray(BlockArray)
end
return Obj
end
-- Checks if the given blocktype exists in the blocktable.
function cMask:Contains(a_BlockType, a_BlockMeta)
if (self.m_NegativeBlockTable ~= nil and not Contains(self.m_NegativeBlockTable, a_BlockType, a_BlockMeta)) then
return true;
end
if (not Contains(self.m_PositiveBlockTable, a_BlockType, a_BlockMeta)) then
return false;
end
return true;
end
|
add_rules("mode.debug", "mode.release")
set_languages("c++17")
set_default("AFK")
target("AFK")
set_kind("static")
add_files("src/*.cpp")
add_includedirs("include/", {public = true})
target("tests")
set_kind("binary")
add_files("tests/*.cpp")
add_deps("AFK")
|
--阴影降临
local m=14010090
local cm=_G["c"..m]
function cm.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(cm.con)
e1:SetTarget(cm.tg)
e1:SetOperation(cm.op)
c:RegisterEffect(e1)
end
function cm.con(e,tp,eg,ep,ev,re,r,rp)
return not Duel.IsExistingMatchingCard(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil)
end
function cm.filter(c,e,tp)
return c:IsType(TYPE_FLIP) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function cm.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(cm.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function cm.op(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,cm.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEDOWN_DEFENSE)
Duel.ConfirmCards(1-tp,g)
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetTarget(aux.TargetBoolFunction(Card.IsLocation,LOCATION_DECK))
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
|
wk.register({
['<leader>f'] = { name = '+Fuzzy Find' },
['<leader>ff'] = { '<cmd>Telescope find_files<cr>', 'Find file' },
['<leader>fg'] = { '<cmd>Telescope git_files<cr>', 'Find git file' },
['<leader>fr'] = { '<cmd>Telescope live_grep<cr>', 'Grep every line in current directory' },
['<leader>fb'] = { '<cmd>Telescope current_buffer_fuzzy_find<cr>', 'Grep every line in current buffer' },
['<leader>fh'] = { '<cmd>Telescope git_branches<cr>', 'Find git branches' },
['<leader>fc'] = { '<cmd>Telescope colorscheme<cr>', 'Find color scheme' },
['<leader>fm'] = { '<cmd>Telescope marks<cr>', 'Find marks' },
['<leader>fl'] = { '<cmd>Telescope lsp_workspace_diagnostics<cr>', 'Find LSP diagnostics' },
['<leader>fs'] = { '<cmd>Telescope spell_suggest<cr>', 'Find spell suggestions' },
['<leader>fv'] = { '<cmd>lua require("plugin.telescope").search_dotfiles()<cr>', 'Browse vim configuration' },
['<leader>fk'] = { '<cmd>lua require("telescope").extensions.file_browser.file_browser()<cr>', "File browser"}
})
|
-- use {
-- "Mofiqul/vscode.nvim",
-- require "colorschemes.vscode_nvim"
-- end
-- }
vim.g.vscode_style = "dark"
-- vim.g.vscode_transparent = 1
vim.cmd("colo vscode")
vim.cmd("hi ColorColumn guibg=#444444")
|
function Create_Hgn_Carrier_Research0(CustomGroup, playerIndex, shipID)
if (Player_GetNumberOfSquadronsOfTypeAwakeOrSleeping(playerIndex, "hgn_mothership") == 0) and (Player_GetNumberOfSquadronsOfTypeAwakeOrSleeping(playerIndex, "hgn_mothership_research0") == 0) then
if playerIndex == Universe_CurrentPlayer() then
UI_SetElementSize("NewResearchMenu", "NonCombat", 0, 0);
end
end
end
function Update_Hgn_Carrier_Research0(CustomGroup, playerIndex, shipID)
--SobGroup_CreateIfNotExist("hgn_carrier_research0"..playerIndex)
--SobGroup_Clear("hgn_carrier_research0"..playerIndex)
--SobGroup_SobGroupAdd("hgn_carrier_research0"..playerIndex, CustomGroup)
end
|
-- test/test-lace.lua
--
-- Lua Access Control Engine -- Tests for the Lace error module
--
-- Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
--
-- For Licence terms, see COPYING
--
-- Step one, start coverage
pcall(require, 'luacov')
local error = require 'lace.error'
local testnames = {}
local real_assert = assert
local total_asserts = 0
local function assert(...)
real_assert(...)
total_asserts = total_asserts + 1
end
local function add_test(suite, name, value)
rawset(suite, name, value)
testnames[#testnames+1] = name
end
local suite = setmetatable({}, {__newindex = add_test})
function suite.error_formation()
local words = {}
local ret1, ret2 = error.error("msg", words)
assert(ret1 == false, "First return of error() should be false")
assert(type(ret2) == "table", "Second return of error() should be a table")
assert(ret2.msg == "msg", "Message should be passed through")
assert(ret2.words == words, "Words should be passed through")
end
function suite.error_offset()
--luacheck: ignore 211/f
local words = {3,5}
local f, err = error.error("msg", words)
local nerr = error.offset(err, 2)
assert(nerr == err, "Offset should return the same error it was given")
assert(words[1] == 5, "Offset should alter the first word")
assert(words[2] == 7, "Offset should alter all the words")
end
function suite.error_augmentation()
--luacheck: ignore 211/f
local f, err = error.error("msg")
local src = {}
local aug = error.augment(err, src, 10)
assert(aug == err, "Augmentation should return the error")
assert(err.words.source == src, "Augmented errors should contain their source data")
assert(err.words.linenr == 10, "Augmented errors should contain their error line")
end
function suite.error_render()
--luacheck: ignore 211/f
local f, err = error.error("msg", {1, 3})
local src = { source = "SOURCE", lines = {
{
original = " ORIG LINE FISH",
content = {
{ spos = 3, epos = 6, str = "ORIG" },
{ spos = 8, epos = 11, str = "LINE" },
{ spos = 13, epos = 16, str = "FISH" },
}
}
}
}
error.augment(err, src, 1)
local estr = error.render(err)
local line1, line2, line3, line4 = estr:match("^([^\n]*)\n([^\n]*)\n([^\n]*)\n([^\n]*)$")
assert(line1, "There is a line 1")
assert(line2, "There is a line 2")
assert(line3, "There is a line 3")
assert(line4, "There is a line 4")
assert(line1 == "msg", "The first line should be the error message")
assert(line2 == "SOURCE :: 1", "The second line is where the error happened")
assert(line3 == src.lines[1].original, "The third line is the original line")
assert(line4 == " ^^^^ ^^^^", "The fourth line highlights relevant words")
end
function suite.error_render_bad_line()
--luacheck: ignore 211/f
local f, err = error.error("msg", {1, 3})
local src = { source = "SOURCE", lines = { } }
error.augment(err, src, 1)
local estr = error.render(err)
local line1, line2, line3, line4 = estr:match("^([^\n]*)\n([^\n]*)\n([^\n]*)\n([^\n]*)$")
assert(line1, "There is a line 1")
assert(line2, "There is a line 2")
assert(line3, "There is a line 3")
assert(line4, "There is a line 4")
assert(line1 == "msg", "The first line should be the error message")
assert(line2 == "SOURCE :: 1", "The second line is where the error happened")
assert(line3 == "???", "The third line is the original line")
assert(line4 == "^^^", "The fourth line highlights relevant words")
end
local count_ok = 0
for _, testname in ipairs(testnames) do
-- print("Run: " .. testname)
local ok, err = xpcall(suite[testname], debug.traceback)
if not ok then
print(err)
print()
else
count_ok = count_ok + 1
end
end
print(tostring(count_ok) .. "/" .. tostring(#testnames) .. " [" .. tostring(total_asserts) .. "] OK")
os.exit(count_ok == #testnames and 0 or 1)
|
package.path = getScriptPath() .. '/?.lua;' .. package.path
local RankedWatchList = require('ranked_watch_list')
local settings = {
color = {
new = RGB(0, 255, 0),
old = RGB(255, 255, 0),
out = RGB(255, 0, 0)
},
daysBack = 0,
top = 8,
period = 5, -- trading week
}
local getWatchList = function ()
return {
TQBR = {
"RASP",
"HYDR",
"GMKN",
"LKOH",
"MVID",
"CHMF",
"MFON",
"NVTK",
"ALRS",
"NLMK",
"RTKM",
"SNGSP",
"ROSN",
"IRAO",
"FEES",
"PHOR",
"RSTI",
"MAGN",
"SIBN",
"TRNFP",
"SBERP",
"VTBR",
"SNGS",
"GAZP",
"MGNT",
"MTSS",
"TATN",
"MSNG",
"SBER",
"MOEX",
"AFLT",
"MTLR"
}
}
end
-----
function main ()
local tId = AllocTable()
AddColumn(tId, 0, "Ticker", true, QTABLE_STRING_TYPE, 15) -- ticker
AddColumn(tId, 1, "Close", true, QTABLE_DOUBLE_TYPE, 20) -- close
AddColumn(tId, 2, "StopLoss", true, QTABLE_DOUBLE_TYPE, 20) -- recommended stop loss price
AddColumn(tId, 3, "Prev. close", true, QTABLE_DOUBLE_TYPE, 20) -- close on prev. week
AddColumn(tId, 4, "% diff", true, QTABLE_DOUBLE_TYPE, 15) -- % difference
AddColumn(tId, 5, "Rank", true, QTABLE_INT_TYPE, 15) -- rank
AddColumn(tId, 6, "Prev. Rank", true, QTABLE_INT_TYPE, 15) -- previous rank
AddColumn(tId, 7, "Avg. daily vol", true, QTABLE_DOUBLE_TYPE, 20) -- avg. daily vol for 2 weeks
CreateWindow(tId)
local rankedWatchList = RankedWatchList:new(getWatchList(), settings)
rankedWatchList:renderToTable(tId)
end
|
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
EasingUtil = {}
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InQuadratic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.OutQuadratic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InOutQuadratic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InCubic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.OutCubic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InOutCubic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InQuartic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.OutQuartic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InOutQuartic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InQuintic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.OutQuintic(percent) end
---@param percent number Value from 0.0 to 1.0
---@return number
---[FrameXML](https://www.townlong-yak.com/framexml/live/EasingUtil.lua)
function EasingUtil.InOutQuintic(percent) end
|
Config = {}
Config.Locale = 'en'
Config.progressBars = true -- If your server has progressBars and wants to use vs text for mugging time.
Config.MinMoney = 5 -- Min amount of money received from mugging
Config.MaxMoney = 100 -- Max amount of money received from mugging.
Config.RobWaitTime = 5 -- Current seconds it takes to finish mugging
Config.AddItemsPerctent = 40 -- This is percent the script will add items as well as cash from mugging set to 0 to turn off.
Config.AddItemsMax = 3 -- This is the max number of items you can receive from NPC from mugging - min is 1
Config.CoolDownTime = 60 -- This is time between mugging NPC in seconds. Setting to 0 will turn off cooldown.
Config.RequiredPermission = "police.service"
Config.Language = {
RequiredPermission = "Observeret røveri",
CallAlreadyTaken = "Dette opkald er allerede taget af en anden."
}
Config.MustUseVoice = false -- With this on, the player must be speaking in game when trying to much someone or the npc will ignore.
Config.giveableItems = {
'water',
'kokain'
}
|
local fs = require "lemoon.fs"
local sys = require "lemoon.sys"
local class = require "lemoon.class"
local throw = require "lemoon.throw"
local filepath = require "lemoon.filepath"
local logger = class.new("lemoon.log","gsmake")
local langdir = {
golang = ".gsmake/golang/src";
}
task.resources = function(task)
gsrpc = task.Owner.Properties.gsrpc or {}
if gsrpc.name == nil then
gsrpc.name = "github.com/gsrpc/gsrpc"
end
if gsrpc.lang == nil then
gsrpc.lang = "golang"
end
if gsrpc.outputdir == nil then
gsrpc.outputdir = langdir[gsrpc.lang]
if gsrpc.outputdir == nil then
gsrpc.outputdir = ".gsmake/gslang/src"
end
end
defaultversion = task.Owner.Loader.Config.DefaultVersion
if gsrpc.version == nil then
gsrpc.version = defaultversion
end
print(string.format("prepare gsrpc compiler [%s:%s] ...",gsrpc.name,gsrpc.version))
sync = task.Owner.Loader.Sync
local path = sync:sync(gsrpc.name,gsrpc.version)
gsrpcpath = filepath.join(task.Owner.Loader.Temp,"gsrpc")
if not fs.exists(gsrpcpath) then
fs.mkdir(gsrpcpath)
end
local loader = class.new("gsmake.loader",task.Owner.Loader.GSMake,path)
loader:load()
loader:setup()
loader:run("install",gsrpcpath)
end
task.resources.Desc = "prepare gsrpc compiler"
local loadedpackages = {}
local loadstack = {}
local linkdependencies = nil
linkdependencies = function(sync,dependencies)
for _,dep in ipairs(dependencies) do
if not dep.version then dep.version = defaultversion end
if loadedpackages[dep.name] then
if loadedpackages[dep.name].version ~= dep.version then
print(string.format("conflict package(%s) version",dep.name))
print("one :")
for i,stack in ipairs(loadstack) do
print(string.format("%s%s->",string.rep(" ",i),stack.Name))
end
print("two :")
for i,stack in ipairs(loadedpackages[dep.name].stack) do
print(string.format("%s%s->",string.rep(" ",i),stack.Name))
end
return true
end
end
local path = sync:sync(dep.name,dep.version)
local linked = filepath.join(gsrpcpath,"src",dep.name)
if not fs.exists(filepath.dir(linked)) then
fs.mkdir(filepath.dir(linked),true)
end
if fs.exists(linked) then
fs.rm(linked)
end
local package = class.new("gsmake.loader",loader.GSMake,path,dep.name,dep.version).Package
if not package.External then
table.insert(loadstack,package)
local properties = package.Properties.gsrpc or {}
if linkdependencies(package.Loader.Sync,properties.dependencies or {}) then
return true
end
table.remove(loadstack)
end
loadedpackages[dep.name] = { version = dep.version; stack = class.clone(loadstack); }
fs.symlink(path,linked)
end
end
task.precompile = function(task)
table.insert(loadstack,task.Owner)
if linkdependencies(sync,gsrpc.dependencies or {}) then
return true
end
local srcpath = filepath.join(gsrpcpath,"src")
local srcfiles = {}
fs.match(srcpath,"[^.]*%.gs",{".gsmake"},function(path)
path = filepath.toslash(filepath.clean(path))
table.insert(srcfiles,path)
end)
fs.match(task.Owner.Path,"[^.]*%.gs",{".gsmake"},function(path)
path = filepath.toslash(filepath.clean(path))
table.insert(srcfiles,path)
end)
local path = filepath.join(gsrpcpath,"bin/gsrpc" .. sys.EXE_NAME)
local outputdir = filepath.join(task.Owner.Path,gsrpc.outputdir)
local exec = sys.exec(path)
if 0 ~= exec:run("-lang",gsrpc.lang,"-o",outputdir,table.unpack(srcfiles)) then
return true
end
end
task.precompile.Desc = "compile the gsrpc files"
task.precompile.Prev = "resources"
|
local config = require('modutram.config.defaults')
local Grid = require('modutram.grid.Grid')
local SlotConfigRepository = require('modutram.slot.SlotConfigRepository')
local t = require('modutram.types')
local SlotFactory = require('modutram.slot.SlotFactory')
local GridModuleFactory = require('modutram.grid_module.factory')
local Slot = require('modutram.slot.Slot')
local GridSlotBuilder = require('modutram.slot.GridSlotBuilder')
local slotFactory = SlotFactory:new{config = config}
describe('GridSlotBuilder', function ()
describe('placeGridSlots', function ()
it('places all slots at 0/0 when grid is empty', function ()
local grid = Grid:new{config = config}
local slotConfigRepository = SlotConfigRepository.makeWithParams({{
type = t.TRAM_UP,
slotType = 'modutram_austria_tram_up_300cm',
widthInCm = 300,
namespace = 'austria'
}, {
type = t.TRAM_DOWN,
slotType = 'modutram_austria_tram_up_350cm',
widthInCm = 350,
namespace = 'austria'
}})
local gridSlotBuilder = GridSlotBuilder:new{grid = grid, config = config}
local slots = gridSlotBuilder:placeGridSlots(slotConfigRepository)
assert.are.same(slotFactory:makeAnySlot(slotConfigRepository, 0, 0, 0), slots)
end)
it('places slot for a station with one module', function ()
local grid = Grid:new{config = config}
local slotConfigRepository = SlotConfigRepository.makeWithParams({{
type = t.TRAM_UP,
slotType = 'modutram_austria_tram_up_300cm',
widthInCm = 300,
namespace = 'austria'
}})
local slot = Slot:new{id = Slot.makeId({type = t.TRAM_UP}), moduleData = {
metadata = {
modutram_widthInCm = 300
}
}}
local gridModule = GridModuleFactory.make(slot)
grid:set(gridModule)
local expected = {
slotFactory:makeSlotAtGridModule(slotConfigRepository, gridModule),
slotFactory:makeSlotsBelowGridModule(slotConfigRepository, gridModule)[1],
slotFactory:makeSlotsAboveGridModule(slotConfigRepository, gridModule)[1],
slotFactory:makeSlotsLeftFromGridModule(slotConfigRepository, gridModule)[1],
slotFactory:makeSlotsRightFromGridModule(slotConfigRepository, gridModule)[1]
}
local gridSlotBuilder = GridSlotBuilder:new{grid = grid, config = config}
local slots = gridSlotBuilder:placeGridSlots(slotConfigRepository)
assert.are.same(expected, slots)
end)
end)
describe("placeGridSlotsFromColumn",function ()
local slotConfigRepository = SlotConfigRepository.makeWithParams({{
type = t.TRAM_UP,
slotType = 'modutram_austria_tram_up_300cm',
widthInCm = 300,
namespace = 'austria'
}})
local moduleData = {
metadata = {
modutram_widthInCm = 300
}
}
local gridModule1 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = 2, gridY = -2, xPos = 210}),
moduleData = moduleData
})
local gridModule2 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = 2, gridY = 2, xPos = 210}),
moduleData = moduleData
})
local gridModule3 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = 2, gridY = 3, xPos = 210}),
moduleData = moduleData
})
local gridModule4 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = 2, gridY = 5, xPos = 210}),
moduleData = moduleData
})
local grid = Grid:new{config = config}
grid:set(gridModule1)
grid:set(gridModule2)
grid:set(gridModule3)
grid:set(gridModule4)
local column = grid:getColumn(2)
local gridSlotBuilder = GridSlotBuilder:new{grid = grid, config = config}
local expected = {
slotFactory:makeSlotAtGridModule(slotConfigRepository, gridModule1),
slotFactory:makeSlotAtGridModule(slotConfigRepository, gridModule2),
slotFactory:makeSlotAtGridModule(slotConfigRepository, gridModule3),
slotFactory:makeSlotAtGridModule(slotConfigRepository, gridModule4),
slotFactory:makeSlotsBelowGridModule(slotConfigRepository, gridModule1)[1],
slotFactory:makeSlotsAboveGridModule(slotConfigRepository, gridModule1)[1],
slotFactory:makeSlotsBelowGridModule(slotConfigRepository, gridModule2)[1],
slotFactory:makeSlotsAboveGridModule(slotConfigRepository, gridModule3)[1],
slotFactory:makeSlotsAboveGridModule(slotConfigRepository, gridModule4)[1]
}
local result = {}
gridSlotBuilder:placeGridSlotsFromColumn(column, slotConfigRepository, result)
assert.are.same(expected, result)
end)
describe("placeGridSlotsLeftFromColumn", function ()
local slotConfigRepository = SlotConfigRepository.makeWithParams({{
type = t.TRAM_UP,
slotType = 'modutram_austria_tram_up_300cm',
widthInCm = 300,
namespace = 'austria'
}})
local moduleData = {
metadata = {
modutram_widthInCm = 300
}
}
local gridModule1 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = -2, gridY = -2, xPos = 210}),
moduleData = moduleData
})
local gridModule2 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = -2, gridY = 2, xPos = 210}),
moduleData = moduleData
})
local grid = Grid:new{config = config}
grid:set(gridModule1)
grid:set(gridModule2)
local column = grid:getColumn(-2)
local gridSlotBuilder = GridSlotBuilder:new{grid = grid, config = config}
local expected = {}
for _, slot in pairs(slotFactory:makeSlotsLeftFromGridModule(slotConfigRepository, gridModule1)) do
table.insert(expected, slot)
end
for _, slot in pairs(slotFactory:makeSlotsLeftFromGridModule(slotConfigRepository, gridModule2)) do
table.insert(expected, slot)
end
local result = {}
gridSlotBuilder:placeGridSlotsLeftFromColumn(column, slotConfigRepository, result)
assert.are.same(expected, result)
end)
describe("placeGridSlotsRightFromColumn", function ()
local slotConfigRepository = SlotConfigRepository.makeWithParams({{
type = t.TRAM_UP,
slotType = 'modutram_austria_tram_up_300cm',
widthInCm = 300,
namespace = 'austria'
}})
local moduleData = {
metadata = {
modutram_widthInCm = 300
}
}
local gridModule1 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = 2, gridY = -2, xPos = 210}),
moduleData = moduleData
})
local gridModule2 = GridModuleFactory.make(Slot:new{
id = Slot.makeId({type = t.TRAM_UP, gridX = 2, gridY = 2, xPos = 210}),
moduleData = moduleData
})
local grid = Grid:new{config = config}
grid:set(gridModule1)
grid:set(gridModule2)
local column = grid:getColumn(2)
local gridSlotBuilder = GridSlotBuilder:new{grid = grid, config = config}
local expected = {}
for _, slot in pairs(slotFactory:makeSlotsRightFromGridModule(slotConfigRepository, gridModule1)) do
table.insert(expected, slot)
end
for _, slot in pairs(slotFactory:makeSlotsRightFromGridModule(slotConfigRepository, gridModule2)) do
table.insert(expected, slot)
end
local result = {}
gridSlotBuilder:placeGridSlotsRightFromColumn(column, slotConfigRepository, result)
assert.are.same(expected, result)
end)
end)
|
local CONFIG = wmChat.anonyChat.config
GM = GM or GAMEMODE
local onKeyCodeTyped = wmChat.dTextEntry.OnKeyCodeTyped
wmChat.dTextEntry.OnKeyCodeTyped = function(self, code)
if code == KEY_ENTER then
if string.Trim( self:GetText() ) != "" then
RunConsoleCommand("anony_say", self:GetText())
end
wmChat.Close()
return true
end
local boolFromChatHTML = onKeyCodeTyped(self, code)
return boolFromChatHTML
end
local playErrorSound = 0
wmChat.dTextEntry.AllowInput = function(self, char)
local value = self:GetValue()
if #value >= CONFIG.MaxChatLimit then
if playErrorSound < CurTime() then
surface.PlaySound(CONFIG.ErrorSound)
playErrorSound = CONFIG.NextErrorSound + CurTime()
end
return true
end
end
local function getPlyName(ply)
if (IsValid(ply)) then
return ply:GetName()
else
return "Unknown"
end
end
if not GM then
timer.Simple(2, function()
include("anonyChat/cl_chat.lua")
end)
return
end
function GM:OnPlayerChat(ply, strText, bTeamOnly, bPlayerIsDead )
return
end
net.Receive("anonyChatSendMessage", function(len)
local chatObject = chat.GetChat(net.ReadString()) // The chat object
local ply = net.ReadEntity() // The sender
local msg = net.ReadString() // The chat message
local channels = net.ReadUInt(16)
local chats = {}
for i=1, channels do
table.insert(chats, chat.GetChat(net.ReadString()))
end
local args = util.JSONToTable(util.Decompress(net.ReadData(net.ReadUInt(16))))
local tab = {}
if IsValid(ply) and ply:IsPlayer() then
tab = chatObject.messageReceivedByPlayer(chatObject, ply, msg, args, chats)
if hook.Run("OnPlayerChat", ply, msg, false, ply:Alive()) then
return
end
else
tab = chatObject.messageReceived(chatObject, msg, args, chats)
end
chat.AddText(unpack(tab))
end)
|
registerNpc(181, {
walk_speed = 180,
run_speed = 700,
scale = 95,
r_weapon = 0,
l_weapon = 0,
level = 47,
hp = 28,
attack = 232,
hit = 142,
def = 146,
res = 64,
avoid = 48,
attack_spd = 115,
is_magic_damage = 0,
ai_type = 22,
give_exp = 50,
drop_type = 191,
drop_money = 20,
drop_item = 53,
union_number = 53,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 160,
npc_type = 4,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end
|
function onSay(player, words, param)
player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Server Info:"
.. "\nExp rate: " .. Game.getExperienceStage(player:getLevel())
.. "\nSkill rate: " .. configManager.getNumber(configKeys.RATE_SKILL)
.. "\nMagic rate: " .. configManager.getNumber(configKeys.RATE_MAGIC)
.. "\nLoot rate: " .. configManager.getNumber(configKeys.RATE_LOOT))
return false
end
|
function onCreate()
makeLuaSprite('whiteVoid','white',-600,-350)
addLuaSprite('whiteVoid',false)
setLuaSpriteScrollFactor('whiteVoid', 0.95, 0.95);
makeLuaSprite('Pshadows','Pshadow',-500,350)
addLuaSprite('Pshadows',false)
setLuaSpriteScrollFactor('Pshadows', 1, 1);
makeAnimatedLuaSprite('popsies','popsicles',-500,70)
addAnimationByPrefix('popsies','popsicles','popsicles',24,true)
addLuaSprite('popsies',false)
objectPlayAnimation('popsies','popsicles',true)
setLuaSpriteScrollFactor('popsies', 1, 1);
makeLuaSprite('theshadows','shadows',0,650)
addLuaSprite('theshadows',false)
setLuaSpriteScrollFactor('theshadows', 1, 1);
makeLuaSprite('Blue','bluebars',-600,-300)
addLuaSprite('Blue',true)
setLuaSpriteScrollFactor('Blue', 1, 1);
makeAnimatedLuaSprite('vis000000','visualizer',1600,800)
addAnimationByPrefix('vis000000','visualizer','visualizer',24,true)
addLuaSprite('vis000000',true)
objectPlayAnimation('vis000000','visualizer',true)
setLuaSpriteScrollFactor('vis000000', 1, 1);
makeAnimatedLuaSprite('vis00000','visualizer',1300,800)
addAnimationByPrefix('vis00000','visualizer','visualizer',24,true)
addLuaSprite('vis00000',true)
objectPlayAnimation('vis00000','visualizer',true)
setLuaSpriteScrollFactor('vis00000', 1, 1);
makeAnimatedLuaSprite('vis0000','visualizer',1000,800)
addAnimationByPrefix('vis0000','visualizer','visualizer',24,true)
addLuaSprite('vis0000',true)
objectPlayAnimation('vis0000','visualizer',true)
setLuaSpriteScrollFactor('vis0000', 1, 1);
makeAnimatedLuaSprite('vis000','visualizer',700,800)
addAnimationByPrefix('vis000','visualizer','visualizer',24,true)
addLuaSprite('vis000',true)
objectPlayAnimation('vis000','visualizer',true)
setLuaSpriteScrollFactor('vis00', 1, 1);
makeAnimatedLuaSprite('vis00','visualizer',400,800)
addAnimationByPrefix('vis00','visualizer','visualizer',24,true)
addLuaSprite('vis00',true)
objectPlayAnimation('vis00','visualizer',true)
setLuaSpriteScrollFactor('vis00', 1, 1);
makeAnimatedLuaSprite('vis0','visualizer',100,800)
addAnimationByPrefix('vis0','visualizer','visualizer',24,true)
addLuaSprite('vis0',true)
objectPlayAnimation('vis0','visualizer',true)
setLuaSpriteScrollFactor('vis0', 1, 1);
makeAnimatedLuaSprite('vis1','visualizer',-200,800)
addAnimationByPrefix('vis1','visualizer','visualizer',24,true)
addLuaSprite('vis1',true)
objectPlayAnimation('vis1','visualizer',true)
setLuaSpriteScrollFactor('vis1', 1, 1);
makeAnimatedLuaSprite('vis2','visualizer',-500,800)
addAnimationByPrefix('vis2','visualizer','visualizer',24,true)
addLuaSprite('vis2',true)
objectPlayAnimation('vis2','visualizer',true)
setLuaSpriteScrollFactor('vis2', 1, 1);
makeAnimatedLuaSprite('vis3','visualizer',-800,800)
addAnimationByPrefix('vis3','visualizer','visualizer',24,true)
addLuaSprite('vis3',true)
objectPlayAnimation('vis3','visualizer',true)
setLuaSpriteScrollFactor('vis3', 1, 1);
end
function onBeatHit()-- for every beat
-- body
end
function onStepHit()-- for every step
-- body
end
function onUpdate()
-- body
end
|
--@import see.rt.ClassLoader
--@import see.rt.DefaultClassLoader
--@native fs
--@native loadstring
--@extends see.rt.DefaultClassLoader
--[[
Load a class from an archive
@param string the archive bytes
@param string the path of the class
@param string name of the class
]]
function ArchiveClassLoader:loadClass(archiveBytes, path, name)
local loc = archiveBytes:find("F" .. path .. "\0", 1, true)
if not loc then
return nil, "Could not find class " .. name .. " in archive path " .. path .. "."
end
loc = loc + #path + 2
local fin = archiveBytes:find("\0", loc) - 1
local code = archiveBytes:sub(loc, fin)
-- Setup class execution environment
local def, err = loadstring(code, name)
if not def then
return nil, err
end
return self:super(DefaultClassLoader).loadClass(def, ClassLoader.getAnnotations(code), name)
end
|
opt.regimes = {
-- start, end, LR, WD,
{ 1, 13, 3e-3, 5e-3, },
{ 14, 24, 3e-4, 5e-4 },
{ 25, 1e8, 3e-5, 0 },
}
opt.nEpochs = 26
|
if debugScenarios == nil then
---@class debugScenarios
debugScenarios = {}
end
debugScenarios.DebugScenario = {
name = "Basic Debug Scenario",
--forceLaunch = true, -- use this to force the launch of THIS scenario right after main menu was loaded, save more clicks! Don't do multiple scenarii with this options
-- startLoc = {x=13538, y=5759, z=0 }, -- Mall
-- startLoc = {x=10145, y=12763, z=0 }, -- lighting test
-- startLoc = {x=3645, y=8564, z=0 }, -- Roadtrip start
-- startLoc = {x=10645, y=10437, z=0 }, -- Police station
-- startLoc = {x=13926, y=5877, z=0 }, -- Mall bookstore
-- startLoc = {x=10862, y=10290, z=0 }, -- Mul
-- startLoc = {x=10580,y=11193,z=0}, -- car crash
-- startLoc = {x=11515, y=8830, z=0 }, -- DIxie gas station
-- startLoc = {x=10657, y=10625, z=0 }, -- Muldraugh gas station
-- startLoc = {x=5796, y=5384, z=0 }, -- Junkyard
-- startLoc = {x=10835, y=10144, z=0 }, -- middle of muldraugh
-- startLoc = {x=6476, y=5263, z=0 }, -- pharma
-- startLoc = {x=10631, y=9750, z=0 }, -- fossoil
-- startLoc = {x=5438, y=5886, z=0 }, -- gas2go
-- startLoc = {x=10181, y=12783, z=0 }, -- laundromat
-- startLoc = {x=8128, y=11729, z=1 }, -- fire dept lvl 1
startLoc = {x=11778, y=6749, z=0 }, -- other
setSandbox = function()
SandboxVars.VehicleEasyUse = true;
-- SandboxVars.ChanceHasGas = 1;*
-- SandboxVars.InitialGas = 2;
SandboxVars.Zombies = 5;
-- SandboxVars.Distribution = 1;
-- SandboxVars.DayLength = 3;
-- SandboxVars.StartMonth = 12;
-- SandboxVars.WaterShutModifier = -1;
-- SandboxVars.ElecShutModifier = -1;
-- SandboxVars.StartTime = 2;
-- SandboxVars.TimeSinceApo = 7;
-- SandboxVars.CarSpawnRate = 2;
-- SandboxVars.LockedCar = 1;
-- SandboxVars.CarAlarm = 1;
-- SandboxVars.ChanceHasGas = 1;
-- SandboxVars.InitialGas = 2;
-- SandboxVars.CarGeneralCondition = 1;
-- SandboxVars.RecentlySurvivorVehicles = 1;
-- SandboxVars.Zombies = 1;
-- SandboxVars.AllowExteriorGenerator = true;
SandboxVars.FoodLoot = 1;
SandboxVars.WeaponLoot = 1;
SandboxVars.OtherLoot = 1;
-- SandboxVars.Temperature = 3;
-- SandboxVars.Rain = 3;
-- -- SandboxVars.erosion = 12
-- SandboxVars.ErosionSpeed = 1
-- SandboxVars.XpMultiplier = "1.0";
-- SandboxVars.Farming = 3;z
-- SandboxVars.NatureAbundance = 5;
-- SandboxVars.PlantResilience = 3;
-- SandboxVars.PlantAbundance = 3;
-- SandboxVars.Alarm = 3;
-- SandboxVars.LockedHouses = 3;
-- SandboxVars.FoodRotSpeed = 3;
-- SandboxVars.FridgeFactor = 3;
-- SandboxVars.ZombiesRespawn = 2;
-- SandboxVars.LootRespawn = 1;
-- SandboxVars.StatsDecrease = 3;
-- SandboxVars.StarterKit = false;
-- SandboxVars.TimeSinceApo = 13;
--
--
end,
onStart = function()
getPlayer():LevelPerk(Perks.Cooking);getPlayer():LevelPerk(Perks.Cooking);getPlayer():LevelPerk(Perks.Cooking);getPlayer():LevelPerk(Perks.Cooking);getPlayer():LevelPerk(Perks.Cooking);
getPlayer():LevelPerk(Perks.Electricity);
getPlayer():LevelPerk(Perks.Electricity);
getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);
getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);getPlayer():LevelPerk(Perks.Woodwork);
-- getPlayer():getInventory():AddItem("Base.DigitalWatch2")
-- getPlayer():getInventory():AddItem("Base.MushroomGeneric1")getPlayer():getInventory():AddItem("Base.MushroomGeneric1")getPlayer():getInventory():AddItem("Base.MushroomGeneric1")getPlayer():getInventory():AddItem("Base.MushroomGeneric1")
-- getPlayer():getInventory():AddItem("Base.Axe")
-- getPlayer():getInventory():AddItem("Base.BakingTrayBread");
-- getPlayer():getInventory():AddItem("Base.DuctTape");getPlayer():getInventory():AddItem("Base.DuctTape");getPlayer():getInventory():AddItem("Base.DuctTape");getPlayer():getInventory():AddItem("Base.DuctTape")
-- getPlayer():getInventory():AddItem("Base.DeadBird");getPlayer():getInventory():AddItem("Base.DeadBird");getPlayer():getInventory():AddItem("Base.DeadBird");getPlayer():getInventory():AddItem("Base.DeadBird");getPlayer():getInventory():AddItem("Base.DeadBird");getPlayer():getInventory():AddItem("Base.DeadBird");getPlayer():getInventory():AddItem("Base.DeadBird");
-- getPlayer():getInventory():AddItem("Base.Bacon")
-- getPlayer():getInventory():AddItem("Base.KitchenKnife")
-- getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");getPlayer():getInventory():AddItem("Base.Plank");
-- getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");getPlayer():getInventory():AddItem("Base.Nails");
-- getPlayer():getInventory():AddItem("Base.BlowTorch");getPlayer():getInventory():AddItem("Base.WeldingMask");
-- getPlayer():getBodyDamage():getBodyPart(BodyPartType.ForeArm_L):setFractureTime(100);
-- getPlayer():getInventory():AddItem("Base.Trousers");
getPlayer():getInventory():AddItem("Base.SpearKnife");
local d = getPlayer():getInventory():AddItem("Base.BaseballBat");
-- local d = getPlayer():getInventory():AddItem("Base.BaseballBatNails");
-- local d = getPlayer():getInventory():AddItem("Base.ButterKnife");
-- local d = getPlayer():getInventory():AddItem("Base.Crowbar");
-- local d = getPlayer():getInventory():AddItem("Base.Axe");
-- local d = getPlayer():getInventory():AddItem("Base.CraftedFishingRod");
-- local d = getPlayer():getInventory():AddItem("Base.FishingRod");
-- local d = getPlayer():getInventory():AddItem("Base.Fork");
-- local d = getPlayer():getInventory():AddItem("Base.Pan");
local d = getPlayer():getInventory():AddItem("Base.HuntingKnife");
-- local d = getPlayer():getInventory():AddItem("Base.KitchenKnife");
-- local d = getPlayer():getInventory():AddItem("Base.PlankNail");
-- local d = getPlayer():getInventory():AddItem("Base.Plank");
-- local d = getPlayer():getInventory():AddItem("Base.Poolcue");
-- local d = getPlayer():getInventory():AddItem("Base.RollingPin");
-- local d = getPlayer():getInventory():AddItem("Base.Scissors");
-- local d = getPlayer():getInventory():AddItem("Base.Screwdriver");
-- local d = getPlayer():getInventory():AddItem("farming.Shovel");
local d = getPlayer():getInventory():AddItem("Base.Sledgehammer");
local d = getPlayer():getInventory():AddItem("Base.Shotgun");
local d = getPlayer():getInventory():AddItem("Base.Pistol");
-- local d = getPlayer():getInventory():AddItem("Base.Spoon");
-- local d = getPlayer():getInventory():AddItem("Base.AxeStone");
-- local d = getPlayer():getInventory():AddItem("Base.HammerStone");
-- local d = getPlayer():getInventory():AddItem("Base.WoodenLance");
-- local d = getPlayer():getInventory():AddItem("Base.HockeyStick");
-- local d = getPlayer():getInventory():AddItem("Base.Pencil");
-- local d = getPlayer():getInventory():AddItem("Base.Golfclub");
local d = getPlayer():getInventory():AddItem("Base.Hat_GolfHat");
local d = getPlayer():getInventory():AddItem("Base.Hammer");
getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");getPlayer():getInventory():AddItem("Base.ShotgunShells");
-- local d = getPlayer():getInventory():AddItem("Base.Bag_ALICEpack");
-- local d = getPlayer():getInventory():AddItem("Base.KitchenKnife");
-- d:setCondition(0);
-- getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");getPlayer():getInventory():AddItem("Base.WhiskeyFull");
end
}
|
package.cpath = "luaclib/?.so" -- 执行命令的当前目录
-- ./3rd/lua/lua ./learn/testdhexchange.lua
local crypt = require "client.crypt"
-- 如果在skynet中使用直接 local crypt = require "skynet.crypt"
--产生一个8字节的随机数,一般作为对称加密算法的随机密钥
local randkey= crypt.randomkey()
print("crypt.randomkey():\t", crypt.hexencode(randkey))
-- DHexchange密钥交换算法
local clientkey = crypt.randomkey() --8byte random
local ckey = crypt.dhexchange(clientkey) -- dhexchange转换8字节的key
print("clientkey:" , crypt.hexencode(clientkey))
print("ckey:\t" , crypt.hexencode(ckey))
local serverkey = crypt.randomkey()
local skey = crypt.dhexchange(serverkey)
print("serverkey:" , crypt.hexencode(serverkey))
print("skey:\t" , crypt.hexencode(skey))
--通过skey 与 clientkey 得到密钥
local csecret = crypt.dhsecret(skey, clientkey)
print("use skey clientkey dhsecret:", crypt.hexencode(csecret)) --交换成功
local ssecret = crypt.dhsecret(ckey, serverkey)
print("use ckey serverkey dhsecret:", crypt.hexencode(ssecret)) --交换成功
local kksecret = crypt.dhsecret(ckey, skey) --交换失败
print("use ckey skey dhsecret:\t", crypt.hexencode(kksecret))
--HMAC64运算利用哈希算法,以一个密钥secret和一个消息challenge为输入,生成一个消息摘要hmac作为输出。
local challenge = crypt.randomkey()
local chmac = crypt.hmac64(challenge, csecret)
local shmac = crypt.hmac64(challenge, ssecret)
print("chmac.hmac64():\t", crypt.hexencode(chmac))
print("shmac.hmac64():\t", crypt.hexencode(shmac))
local str = "hi~ how are you"
local b64str = crypt.base64encode(str)
print("b64str:\t",b64str)
print("crypt.base64decode(b64str):\t",crypt.base64decode(b64str))
--用key加密plaintext得到密文,key必须是8字节
local plaintext = "base64(user@base64(用户名) server:base64(服务器id) passwd)"
local ciphertext = crypt.desencode(randkey, plaintext)
print("ciphertext:\t",crypt.hexencode(ciphertext))
--用key解密ciphertext得到明文,key必须是8字节
print("DES_decode:\t",crypt.desdecode(randkey, ciphertext))
|
object_static_item_eqp_camping_grill_s1 = object_static_item_shared_eqp_camping_grill_s1:new {
}
ObjectTemplates:addTemplate(object_static_item_eqp_camping_grill_s1, "object/static/item/eqp_camping_grill_s1.iff")
|
Scorpio "KittyBox.Widget.Layout.Demo" ""
import "KittyBox.Layout"
import "KittyBox"
TestLinearLayoutParent = LinearLayout("TestLinearLayoutParent")
TestLinearLayoutParent.Orientation = Orientation.HORIZONTAL
TestLinearLayoutParent:SetPoint("CENTER")
TestLinearLayout = LinearLayout("TestLinearLayout")
TestLinearLayout:SetLayoutParams(LayoutParams(500, 800))
TestLinearLayout.Gravity = Gravity.CENTER_HORIZONTAL + Gravity.CENTER_VERTICAL
TestLinearLayout.Padding = Padding(50, 80, 60, 100)
TestLinearLayout:SetPoint("CENTER")
TestLinearLayoutParent:AddChild(TestLinearLayout)
TestButton = UIPanelButton("TestButton")
TestButton:SetText("测试")
local layoutParams = {
width = SizeMode.WRAP_CONTENT,
height = SizeMode.WRAP_CONTENT,
prefWidth = 100,
prefHeight = 50,
weight = 0.5,
margin = Margin(20, 50)
}
TestLinearLayout:AddChild(TestButton, layoutParams)
TestButton2 = UIPanelButton("TestButton2")
TestButton2:SetText("测试2")
local layoutParams2 = {
width = SizeMode.WRAP_CONTENT,
height = SizeMode.WRAP_CONTENT,
prefWidth = 150,
prefHeight = 200,
weight = 1,
margin = Margin(150, 20)
}
TestLinearLayout:AddChild(TestButton2, layoutParams2)
TestButton3 = UIPanelButton("TestButton3")
TestButton3:SetText("测试3")
local layoutParams3 = {
width = SizeMode.WRAP_CONTENT,
height = SizeMode.WRAP_CONTENT,
prefWidth = 150,
prefHeight = 200,
weight = 1,
margin = Margin(150, 20)
}
TestLinearLayoutParent:AddChild(TestButton3, layoutParams3)
Delay(5, function()
TestLinearLayout.Orientation = Orientation.HORIZONTAL
end)
Delay(10, function()
TestLinearLayout.LayoutDirection = LayoutDirection.RIGHT_TO_LEFT
print(TestLinearLayout:GetEffectiveScale(), TestLinearLayout:GetSize())
end)
Delay(15, function()
TestLinearLayout:SetScale(1.5)
end)
|
--[[
--
-- TODO: We should actually write the tests here, these are just examples.
local Job = require('plenary.job')
describe('Job', function()
it('should_chain_data', function()
local first_job = Job:new(...)
local second_job = Job:new(...)
-- Different options
first_job:chain(second_job)
first_job:and_then(second_job)
first_job:then(second_job)
Job.chain(first_job, second_job)
first_job:after(function() ... end)
-- Different kinds of things
-- 1. Run one job, then run another (only when finished, possibly w/ the results)
-- 2. Run one job, when done, run some synchronous code (just some callback, not necessarily a Job)
-- 3. Pipe stdout of one job, to the next job
-- Example 1:
-- I have a job that searches the file system for X
-- I have another job that determines the git status for X
-- Example 2:
-- I have a job that does some file system stuff
-- I want to prompt the user what to do when it's done
end)
end)
--]]
|
-- Returns a n x m array initialized to v
function new2Darray2v(n,m,v)
grid = {}
for i = 1, n do
grid[i] = {}
for j = 1, m do
grid[i][j] = v -- Fill the values here
end
end
return grid
end
function isNumeric(x)
if tonumber(x) ~= nil then
return true
end
return false
end
function isInt(n)
return n==math.floor(n)
end
-- Returns full latex code to render a table, table columns in latex are equal to amount of elements in first index of array(#array[1])
-- so each element in array is a row in latex
function latexTable(array, caption, label, inject,inject_on, floatPrecision)
--[[
array: 2d array of data
caption: caption at bottom of table
label: latex label of table
inject: string between tabular lines, "\\line" for example
inject_on: list of lines to inject string at the end
- Bound is [2, rows - 1], nil adds inject string to all lines
- Out of bound line numbers are ignored
- The list is sorted automatically
floatPrecision: precision to format float numbers to, ie: 0.8(8 decimal digits)
]]
local res = [[
\begin{table}[htbp]
\begin{center}
\begin{tabular}
]]
for i=1,#array[1] do
if i == 1 then
res = res .. "{r"
elseif i ~= #array[1] then
res = res .. "c"
else
res = res .. "c}"
end
end
res = res .. "\\hline"
res = res .. tableToTeX(array,inject ,inject_on, floatPrecision)
res = res .. string.format([[
\\ \hline
\end{tabular}
\caption{%s}
\label{%s}
\end{center}
\end{table}
]],caption,label)
return res
end
--from "https://gist.github.com/calebreister/8dd7ab503c91dea4dd2c499b9d004231" Edited
function tableToTeX(array, inject, inject_on, floatPrecision)
--[[
array: the 2D array of data
inject: string between tabular lines
inject_on: list of lines to inject string at the end
- Bound is [2, rows - 1], nil adds inject string to all lines
- Out of bound line numbers are ignored
- The list is sorted automatically
For some reason, LuaLaTeX does not like it when I output newlines with
\hlines. The output of this function is a continuous string.
floatPrecision: precision to format float numbers to, ie: 0.8(8 decimal digits)
]]
--Initial conditions
local result = ""
local line = 1 --keeps track of add_to index, not used if inject_on is nil
if inject_on ~= nil then
table.sort(inject_on)
end
--Insert data
for y=1, #array do
if inject ~= nil and y ~= 1 then
if inject_on == nil or inject_on[line] == y then
result = result .. inject .. ' '
line = line + 1
end
end
for x=1, #array[y] do
if (isNumeric(array[y][x]) and not isInt(array[y][x]) ) then
local a = "%"..floatPrecision.."f"
result = result .. string.format(a,array[y][x])
else
result = result .. array[y][x]
end
if x < #array[y] then
result = result .. " & "
end
end
if y < #array then
result = result .. " \\\\ "
end
end
return result
end
-- Returns full latex code to render a bar chart, the array is array[y][x]
-- so there is a plot for each y, of x elements
function latexBarChart(array,caption,label,barWidth,width, height, xmin, xmax, ymin, ymax, floatPrecision, horizontalBars)
--[[
array: 2d array of data
caption: caption at bottom of table
label: latex label of table
inject: string between tabular lines, "\\line" for example
inject_on: list of lines to inject string at the end
- Bound is [2, rows - 1], nil adds inject string to all lines
- Out of bound line numbers are ignored
- The list is sorted automatically
floatPrecision: precision to format float numbers to, ie: 0.8(8 decimal digits)
]]
local typeOfBar
if horizontalBars then
typeOfBar = "xbar"
else
typeOfBar = "ybar"
end
local res = string.format([[
\begin{figure}[htbp]
\centering
\begin{tikzpicture}
\begin{axis} [%s = .05cm,
bar width = %fpt,
width=%fcm,
height=%fcm,
xmin = %f,
xmax = %f,
ymin = %f,
ymax = %f,
enlarge y limits = {abs = .8},
enlarge x limits = {value = .25, upper},
]
]],typeOfBar, barWidth,width, height, xmin, xmax, ymin, ymax)
--Insert data
for y=1, #array do
res = res .. "\\addplot coordinates {"
for x=2, #array[y] do
if (isNumeric(array[y][x]) and not isInt(array[y][x]) ) then
local a = string.format("%"..floatPrecision.."f", array[y][x])
--res = res .. string.format("\\bcbar[text=%s]{%f}", array[1][x], a)
end
if horizontalBars then
res = res .. string.format("(%f,%f)", array[y][x], x-1 )
else
res = res .. string.format("(%f,%f)", x-1, array[y][x] )
end
if x == #array[y] then
--nothing for now
end
end
res = res .. "};"
end
res = res .. "\\legend {"
for y=1,#array do
res = res .. array[y][1]
if y ~= #array then
res = res .. ","
end
end
res = res .. "}"
res = res .. string.format([[\end{axis}
\end{tikzpicture}
\caption{%s} \label{fig:%s}
\end{figure}
]],caption,label)
return res
end
|
--
--
-- performancebrowser.lua
--
--
local bSupportsStats = getPerformanceStats
local DEFAULTCOLUMNSIZE = "180px"
local httpColumns = {}
local httpRows = {}
local updateInterval = 5000
local lastUpdateTime = 0
local queryCatagory = "none"
local queryFilter = ""
local queryOptions = ""
local categoryUpdateTime = {}
-- Browser wants to know what categories to put in the list
function getCategories ()
if not bSupportsStats then return { "not supported" } end
-- Get active catagories
local columnList,rowList = getPerformanceStats("")
local categories = {}
for _,row in ipairs(rowList) do
table.insert( categories, row[1] )
end
return categories
end
-- Browser has changed display request
function setQuery ( catagory, options, filter )
queryCatagory = catagory
queryOptions = options
queryFilter = filter
lastUpdateTime = 0
end
-- Browser wants columns to display
function getHttpColumns( )
if getTickCount() - lastUpdateTime > updateInterval then
lastUpdateTime = getTickCount()
updateCache()
end
return httpColumns
end
-- Browser wants rows to display
function getHttpRows( )
return httpRows
end
-- Update cached table
function updateCache()
if not bSupportsStats then return end
local bClearChange = getTickCount() - (categoryUpdateTime[queryCatagory] or 0) > 60000
categoryUpdateTime[queryCatagory] = getTickCount()
local columnSize = DEFAULTCOLUMNSIZE
-- Fetch table
local columnList,rowList = getPerformanceStats( queryCatagory, queryOptions, queryFilter )
if #columnList == 1 then
columnSize = "500px"
end
-- Process columns
local rowIndices = {}
local newColumns = {}
local prevSectionName = ""
local idx = 1
for k,columnName in pairs(columnList) do
local parts = split ( columnName, string.byte( '.' ) )
if #parts == 2 then
local sectionName = parts[1]
columnName = parts[2]
if sectionName ~= prevSectionName then
prevSectionName = sectionName
table.insert(rowIndices,false)
table.insert(newColumns,{name=" "..sectionName,size=columnSize})
end
end
table.insert(rowIndices,idx)
idx = idx + 1
table.insert(newColumns,{name=columnName,size=columnSize})
end
httpColumns = newColumns
-- Process rows
local newRows = {}
for _, row in ipairs(rowList) do
local rowdata = {}
local style = "main"
if #row > 0 then
if string.find( row[1], '.', 1, true ) ~= nil then
style = "sub"
end
end
table.insert(rowdata,style)
for i, idx in ipairs(rowIndices) do
if idx then
if bClearChange and newColumns[i].name == "change" then
table.insert(rowdata,"")
else
table.insert(rowdata,row[idx])
end
else
table.insert(rowdata,style == "sub" and " + " or " | ")
end
end
table.insert(newRows,rowdata)
end
httpRows = newRows
end
|
boss_cursed_zeld_mind_crack = {}
if IsServer() then
function boss_cursed_zeld_mind_crack:OnSpellStart()
local caster = self:GetCaster()
local health = self:GetSpecialValueFor("clone_health")
local modelScale = self:GetSpecialValueFor("clone_model_scale")
local armor = caster:GetPhysicalArmorBaseValue()
local damageMultiplier = self:GetSpecialValueFor("clone_damage_pct") * 0.01
local damageMin = caster:GetBaseDamageMin() * damageMultiplier
local damageMax = caster:GetBaseDamageMax() * damageMultiplier
for i = 1, self:GetSpecialValueFor("clone_count") do
local clone = CreateUnitByName(caster:GetUnitName(), caster:GetAbsOrigin() + RandomVector(400), true, nil, nil, caster:GetTeamNumber())
clone.isMindCrackClone = true
clone:SetBaseMaxHealth(health)
clone:SetMaxHealth(health)
clone:SetHealth(health)
clone:SetPhysicalArmorBaseValue(armor)
clone:SetBaseDamageMin(damageMin)
clone:SetBaseDamageMax(damageMax)
clone:SetModelScale(modelScale)
clone:SetDeathXP(0)
clone:FindAbilityByName("boss_cursed_zeld_shadows_curse"):SetActivated(false)
clone:FindAbilityByName("boss_cursed_zeld_mind_crack"):SetActivated(false)
Bosses:MakeBossAI(clone, "cursed_zeld", {})
end
end
end
|
--------------------------------------------------------------------------------
-- Game mechanics Settings -----------------------------------------------------
--------------------------------------------------------------------------------
require("config/functions")
behaviors = "/scripts/behaviors/behaviors.lua"
|
local skynet = require "skynet"
require "skynet.manager"
local socket = require "skynet.socket"
local crypt = require "skynet.crypt"
local websocket = require "chestnut.websocket"
local httpd = require "http.httpd"
local urllib = require "http.url"
local sockethelper = require "http.sockethelper"
local log = require "chestnut.skynet.log"
local servicecode = require "chestnut.servicecode"
local verify
local server_list = {}
local user_online = {}
local server_handler = {}
function server_handler.auth_handler(token)
-- the token is base64(user)@base64(server):base64(password)
local user, server, password = token:match("([^@]+)@([^:]+):(.+)")
user = crypt.base64decode(user)
server = crypt.base64decode(server)
password = crypt.base64decode(password)
assert(password == "Password", "Invalid password")
log.info("auth_handler %s@%s:%s", user, server, password)
local res = skynet.call(verify, "lua", "signup", server, user, password)
if res.code == 200 then
return server_handler.login_handler(server, res.uid)
else
log.error("signup server return code is not 200.")
return string.format("%d", res.code)
end
end
function server_handler.login_handler(server, uid, secret)
log.info(string.format("%s@%s is login, secret is", uid, server))
local gameserver = assert(server_list[server], "Unknown server")
-- only one can login, because disallow multilogin
local last = user_online[uid]
if last then
log.info("uid(%d) logined again, will kick last address(%d), begin ---------- ", uid, last.address)
local ok = skynet.call(last.address, "lua", "kick", uid, last.subid)
if not ok then
log.error("kick uid(%d) failture, so you can not login.", uid)
error(string.format("kick uid(%d) failture", uid))
else
log.info("uid(%d) logined again, last address has logout, end ---------- ", uid)
end
end
if user_online[uid] then
error(string.format("user %s is already online", uid))
end
local res = skynet.call(gameserver.address, "lua", "login", uid, "secret")
if res.errorcode == servicecode.SUCCESS then
user_online[uid] = { address = gameserver.address, subid = res.subid , server = server}
local gated = gameserver.gated
local key = string.format("200#%d:%d@%s", uid, res.subid, gated)
return key
elseif res.errorcode == servicecode.LOGIN_AGENT_LOAD_ERR then
log.error("LOGIN_AGENT_LOAD_ERR.")
return string.format("%d", res.errorcode)
else
error("gen subid is wrong")
end
end
local handler = {}
function handler.on_open(ws)
log.info(string.format("%d::open", ws.id))
-- skynet.error("New client from : " .. addr)
end
function handler.on_message(ws, message)
local ok, err = pcall(server_handler.auth_handler, message)
if ok then
ws:send_text(err)
ws:close()
else
log.error(err)
ws:send_text("500")
ws:close()
end
end
function handler.on_close(ws, code, reason)
log.info(string.format("%d close:%s %s", ws.id, code, reason))
end
local function handle_socket(id)
-- limit request body size to 8192 (you can pass nil to unlimit)
local code, url, method, header, body = httpd.read_request(sockethelper.readfunc(id), 8192)
if code then
if header.upgrade == "websocket" then
local ws = websocket.new(id, header, handler)
ws:start()
end
end
end
local CMD = {}
function CMD.register_gate(server, address, gated)
local s = {
address = address,
gated = gated,
}
server_list[server] = s
return true
end
function CMD.logout(uid, subid)
local u = user_online[uid]
if u then
log.info(string.format("%s@%s is logout", uid, u.server))
user_online[uid] = nil
return servicecode.SUCCESS
else
log.error("logined service logout failture, uid: %d, subid: %d", uid, subid)
return servicecode.FAIL
end
end
skynet.register_protocol {
name = "client",
id = skynet.PTYPE_CLIENT,
pack = function(m) return skynet.pack(m) end,
-- unpack = skynet.tostring,
}
skynet.start(function()
local address = skynet.getenv 'wslogind'
skynet.error("Listening "..address)
local id = assert(socket.listen(address))
socket.start(id , function(id, addr)
socket.start(id)
pcall(handle_socket, id)
end)
skynet.dispatch("lua", function ( _, _, cmd, ... )
-- body
local f = assert(CMD[cmd])
local r = f( ... )
if r ~= servicecode.NORET then
if r ~= nil then
skynet.retpack(r)
else
log.error("wslogind cmd = %s not return", cmd)
end
end
end)
verify = skynet.uniqueservice("logindverify")
skynet.register ".wslogind"
end)
|
utils = require('utils')
local noremap = utils.noremap
-- remap the leader key to <Space>
vim.api.nvim_set_keymap('n', '<space>', '', {})
vim.g.mapleader = ' '
-- Disable ex mode
noremap('n', 'Q', '<nop>')
-- Disable undo text in insert mode
noremap('i', '<c-u>', '<nop>')
-- Remove last search highlight
noremap('n', '<leader><esc>', ':nohlsearch<cr>')
-- Close quickfix and remove highlight
noremap('n', '<leader>qx', ':cclose<cr>:noh<cr>')
-- Split line
noremap('n', 'K', 'i<cr><esc>')
-- Remap search next to keep search in the middle of the screen
noremap('n', 'n', 'nzzzv')
noremap('n', 'N', 'Nzzzv')
-- Quicker quit and save mappings
noremap('n', 'QQ', ':q<cr>')
noremap('n', '<leader>w', ':w<cr>')
-- Easy change global with next
noremap('n', 'c*', '*Ncgn')
-- Window resizing
noremap('n', '<leader><up>', ':5wincmd +<cr>')
noremap('n', '<leader><down>', ':5wincmd -<cr>')
noremap('n', '<leader><left>', ':5wincmd <<cr>')
noremap('n', '<leader><right>', ':5wincmd ><cr>')
-- Panes / Tabs
noremap('n', '<leader>-', ':vsplit %:h<cr>')
noremap('n', '<leader>_', ':split %:h<cr>')
noremap('n', '<leader>=', ':tab split %:h<cr>')
-- Delete selected to text to void and paste default register
noremap('v', '<leader>p', '"_dP')
-- Yank to end of line because consistency makes sense
noremap('n', 'Y', 'y$')
-- Substitute current word
noremap('n', '<leader>s', ':s/<c-r><c-w>//g<left><left>')
noremap('n', '<leader>S', ':%s/<c-r><c-w>//g<left><left>')
noremap('x', '<leader>s', ':s///g<left><left><left>')
|
return {
hand_left = {
{ {9, 40}, {11, 36}, {11, 37}, {11, 36}, {0, 0}, {9, 40}, {9, 40}, {10, 40}, {10, 39}, {10, 39}, {0, 40}, {-10, 40}, },
{ {9, 40}, {9, 36}, {9, 37}, {9, 36}, {0, 0}, {9, 40}, {9, 40}, {-10, 40}, {-10, 39}, {-10, 39}, {-2, 40}, {-9, 40}, },
{ {11, 34}, {0, 0}, {0, 0}, {9, 40}, {0, 0}, {-2, 46}, {16, 26}, {12, 42}, {12, 40}, {10, 40}, {9, 40}, {9, 40}, },
{ {9, 34}, {0, 0}, {0, 0}, {9, 40}, {0, 0}, {7, 34}, {14, 26}, {8, 34}, {6, 40}, {16, 34}, {14, 35}, {16, 35}, },
{ {11, 26}, {11, 23}, {11, 24}, {11, 23}, {0, 0}, {11, 21}, {10, 30}, {10, 29}, {10, 29}, {9, 37}, {-1, 45}, {13, 36}, },
{ {10, 26}, {10, 23}, {10, 24}, {10, 23}, {0, 0}, {10, 21}, {-11, 30}, {-11, 29}, {-12, 29}, {12, 37}, {11, 45}, {0, 0}, },
{ {-1, 27}, {-1, 24}, {-1, 25}, {-1, 24}, {0, 0}, {-1, 22}, {-1, 42}, {-1, 38}, {-1, 39}, {-1, 38}, {0, 0}, {-1, 36}, },
{ {13, 27}, {13, 24}, {13, 25}, {13, 24}, {0, 0}, {13, 22}, {13, 42}, {13, 38}, {13, 39}, {13, 38}, {0, 0}, {13, 36}, },
{ {9, 40}, {11, 36}, {11, 37}, {11, 34}, {9, 40}, {11, 36}, {11, 37}, {11, 34}, {9, 40}, {11, 36}, {11, 37}, {11, 34}, },
{ {14, 26}, {14, 24}, {14, 25}, {14, 22}, {14, 42}, {14, 39}, {14, 40}, {14, 38}, {16, 34}, {16, 31}, {16, 32}, {16, 29}, },
{ {6, 30}, {-12, 32}, {5, 32}, {15, 31}, {6, 27}, {5, 30}, {5, 29}, {15, 29}, {6, 25}, {-12, 27}, {5, 27}, {15, 26}, },
{ {16, 34}, {16, 34}, {16, 34}, {16, 34}, {16, 32}, {16, 32}, {16, 32}, {16, 32}, {16, 29}, {16, 29}, {16, 29}, {16, 29}, },
{ {-2, 46}, {-1, 46}, {0, 46}, {-1, 46}, {8, 41}, {9, 42}, {4, 45}, {9, 42}, {9, 36}, {5, 43}, {5, 31}, {0, 0}, },
{ {9, 46}, {10, 46}, {11, 46}, {10, 46}, {-11, 37}, {-12, 33}, {-11, 31}, {-12, 33}, {12, 36}, {12, 45}, {15, 32}, {0, 0}, },
{ {-18, 34}, {-18, 34}, {-18, 34}, {0, 0}, {-12, 36}, {-12, 36}, {-12, 36}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, },
{ {17, 27}, {17, 27}, {17, 27}, {0, 0}, {10, 34}, {10, 34}, {10, 34}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, },
},
hand_right = {
{ {-10, 40}, {-10, 36}, {-10, 37}, {-10, 36}, {0, 0}, {-10, 40}, {-10, 40}, {-10, 40}, {-10, 39}, {-10, 39}, {-1, 40}, {8, 40}, },
{ {-10, 40}, {-12, 36}, {-12, 37}, {-12, 36}, {0, 0}, {-10, 40}, {-10, 40}, {10, 40}, {10, 39}, {10, 39}, {-1, 40}, {9, 40}, },
{ {-10, 34}, {0, 0}, {0, 0}, {-10, 40}, {0, 0}, {-8, 34}, {-15, 26}, {-9, 34}, {-7, 40}, {-17, 34}, {-15, 35}, {-17, 35}, },
{ {-12, 34}, {0, 0}, {0, 0}, {-10, 40}, {0, 0}, {1, 45}, {-17, 26}, {-12, 42}, {-13, 40}, {-11, 40}, {-10, 40}, {-10, 40}, },
{ {-11, 26}, {-11, 23}, {-11, 24}, {-11, 23}, {0, 0}, {-11, 21}, {-10, 30}, {-10, 29}, {-10, 29}, {-12, 37}, {-12, 45}, {-15, 36}, },
{ {-12, 26}, {-12, 23}, {-12, 24}, {-12, 23}, {0, 0}, {-12, 21}, {11, 30}, {11, 29}, {10, 29}, {-10, 37}, {0, 45}, {0, 0}, },
{ {-14, 27}, {-14, 24}, {-14, 25}, {-14, 24}, {0, 0}, {-14, 22}, {-14, 42}, {-14, 38}, {-14, 39}, {-14, 38}, {0, 0}, {-14, 36}, },
{ {0, 27}, {0, 24}, {0, 25}, {0, 24}, {0, 0}, {0, 22}, {0, 42}, {0, 38}, {0, 39}, {0, 38}, {0, 0}, {0, 36}, },
{ {-15, 26}, {-15, 24}, {-15, 25}, {-15, 22}, {-15, 42}, {-15, 39}, {-15, 40}, {-15, 38}, {-17, 34}, {-17, 31}, {-17, 32}, {-17, 29}, },
{ {-10, 40}, {-12, 36}, {-12, 37}, {-12, 34}, {-10, 40}, {-12, 36}, {-12, 37}, {-12, 34}, {-10, 40}, {-12, 36}, {-12, 37}, {-12, 34}, },
{ {-17, 34}, {-17, 34}, {-17, 34}, {-17, 34}, {-17, 32}, {-17, 32}, {-17, 32}, {-17, 32}, {-17, 29}, {-17, 29}, {-17, 29}, {-17, 29}, },
{ {-7, 30}, {11, 32}, {-6, 32}, {-16, 31}, {-7, 27}, {11, 30}, {-6, 29}, {-16, 29}, {-7, 25}, {11, 27}, {-6, 27}, {-16, 26}, },
{ {-10, 46}, {-11, 46}, {-12, 46}, {-11, 46}, {-5, 45}, {-10, 42}, {-9, 41}, {-9, 42}, {-13, 36}, {-13, 45}, {-16, 32}, {0, 0}, },
{ {1, 46}, {0, 46}, {-1, 46}, {0, 46}, {10, 31}, {10, 33}, {10, 37}, {10, 33}, {-10, 36}, {-5, 44}, {-5, 31}, {0, 0}, },
{ {-18, 27}, {-18, 27}, {-18, 27}, {0, 0}, {-11, 34}, {-11, 34}, {-11, 34}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, },
{ {17, 34}, {17, 34}, {17, 34}, {0, 0}, {11, 36}, {11, 36}, {11, 36}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, {0, 0}, },
},
}
|
local sieve = require('sieve')
describe('sieve', function()
local select = select or function(n, ...)
return table.pack(...)[n]
end
local function primes_from(co)
local primes = {}
while true do
local _, prime = coroutine.resume(co)
if prime == nil then return primes end
table.insert(primes, prime)
end
end
it('should return a coroutine that generates primes', function()
local co = sieve(9)
assert.equal(2, select(2, coroutine.resume(co)))
assert.equal(3, select(2, coroutine.resume(co)))
assert.equal(5, select(2, coroutine.resume(co)))
assert.equal(7, select(2, coroutine.resume(co)))
assert.is_nil(select(2, coroutine.resume(co)))
end)
it('should find primes up to 10', function()
assert.same({ 2, 3, 5, 7 }, primes_from(sieve(10)))
end)
it('should find primes up to 1000', function()
assert.same(
{ 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 },
primes_from(sieve(1000))
)
end)
it('should include the limit if it is prime', function()
assert.same({ 2, 3, 5, 7, 11, 13 }, primes_from(sieve(13)))
end)
it('should find the first prime', function()
assert.same({ 2 }, primes_from(sieve(2)))
end)
it('should not find any primes under 2', function()
assert.same({}, primes_from(sieve(1)))
end)
end)
|
--[[
OpenAPI Petstore
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
]]
-- inline_object class
local inline_object = {}
local inline_object_mt = {
__name = "inline_object";
__index = inline_object;
}
local function cast_inline_object(t)
return setmetatable(t, inline_object_mt)
end
local function new_inline_object(name, status)
return cast_inline_object({
["name"] = name;
["status"] = status;
})
end
return {
cast = cast_inline_object;
new = new_inline_object;
}
|
--Created by mpk5lmao Magice gun --
local enabled = true
Player = script.Parent.Parent
c = Player.Character
game:GetService("Chat"):Chat(Player.Character.Head, "Magic Gun Hurrra!!!!!!!!!")
--Player:WaitForDataReady()
mouse = Player:GetMouse()
run = game:GetService("RunService")
function onKeyDown(key)
if not enabled then return end
enabled = true
Key = key:lower()
if key == "e" then
RightShoulder = Player.Character.Torso["Right Shoulder"]
LeftShoulder = Player.Character.Torso["Left Shoulder"]
Run = game:GetService("RunService")
local pow = Instance.new("Sound")
pow.SoundId = ("http://www.roblox.com/asset/?id=2691586")
pow.Volume = 1
pow.Parent = game.Workspace
x = Instance.new("Part")
x.BrickColor = BrickColor.new("Cool yellow")
x.Size = Vector3.new(1, 1, 2)
x.TopSurface = "Smooth"
x.BottomSurface = "Smooth"
x.Shape = "Ball"
x.Name = Player.Name
x.CanCollide = false
x.Transparency = 0
t = Instance.new("SpecialMesh")
t.MeshId = "http://www.roblox.com/asset/?id=2697549"
t.TextureId = ""
t.MeshType = "FileMesh"
t.Scale = Vector3.new(1.7, 1.7, 1.7)
t.Parent = x
w = Instance.new ("Part")
w.Size = Vector3.new (1, 1, 1)
w.TopSurface = "Smooth"
w.BottomSurface = "Smooth"
w.BrickColor = BrickColor.new("Mid gray")
w.Reflectance = 0.3
w.Material = "Ice"
w.CanCollide = false
w.Transparency = 0
w.Parent = c
w.Name = "LeftS"
q = Instance.new("SpecialMesh")
q.MeshId = "http://www.roblox.com/asset/?id=4372594"
q.TextureId = ""
q.MeshType = "FileMesh"
q.Scale = Vector3.new(1.7, 1.7, 1.7)
q.Parent = w
function onTouched(hit)
local human = hit.Parent:findFirstChild("Humanoid")
local fon = hit.Parent
if (human ~= nil) then
game:GetService("Chat"):Chat(Player.Character.Head, "Hit")
human.Health = human.Health - 15 -- Change the amount to change the damage.
-- human.Torso
end
end
x.Touched:connect(onTouched)
--function a(part)
--local a = part.Parent:FindFirstChild("Humanoid")
--if (a ~= nil) then
--a.Parent:Remove()
--end
--end
--x.Touched:connect(a)
--fd = script.Firedamage:clone()
--fd.Parent = x
y = Instance.new("BodyVelocity")
y.maxForce = Vector3.new(math.huge, math.huge, math.huge)
y.velocity = Player.Character.Torso.CFrame.lookVector*600
x.Parent = Workspace
y.Parent = x
pow:Play()
w1 = Instance.new ("Weld", c)
w1.Part0 = w1.Parent["Left Arm"]
print 'Its on my arm'
w1.Part1 = w
w1.C1 = CFrame.fromEulerAnglesXYZ (1.5, 0, 0) *CFrame.new (0, 1.5, 0)
x.CFrame = Player.Character.Torso.CFrame*CFrame.new(0, 0, -5)
--fd.Disabled = false
game.Debris:AddItem(x, 6)
game.Debris:AddItem(pow, 2)
wait(0.25)
end
wait(.001)
enabled = true
end
script.Parent.Parent.Character.Humanoid.MaxHealth = 450
script.Parent.Parent.Character.Humanoid.Health = 400
LeftShoulder = Player.Character.Torso["Left Shoulder"]
for i = .5, 1 do
LeftShoulder.C0 = LeftShoulder.C0 *CFrame.Angles(0, 0, -1.5)
end
mouse.KeyDown:connect(onKeyDown)
|
--[[
Rematch refers to pets as a single number or string, depending on their
context. This reference, called a petID, can be one of seven idTypes:
idType example petID value description
---------- --------------------- -----------------------------------
"pet" "Battle-0-0000000etc" a player-owned pet in the journal
"species" 42 speciesID species number
"leveling" 0 leveling slot
"ignored" "ignored" ignored slot
"link" "battlepet:42:25:etc" linked pet
"battle" "battle:2:1" pet in battle (battle:owner:index)
"random" "random:10" random mechanical pet (random:0 for any pet type)
"unknown" (anything, even nil) indecipherable/undefined pet
To simplify getting information about these different types of pets, to
eliminate the scattered code to independently call the various API through
C_PetJournal and C_PetBattles, and to reduce redundant API calls for
information already retrieved (or information not used!), this module
encapsulates a "front end" for information about pets.
To use, first create a petInfo instance:
local petInfo = rematch:CreatePetInfo()
Then fetch a petID to make it the pet of interest:
petInfo:Fetch(petID)
After a pet of interest is fetched, simply index the stat you want:
print(petInfo.name,"is level",petInfo.level,"and breed",petInfo.breedName)
The stat can be any of these:
petID: this is the pet reference Fetched (string, number, link, etc)
idType: "pet" "species" "leveling" "ignored" "link" "battle" "random" or "unknown" (string)
speciesID: numeric speciesID of the pet (integer)
customName: user-renamed pet name (string)
speciesName: name of the species (string)
name: customName if defined, speciesName otherwise (string)
level: whole level 1-25 (integer)
xp: amount of xp in current level (integer)
maxXp: total xp to reach next level (integer)
fullLevel: level+xp/maxXp (float)
displayID: id of the pet's skin (integer)
isFavorite: whether pet is favorited (bool)
icon: fileID of pet's icon or specific filename (integer or string)
petType: numeric type of pet 1-10 (integer)
creatureID: npcID of summoned pet (integer)
sourceText: formatted text about where pet is from (string)
loreText: "back of the card" lore (string)
isWild: whether the pet is found in the wild (bool)
canBattle: whether pet can battle (bool)
isTradable: whether pet can be caged (bool)
isUnique: whether only one of pet can be learned (bool)
isObtainable: whether this pet is in the journal (bool)
health: current health of the pet (integer)
maxHealth: maximum health of the pet (integer)
power: power stat of the pet (integer)
speed: speed stat of the pet (integer)
rarity: rarity 1-4 of pet (integer)
isDead: whether the pet is dead (bool)
isInjured: whether the pet has less than max health (bool)
isSummonable: whether the pet can be summoned (bool)
isRevoked: whether the pet is revoked (bool)
abilityList: table of pet's abilities (table)
levelList: table of pet's ability levels (table)
valid: whether the petID is valid and petID is not missing (bool)
owned: whether the petID is a valid pet owned by the player (bool)
count: number of pet the player owns (integer)
maxCount: maximum number of this pet the player can own (integer)
hasBreed: whether pet can battle and there's a breed source (bool)
breedID: 3-12 for known breeds, 0 for unknown breed, nil for n/a (integer)
breedName: text version of breed like P/P or S/B (string)
possibleBreedIDs: list of breedIDs possible for the pet's species (table)
possibleBreedNames: list of breedNames possible for the pet's species (table)
numPossibleBreeds: number of known breeds for the pet (integer)
needsFanfare: whether a pet is wrapped (bool)
battleOwner: whether ally(1) or enemy(2) pet in battle (integer)
battleIndex: 1-3 index of pet in battle (integer)
isSlotted: whether pet is slotted (bool)
inTeams: whether pet is in any teams (pet and species idTypes only) (bool)
numTeams: number of teams the pet belongs to (pet and species only) (integer)
sourceID: the source index (1=Drop, 2=Quest, 3=Vendor, etc) of the pet (integer)
moveset: the exact moveset of the pet ("123,456,etc") (string)
speciesAt25: whether the pet has a version at level 25 (bool)
hasNotes: whether the pet has notes
notes: the text of the pet's notes
isLeveling: whether the pet is in the queue
isSummoned: whether the pet is currently summoned (companion pet)
How it works:
petInfo:Fetch(petID) will check if the petID is different from the last-
fetched pet. If so, it will wipe the existing information and store the
petID and idType within the table, ready for stats to be queried/indexed.
The created petInfo table has a __index metamethod to look up indexes
that don't exist.
If a petInfo[stat] has no value, the __index metamethod will call the
appropriate API (depending on the idType of the pet) and fill in its
value. Future references to petInfo[stat] will have a value and not
invoke a __index.
Also:
rematch.petInfo and rematch.altInfo are defined at the end of this file
for use throughout the addon.
The script filter system has its own petInfo that's already fetched for each
pet. Script filters do not need to fetch a the current pet.
petInfo:Reset() will force a wipe of information.
When the petID is guaranteed to be from the journal (either a valid,
owned petID string or speciesID), Fetch(petID,true) will skip the
test of its type to improve performance.
link format:
"battlepet:<speciesID>:<level>:<rarity>:<health>:<power>:<speed>"
]]
local _,L = ...
local rematch = Rematch
local GetPetInfoByPetID = C_PetJournal.GetPetInfoByPetID
local GetPetInfoBySpeciesID = C_PetJournal.GetPetInfoBySpeciesID
-- every petInfo key added needs to be added here; key="Group", where Group is a key in queryAPI
local apiByStat = {
speciesID="Info", customName="Info", level="Info", xp="Info", maxXp="Info",
displayID="Info", isFavorite="Info", speciesName="Info", name="Info", icon="Info",
petType="Info", creatureID="Info", sourceText="Info", loreText="Info", isWild="Info",
canBattle="Info", isTradable="Info", isUnique="Info", isObtainable="Info", health="Stats",
maxHealth="Stats", power="Stats", speed="Stats", rarity="Stats", isDead="Dead", isInjured="Dead",
isSummonable="Other", isRevoked="Other", abilityList="Abilities", levelList="Abilities",
valid="Valid", count="Count", maxCount="Count", fullLevel="FullLevel", needsFanfare="Fanfare",
breedID="Breed", breedName="Breed", possibleBreedIDs="PossibleBreeds",
possibleBreedNames="PossibleBreeds", numPossibleBreeds="PossibleBreeds", hasBreed="Breed",
owned="Valid", battleOwner="Battle", battleIndex="Battle", isSlotted="Slotted",
inTeams="Teams", numTeams="Teams", sourceID="Source", moveset="Moveset", speciesAt25="SpeciesAt25",
notes="Notes", hasNotes="Notes", isLeveling="IsLeveling", isSummoned="IsSummoned",
}
-- indexed by petInfo table reference, this will contain reused tables like fetchedAPI
-- and abilityList to prevent garbage creation
local hiddenTables = {}
-- for Breed stat group
local breedSource -- addon that's providing breed data: "BattlePetBreedID", "PetTracker_Breeds" or "LibPetBreedInfo-1.0"
local breedLib -- for LibPetBreedInfo-1.0 only
local breedNames = {nil,nil,"B/B","P/P","S/S","H/H","H/P","P/S","H/S","P/B","S/B","H/B"}
-- getIDType takes a petID and returns what type of id it is
-- possible: "pet" "species" "leveling" "ignored" "link" "battle" "random" or "unknown"
local function getIDType(id)
local idType = type(id)
if idType=="string" then
if id:match("^BattlePet%-%x%-%x%x%x%x%x%x%x%x%x%x%x%x$") then
return "pet"
elseif id:match("battlepet:%d+:%d+:%d+:%d+:%d+:%d+") then
return "link"
elseif id:match("battle:%d:%d") then
return "battle"
elseif id:match("random:%d+") then
return "random"
elseif id=="ignored" then
return "ignored"
end
elseif idType=="number" then
if id>0 then
return "species"
elseif id==0 then
return "leveling"
end
end
return "unknown" -- if we reached here, no idea what this petID is!
end
-- used in Info functions to gather info by petID (BattlePet-0-000etc)
local function fillInfoByPetID(self,petID)
local customName, speciesName -- prevent a __index lookup if petID is invalid or not renamed
self.speciesID,customName,self.level,self.xp,self.maxXp,self.displayID,
self.isFavorite,speciesName,self.icon,self.petType,self.creatureID,
self.sourceText,self.loreText,self.isWild,self.canBattle,self.isTradable,
self.isUnique,self.isObtainable = GetPetInfoByPetID(petID)
self.name = customName or speciesName
self.customName = customName
self.speciesName = speciesName
end
-- used in Info functions to gather info by speciesID (42)
local function fillInfoBySpeciesID(self,speciesID)
local speciesName -- prevent a __index lookup if speciesID is invalid
speciesName,self.icon,self.petType,self.creatureID,self.sourceText,
self.loreText,self.isWild,self.canBattle,self.isTradable,self.isUnique,
self.isObtainable,self.displayID = GetPetInfoBySpeciesID(speciesID)
self.speciesName = speciesName
self.name = speciesName
self.speciesID = speciesID
end
-- indexed by API group ("Info", "Stats", etc) these are the functions that are called
-- if fetchedAPI[key] is nil; they fill petInfo with values depending on the pet idType
local queryAPIs = {
Info = function(self)
-- the majority of info is behind GetPetInfoByPetID and GetPetInfoBySpeciesID
local idType = self.idType
if idType=="pet" then
fillInfoByPetID(self,self.petID)
elseif idType=="species" then
fillInfoBySpeciesID(self,self.petID)
elseif idType=="leveling" then
self.name = L["Leveling Pet"]
self.icon = "Interface\\AddOns\\Rematch\\Textures\\LevelingIcon.blp"
elseif idType=="ignored" then
self.name = L["Ignored Pet"]
self.icon = "Interface\\AddOns\\Rematch\\Textures\\IgnoredIcon.blp"
elseif idType=="link" then
local speciesID,level = self.petID:match("battlepet:(%d+):(%d+):")
speciesID = tonumber(speciesID)
if speciesID then
fillInfoBySpeciesID(self,speciesID)
self.level = tonumber(level)
end
elseif idType=="battle" then
local owner = self.battleOwner
local index = self.battleIndex
if owner==1 then -- for ally battle pets, just use the loaded pet
local petID = C_PetJournal.GetPetLoadOutInfo(index)
if petID then
fillInfoByPetID(self,petID)
end
elseif owner==2 then
local speciesID = C_PetBattles.GetPetSpeciesID(owner,index)
if speciesID then
fillInfoBySpeciesID(self,speciesID)
self.level = C_PetBattles.GetLevel(owner,index)
self.displayID = C_PetBattles.GetDisplayID(owner,index)
end
end
elseif idType=="random" then
-- petType always defined as 0-10 for random pets
local petType = math.min(10,math.max(0,tonumber(self.petID:match("random:(%d+)")) or 0))
self.petType = petType
-- name is "Random Pet" or "Random Humanoid", "Random Dragonkin", etc
local suffix = PET_TYPE_SUFFIX[petType]
self.name = suffix and format(L["Random %s"],_G["BATTLE_PET_NAME_"..petType]) or L["Random Pet"]
self.icon = suffix and format("Interface\\Icons\\Icon_PetFamily_%s",suffix) or "Interface\\Icons\\INV_Misc_Dice_02"
else
self.name = L["Unknown"]
self.icon = "Interface\\Icons\\INV_Misc_QuestionMark"
end
end,
-- only owned pets, linked pets and battle pets have real stats
Stats = function(self)
local idType = self.idType
if idType=="pet" then
self.health,self.maxHealth,self.power,self.speed,self.rarity = C_PetJournal.GetPetStats(self.petID)
elseif idType=="link" then
local rarity,health,power,speed = self.petID:match("battlepet:%d+:%d+:(%d+):(%d+):(%d+):(%d+)")
if rarity then
self.rarity = tonumber(rarity)+1 -- links are 0-3 rarity intead of 1-4
self.health = tonumber(health)
self.maxHealth = tonumber(health)
self.power = tonumber(power)
self.speed = tonumber(speed)
end
elseif idType=="battle" then -- pets in a battle fetch live stats (but note values cache!)
local owner = self.battleOwner
local index = self.battleIndex
if C_PetBattles.GetPetSpeciesID(owner,index) then
self.rarity = C_PetBattles.GetBreedQuality(owner,index)
self.health = C_PetBattles.GetHealth(owner,index)
self.maxHealth = C_PetBattles.GetMaxHealth(owner,index)
self.power = C_PetBattles.GetPower(owner,index)
self.speed = C_PetBattles.GetSpeed(owner,index)
end
end
end,
-- intended to be functions that are only called for journal listing; may separate these later
Other = function(self)
if self.idType=="pet" then
local petID = self.petID
self.isSummonable = C_PetJournal.PetIsSummonable(petID)
self.isRevoked = C_PetJournal.PetIsRevoked(petID)
end
end,
-- fills petInfo.abilityList and .levelList
Abilities = function(self)
if self.speciesID then
local abilityList = hiddenTables[self].abilityList
local levelList = hiddenTables[self].levelList
C_PetJournal.GetPetAbilityList(self.speciesID,abilityList,levelList)
self.abilityList = abilityList
self.levelList = levelList
end
end,
-- petInfo.valid verifies the pet contains information (not a reassigned petID or bad speciesID)
Valid = function(self)
local idType = self.idType
if idType=="pet" and self.speciesID then -- if speciesID read ok then "pet" petID is functional
self.valid = true
self.owned = true -- owned is only true if regular petID is valid
elseif (idType=="species" and self.name) or (idType=="leveling" or idType=="ignored" or idType=="random") or (idType=="link" and self.name) or (idType=="battle" and self.name) then
self.valid = true
self.owned = false
else
self.valid = false
end
end,
-- fills petInfo.count and petInfo.maxCount with the number of a species the player owns
Count = function(self)
if self.speciesID then
self.count,self.maxCount = C_PetJournal.GetNumCollectedInfo(self.speciesID)
end
end,
-- the regular level is an Info function (which this will use if .level not defined)
FullLevel = function(self)
local xp = self.xp
if xp then
self.fullLevel = self.level + (xp/self.maxXp)
else
self.fullLevel = self.level
end
end,
-- whether a pet is wrapped
Fanfare = function(self)
self.needsFanfare = self.idType=="pet" and C_PetJournal.PetNeedsFanfare(self.petID)
end,
-- whether a pet isDead
Dead = function(self)
if self.maxHealth and self.maxHealth > 0 then
self.isDead = self.health==0
self.isInjured = self.health<self.maxHealth
end
end,
-- this fills petInfo.breedID and petInfo.breedName depending on which breed addon is enabled, if any
Breed = function(self)
local source = rematch:GetBreedSource()
local idType = self.idType
if source and self.valid and self.canBattle and (idType=="pet" or idType=="link" or idType=="battle") then
local breedID, breedName
if source=="BattlePetBreedID" then
if idType=="pet" or idType=="link" then
breedID = BPBID_Internal.CalculateBreedID(self.speciesID,self.rarity,self.level,self.maxHealth,self.power,self.speed,false,false)
elseif idType=="battle" then
breedID = BPBID_Internal.breedCache[self.battleIndex + (self.battleOwner==2 and 3 or 0)]
end
elseif source=="PetTracker_Breeds" then
if idType=="pet" then
breedID = PetTracker.Journal:GetBreed(self.petID)
elseif idType=="link" then
breedID = PetTracker.Predict:Breed(self.speciesID,self.level,self.rarity,self.maxHealth,self.power,self.speed)
elseif idType=="battle" then
breedID = PetTracker.Battle:Get(self.battleOwner,self.battleIndex):GetBreed()
end
if breedID then
breedName = PetTracker:GetBreedIcon(breedID,.85) -- using PetTracker's breed icon
end
elseif source=="LibPetBreedInfo-1.0" then
if idType=="pet" then
breedID = breedLib:GetBreedByPetID(self.petID)
elseif idType=="link" then
breedID = breedLib:GetBreedByStats(self.speciesID,self.level,self.rarity,self.maxHealth,self.power,self.speed)
elseif idType=="battle" then
breedID = breedLib:GetBreedByPetBattleSlot(self.battleOwner,self.battleIndex)
end
end
-- make unknown breeds breedID 0 and named "NEW" if no known breeds or "???" otherwise
if type(breedID)~="number" then
breedID = 0
breedName = self.numPossibleBreeds==0 and "NEW" or "???"
end
self.breedID = breedID
self.breedName = breedName or breedNames[breedID]
self.hasBreed = true
else
self.hasBreed = false
end
end,
-- for possibleBreedIDs and possibleBreedNames, only need a speciesID (and a breed source)
PossibleBreeds = function(self)
wipe(hiddenTables[self].possibleBreedIDs)
wipe(hiddenTables[self].possibleBreedNames)
local possibleBreedIDs = hiddenTables[self].possibleBreedIDs
local possibleBreedNames = hiddenTables[self].possibleBreedNames
local source = rematch:GetBreedSource()
local speciesID = self.speciesID
if source and type(speciesID)=="number" and self.canBattle then
local data -- the table that contains possible breeds
if source=="BattlePetBreedID" then
if not BPBID_Arrays.BreedsPerSpecies then
BPBID_Arrays.InitializeArrays()
end
data = BPBID_Arrays.BreedsPerSpecies[speciesID]
elseif source=="PetTracker_Breeds" then
data = PetTracker.Breeds[speciesID]
elseif source=="LibPetBreedInfo-1.0" then
data = breedLib:GetAvailableBreeds(speciesID)
end
-- if there's a table of breeds, copy them to possibleBreeds
if data then
for _,breed in ipairs(data) do
tinsert(possibleBreedIDs,breed)
if source=="PetTracker_Breeds" then
tinsert(possibleBreedNames,PetTracker:GetBreedIcon(breed,0.85))
else
tinsert(possibleBreedNames,breedNames[breed])
end
end
end
self.possibleBreedIDs = possibleBreedIDs
self.possibleBreedNames = possibleBreedNames
self.numPossibleBreeds = #possibleBreedIDs
end
end,
-- pulls battleOwner and battleIndex from the "battle" petID
Battle = function(self)
if self.idType=="battle" then
local owner,index = self.petID:match("battle:(%d):(%d)")
self.battleOwner = tonumber(owner)
self.battleIndex = tonumber(index)
end
end,
-- whether the pet is slotted
Slotted = function(self)
local idType = self.idType
self.isSlotted = (idType=="pet" and C_PetJournal.PetIsSlotted(self.petID)) or (idType=="battle" and self.battleOwner==1)
end,
-- pulls the number of teams the pet of interest belongs to
Teams = function(self)
-- defining the actual stats inTeams and numTeams
local idType = self.idType
if idType=="pet" or idType=="species" then
local numTeams = rematch.petsInTeams[self.petID] or 0
self.inTeams = numTeams>0
self.numTeams = numTeams
end
end,
-- sourceID is source pet filter category (1=Drop, 2=Vendor, 3=Quest, etc)
Source = function(self)
self.sourceID = rematch.sourceIDs[self.speciesID]
end,
-- moveset is the list of abilityIDs separated by commas like "429,492,538,535,357,536" for a black tabby cat
Moveset = function(self)
self.moveset = rematch.movesetsBySpecies[self.speciesID]
end,
SpeciesAt25 = function(self)
self.speciesAt25 = rematch.speciesAt25[self.speciesID] and true
end,
Notes = function(self)
local speciesID = self.speciesID
self.notes = RematchSettings.PetNotes[speciesID]
if self.notes then
self.hasNotes = true
end
end,
IsLeveling = function(self)
self.isLeveling = self.owned and rematch:IsPetLeveling(self.petID)
end,
IsSummoned = function(self)
self.isSummoned = C_PetJournal.GetSummonedPetGUID() == self.petID
end,
}
-- rematch:GetBreedSource() is used by the Breed and PossibleBreeds API
-- the first time this runs it looks for a breed addon enabled and returns it
-- future runs will just return the saved source (so this only looks for a breed addon once)
-- addons are used in this priority: BattlePetBreedID, PetTracker_Breeds then LibPetBreedInfo-1.0
function rematch:GetBreedSource()
if breedSource==nil then
for _,addon in pairs({"BattlePetBreedID","PetTracker_Breeds"}) do
if IsAddOnLoaded(addon) then
if addon~="PetTracker_Breeds" or GetAddOnMetadata("PetTracker_Breeds","Version")~="7.1.4" then
breedSource = addon
return addon
end
end
end
-- one of the sources is not loaded, try loading LibPetBreedInfo separately
LoadAddOn("LibPetBreedInfo-1.0")
if LibStub then
for lib in LibStub:IterateLibraries() do
if lib=="LibPetBreedInfo-1.0" then
breedLib = LibStub("LibPetBreedInfo-1.0")
if lib then
breedSource = lib
return lib
end
end
end
end
breedSource = false -- none found, only attempt to find a source once
end
return breedSource
end
-- returns the name of a breed by its ID (used by PetMenus' breed menu; not petInfo)
function rematch:GetBreedNameByID(breedID)
if rematch:GetBreedSource()=="PetTracker_Breeds" then
return PetTracker:GetBreedIcon(breedID,.85)
else
return breedNames[breedID]
end
end
local reset -- function used in fetch and petInfo, definining it after fetch
-- makes a petID the "pet of interest" to a petInfo(self)
-- if journal is true, the petID is guaranteed to be a valid owned petID or a valid speciesID
local function fetch(self,petID,journal)
if petID~=self.petID then
reset(self)
self.petID = petID
if journal then
self.idType = type(petID)=="string" and "pet" or "species"
else
self.idType = getIDType(petID)
end
end
return self
end
-- wipes a petInfo(self) for new data
function reset(self)
wipe(self)
wipe(hiddenTables[self].fetchedAPI)
self.Fetch = fetch
self.Reset = reset
end
-- __index lookup when stat(index) is nil
-- if its API has not been fetched yet, call the API to fill in stats
-- then return the fetched value (or the old nil if it's been fetched before)
local function lookup(self,stat)
local api = apiByStat[stat]
local fetchedAPI = hiddenTables[self].fetchedAPI
if api and not fetchedAPI[api] and queryAPIs[api] then
fetchedAPI[api] = true
queryAPIs[api](self)
end
return rawget(self,stat)
end
-- this creates a new petInfo and returns it
function rematch:CreatePetInfo()
local info = {}
hiddenTables[info] = {
fetchedAPI = {}, -- lookup of API functions that have been called for current pet
abilityList = {}, -- cached result of C_PetJournal.GetPetAbilityList
levelList = {}, -- cached result of C_PetJournal.GetPetAbilityList
possibleBreedIDs = {}, -- table of breedIDs possible for a speciesID
possibleBreedNames = {}, -- table of breedNames possible for a speciesID
}
reset(info)
setmetatable(info,{__index=lookup})
return info
end
-- create two petInfos for use in the addon
rematch.petInfo = rematch:CreatePetInfo()
rematch.altInfo = rematch:CreatePetInfo()
|
local util = require "server.account.util"
local resty_redis = require "resty.redis"
local _M = {}
function _M:new(config)
config = config or util.config().db.config
local db = resty_redis:new()
if config.timeout then
db:set_timeout(config.timeout)
end
local ok,err = db:connect(config.host,config.port)
assert(ok,err)
if config.auth then
ok,err = db:auth(config.auth)
assert(ok,err)
end
return db
end
function _M:close(db)
db:set_keepalive(10000,100)
end
return _M
|
local ffi = require "ffi"
ffi.cdef [[
static const unsigned int XK_VoidSymbol = 0xffffff; /* Void symbol */
/*
* TTY function keys, cleverly chosen to map to ASCII, for convenience of
* programming, but could have been arbitrary (at the cost of lookup
* tables in client code).
*/
static const unsigned int XK_BackSpace = 0xff08; /* Back space, back char */
static const unsigned int XK_Tab = 0xff09;
static const unsigned int XK_Linefeed = 0xff0a; /* Linefeed, LF */
static const unsigned int XK_Clear = 0xff0b;
static const unsigned int XK_Return = 0xff0d; /* Return, enter */
static const unsigned int XK_Pause = 0xff13; /* Pause, hold */
static const unsigned int XK_Scroll_Lock = 0xff14;
static const unsigned int XK_Sys_Req = 0xff15;
static const unsigned int XK_Escape = 0xff1b;
static const unsigned int XK_Delete = 0xffff; /* Delete, rubout */
/* International & multi-key character composition */
static const unsigned int XK_Multi_key = 0xff20; /* Multi-key character compose */
static const unsigned int XK_Codeinput = 0xff37;
static const unsigned int XK_SingleCandidate = 0xff3c;
static const unsigned int XK_MultipleCandidate = 0xff3d;
static const unsigned int XK_PreviousCandidate = 0xff3e;
/* Japanese keyboard support */
static const unsigned int XK_Kanji = 0xff21; /* Kanji, Kanji convert */
static const unsigned int XK_Muhenkan = 0xff22; /* Cancel Conversion */
static const unsigned int XK_Henkan_Mode = 0xff23; /* Start/Stop Conversion */
static const unsigned int XK_Henkan = 0xff23; /* Alias for Henkan_Mode */
static const unsigned int XK_Romaji = 0xff24; /* to Romaji */
static const unsigned int XK_Hiragana = 0xff25; /* to Hiragana */
static const unsigned int XK_Katakana = 0xff26; /* to Katakana */
static const unsigned int XK_Hiragana_Katakana = 0xff27; /* Hiragana/Katakana toggle */
static const unsigned int XK_Zenkaku = 0xff28; /* to Zenkaku */
static const unsigned int XK_Hankaku = 0xff29; /* to Hankaku */
static const unsigned int XK_Zenkaku_Hankaku = 0xff2a; /* Zenkaku/Hankaku toggle */
static const unsigned int XK_Touroku = 0xff2b; /* Add to Dictionary */
static const unsigned int XK_Massyo = 0xff2c; /* Delete from Dictionary */
static const unsigned int XK_Kana_Lock = 0xff2d; /* Kana Lock */
static const unsigned int XK_Kana_Shift = 0xff2e; /* Kana Shift */
static const unsigned int XK_Eisu_Shift = 0xff2f; /* Alphanumeric Shift */
static const unsigned int XK_Eisu_toggle = 0xff30; /* Alphanumeric toggle */
static const unsigned int XK_Kanji_Bangou = 0xff37; /* Codeinput */
static const unsigned int XK_Zen_Koho = 0xff3d; /* Multiple/All Candidate(s) */
static const unsigned int XK_Mae_Koho = 0xff3e; /* Previous Candidate */
/* 0xff31 thru 0xff3f are under XK_KOREAN */
/* Cursor control & motion */
static const unsigned int XK_Home = 0xff50;
static const unsigned int XK_Left = 0xff51; /* Move left, left arrow */
static const unsigned int XK_Up = 0xff52; /* Move up, up arrow */
static const unsigned int XK_Right = 0xff53; /* Move right, right arrow */
static const unsigned int XK_Down = 0xff54; /* Move down, down arrow */
static const unsigned int XK_Prior = 0xff55; /* Prior, previous */
static const unsigned int XK_Page_Up = 0xff55;
static const unsigned int XK_Next = 0xff56; /* Next */
static const unsigned int XK_Page_Down = 0xff56;
static const unsigned int XK_End = 0xff57; /* EOL */
static const unsigned int XK_Begin = 0xff58; /* BOL */
/* Misc functions */
static const unsigned int XK_Select = 0xff60; /* Select, mark */
static const unsigned int XK_Print = 0xff61;
static const unsigned int XK_Execute = 0xff62; /* Execute, run, do */
static const unsigned int XK_Insert = 0xff63; /* Insert, insert here */
static const unsigned int XK_Undo = 0xff65;
static const unsigned int XK_Redo = 0xff66; /* Redo, again */
static const unsigned int XK_Menu = 0xff67;
static const unsigned int XK_Find = 0xff68; /* Find, search */
static const unsigned int XK_Cancel = 0xff69; /* Cancel, stop, abort, exit */
static const unsigned int XK_Help = 0xff6a; /* Help */
static const unsigned int XK_Break = 0xff6b;
static const unsigned int XK_Mode_switch = 0xff7e; /* Character set switch */
static const unsigned int XK_script_switch = 0xff7e; /* Alias for mode_switch */
static const unsigned int XK_Num_Lock = 0xff7f;
/* Keypad functions, keypad numbers cleverly chosen to map to ASCII */
static const unsigned int XK_KP_Space = 0xff80; /* Space */
static const unsigned int XK_KP_Tab = 0xff89;
static const unsigned int XK_KP_Enter = 0xff8d; /* Enter */
static const unsigned int XK_KP_F1 = 0xff91; /* PF1, KP_A, ... */
static const unsigned int XK_KP_F2 = 0xff92;
static const unsigned int XK_KP_F3 = 0xff93;
static const unsigned int XK_KP_F4 = 0xff94;
static const unsigned int XK_KP_Home = 0xff95;
static const unsigned int XK_KP_Left = 0xff96;
static const unsigned int XK_KP_Up = 0xff97;
static const unsigned int XK_KP_Right = 0xff98;
static const unsigned int XK_KP_Down = 0xff99;
static const unsigned int XK_KP_Prior = 0xff9a;
static const unsigned int XK_KP_Page_Up = 0xff9a;
static const unsigned int XK_KP_Next = 0xff9b;
static const unsigned int XK_KP_Page_Down = 0xff9b;
static const unsigned int XK_KP_End = 0xff9c;
static const unsigned int XK_KP_Begin = 0xff9d;
static const unsigned int XK_KP_Insert = 0xff9e;
static const unsigned int XK_KP_Delete = 0xff9f;
static const unsigned int XK_KP_Equal = 0xffbd; /* Equals */
static const unsigned int XK_KP_Multiply = 0xffaa;
static const unsigned int XK_KP_Add = 0xffab;
static const unsigned int XK_KP_Separator = 0xffac; /* Separator, often comma */
static const unsigned int XK_KP_Subtract = 0xffad;
static const unsigned int XK_KP_Decimal = 0xffae;
static const unsigned int XK_KP_Divide = 0xffaf;
static const unsigned int XK_KP_0 = 0xffb0;
static const unsigned int XK_KP_1 = 0xffb1;
static const unsigned int XK_KP_2 = 0xffb2;
static const unsigned int XK_KP_3 = 0xffb3;
static const unsigned int XK_KP_4 = 0xffb4;
static const unsigned int XK_KP_5 = 0xffb5;
static const unsigned int XK_KP_6 = 0xffb6;
static const unsigned int XK_KP_7 = 0xffb7;
static const unsigned int XK_KP_8 = 0xffb8;
static const unsigned int XK_KP_9 = 0xffb9;
/*
* Auxiliary functions; note the duplicate definitions for left and right
* function keys; Sun keyboards and a few other manufacturers have such
* function key groups on the left and/or right sides of the keyboard.
* We've not found a keyboard with more than 35 function keys total.
*/
static const unsigned int XK_F1 = 0xffbe;
static const unsigned int XK_F2 = 0xffbf;
static const unsigned int XK_F3 = 0xffc0;
static const unsigned int XK_F4 = 0xffc1;
static const unsigned int XK_F5 = 0xffc2;
static const unsigned int XK_F6 = 0xffc3;
static const unsigned int XK_F7 = 0xffc4;
static const unsigned int XK_F8 = 0xffc5;
static const unsigned int XK_F9 = 0xffc6;
static const unsigned int XK_F10 = 0xffc7;
static const unsigned int XK_F11 = 0xffc8;
static const unsigned int XK_L1 = 0xffc8;
static const unsigned int XK_F12 = 0xffc9;
static const unsigned int XK_L2 = 0xffc9;
static const unsigned int XK_F13 = 0xffca;
static const unsigned int XK_L3 = 0xffca;
static const unsigned int XK_F14 = 0xffcb;
static const unsigned int XK_L4 = 0xffcb;
static const unsigned int XK_F15 = 0xffcc;
static const unsigned int XK_L5 = 0xffcc;
static const unsigned int XK_F16 = 0xffcd;
static const unsigned int XK_L6 = 0xffcd;
static const unsigned int XK_F17 = 0xffce;
static const unsigned int XK_L7 = 0xffce;
static const unsigned int XK_F18 = 0xffcf;
static const unsigned int XK_L8 = 0xffcf;
static const unsigned int XK_F19 = 0xffd0;
static const unsigned int XK_L9 = 0xffd0;
static const unsigned int XK_F20 = 0xffd1;
static const unsigned int XK_L10 = 0xffd1;
static const unsigned int XK_F21 = 0xffd2;
static const unsigned int XK_R1 = 0xffd2;
static const unsigned int XK_F22 = 0xffd3;
static const unsigned int XK_R2 = 0xffd3;
static const unsigned int XK_F23 = 0xffd4;
static const unsigned int XK_R3 = 0xffd4;
static const unsigned int XK_F24 = 0xffd5;
static const unsigned int XK_R4 = 0xffd5;
static const unsigned int XK_F25 = 0xffd6;
static const unsigned int XK_R5 = 0xffd6;
static const unsigned int XK_F26 = 0xffd7;
static const unsigned int XK_R6 = 0xffd7;
static const unsigned int XK_F27 = 0xffd8;
static const unsigned int XK_R7 = 0xffd8;
static const unsigned int XK_F28 = 0xffd9;
static const unsigned int XK_R8 = 0xffd9;
static const unsigned int XK_F29 = 0xffda;
static const unsigned int XK_R9 = 0xffda;
static const unsigned int XK_F30 = 0xffdb;
static const unsigned int XK_R10 = 0xffdb;
static const unsigned int XK_F31 = 0xffdc;
static const unsigned int XK_R11 = 0xffdc;
static const unsigned int XK_F32 = 0xffdd;
static const unsigned int XK_R12 = 0xffdd;
static const unsigned int XK_F33 = 0xffde;
static const unsigned int XK_R13 = 0xffde;
static const unsigned int XK_F34 = 0xffdf;
static const unsigned int XK_R14 = 0xffdf;
static const unsigned int XK_F35 = 0xffe0;
static const unsigned int XK_R15 = 0xffe0;
/* Modifiers */
static const unsigned int XK_Shift_L = 0xffe1; /* Left shift */
static const unsigned int XK_Shift_R = 0xffe2; /* Right shift */
static const unsigned int XK_Control_L = 0xffe3; /* Left control */
static const unsigned int XK_Control_R = 0xffe4; /* Right control */
static const unsigned int XK_Caps_Lock = 0xffe5; /* Caps lock */
static const unsigned int XK_Shift_Lock = 0xffe6; /* Shift lock */
static const unsigned int XK_Meta_L = 0xffe7; /* Left meta */
static const unsigned int XK_Meta_R = 0xffe8; /* Right meta */
static const unsigned int XK_Alt_L = 0xffe9; /* Left alt */
static const unsigned int XK_Alt_R = 0xffea; /* Right alt */
static const unsigned int XK_Super_L = 0xffeb; /* Left super */
static const unsigned int XK_Super_R = 0xffec; /* Right super */
static const unsigned int XK_Hyper_L = 0xffed; /* Left hyper */
static const unsigned int XK_Hyper_R = 0xffee; /* Right hyper */
/*
* Keyboard (XKB) Extension function and modifier keys
* (from Appendix C of "The X Keyboard Extension: Protocol Specification")
* Byte 3 = 0xfe
*/
static const unsigned int XK_ISO_Lock = 0xfe01;
static const unsigned int XK_ISO_Level2_Latch = 0xfe02;
static const unsigned int XK_ISO_Level3_Shift = 0xfe03;
static const unsigned int XK_ISO_Level3_Latch = 0xfe04;
static const unsigned int XK_ISO_Level3_Lock = 0xfe05;
static const unsigned int XK_ISO_Level5_Shift = 0xfe11;
static const unsigned int XK_ISO_Level5_Latch = 0xfe12;
static const unsigned int XK_ISO_Level5_Lock = 0xfe13;
static const unsigned int XK_ISO_Group_Shift = 0xff7e; /* Alias for mode_switch */
static const unsigned int XK_ISO_Group_Latch = 0xfe06;
static const unsigned int XK_ISO_Group_Lock = 0xfe07;
static const unsigned int XK_ISO_Next_Group = 0xfe08;
static const unsigned int XK_ISO_Next_Group_Lock = 0xfe09;
static const unsigned int XK_ISO_Prev_Group = 0xfe0a;
static const unsigned int XK_ISO_Prev_Group_Lock = 0xfe0b;
static const unsigned int XK_ISO_First_Group = 0xfe0c;
static const unsigned int XK_ISO_First_Group_Lock = 0xfe0d;
static const unsigned int XK_ISO_Last_Group = 0xfe0e;
static const unsigned int XK_ISO_Last_Group_Lock = 0xfe0f;
static const unsigned int XK_ISO_Left_Tab = 0xfe20;
static const unsigned int XK_ISO_Move_Line_Up = 0xfe21;
static const unsigned int XK_ISO_Move_Line_Down = 0xfe22;
static const unsigned int XK_ISO_Partial_Line_Up = 0xfe23;
static const unsigned int XK_ISO_Partial_Line_Down = 0xfe24;
static const unsigned int XK_ISO_Partial_Space_Left = 0xfe25;
static const unsigned int XK_ISO_Partial_Space_Right = 0xfe26;
static const unsigned int XK_ISO_Set_Margin_Left = 0xfe27;
static const unsigned int XK_ISO_Set_Margin_Right = 0xfe28;
static const unsigned int XK_ISO_Release_Margin_Left = 0xfe29;
static const unsigned int XK_ISO_Release_Margin_Right = 0xfe2a;
static const unsigned int XK_ISO_Release_Both_Margins = 0xfe2b;
static const unsigned int XK_ISO_Fast_Cursor_Left = 0xfe2c;
static const unsigned int XK_ISO_Fast_Cursor_Right = 0xfe2d;
static const unsigned int XK_ISO_Fast_Cursor_Up = 0xfe2e;
static const unsigned int XK_ISO_Fast_Cursor_Down = 0xfe2f;
static const unsigned int XK_ISO_Continuous_Underline = 0xfe30;
static const unsigned int XK_ISO_Discontinuous_Underline = 0xfe31;
static const unsigned int XK_ISO_Emphasize = 0xfe32;
static const unsigned int XK_ISO_Center_Object = 0xfe33;
static const unsigned int XK_ISO_Enter = 0xfe34;
static const unsigned int XK_dead_grave = 0xfe50;
static const unsigned int XK_dead_acute = 0xfe51;
static const unsigned int XK_dead_circumflex = 0xfe52;
static const unsigned int XK_dead_tilde = 0xfe53;
static const unsigned int XK_dead_perispomeni = 0xfe53; /* alias for dead_tilde */
static const unsigned int XK_dead_macron = 0xfe54;
static const unsigned int XK_dead_breve = 0xfe55;
static const unsigned int XK_dead_abovedot = 0xfe56;
static const unsigned int XK_dead_diaeresis = 0xfe57;
static const unsigned int XK_dead_abovering = 0xfe58;
static const unsigned int XK_dead_doubleacute = 0xfe59;
static const unsigned int XK_dead_caron = 0xfe5a;
static const unsigned int XK_dead_cedilla = 0xfe5b;
static const unsigned int XK_dead_ogonek = 0xfe5c;
static const unsigned int XK_dead_iota = 0xfe5d;
static const unsigned int XK_dead_voiced_sound = 0xfe5e;
static const unsigned int XK_dead_semivoiced_sound = 0xfe5f;
static const unsigned int XK_dead_belowdot = 0xfe60;
static const unsigned int XK_dead_hook = 0xfe61;
static const unsigned int XK_dead_horn = 0xfe62;
static const unsigned int XK_dead_stroke = 0xfe63;
static const unsigned int XK_dead_abovecomma = 0xfe64;
static const unsigned int XK_dead_psili = 0xfe64; /* alias for dead_abovecomma */
static const unsigned int XK_dead_abovereversedcomma = 0xfe65;
static const unsigned int XK_dead_dasia = 0xfe65; /* alias for dead_abovereversedcomma */
static const unsigned int XK_dead_doublegrave = 0xfe66;
static const unsigned int XK_dead_belowring = 0xfe67;
static const unsigned int XK_dead_belowmacron = 0xfe68;
static const unsigned int XK_dead_belowcircumflex = 0xfe69;
static const unsigned int XK_dead_belowtilde = 0xfe6a;
static const unsigned int XK_dead_belowbreve = 0xfe6b;
static const unsigned int XK_dead_belowdiaeresis = 0xfe6c;
static const unsigned int XK_dead_invertedbreve = 0xfe6d;
static const unsigned int XK_dead_belowcomma = 0xfe6e;
static const unsigned int XK_dead_currency = 0xfe6f;
/* extra dead elements for German T3 layout */
static const unsigned int XK_dead_lowline = 0xfe90;
static const unsigned int XK_dead_aboveverticalline = 0xfe91;
static const unsigned int XK_dead_belowverticalline = 0xfe92;
static const unsigned int XK_dead_longsolidusoverlay = 0xfe93;
/* dead vowels for universal syllable entry */
static const unsigned int XK_dead_a = 0xfe80;
static const unsigned int XK_dead_A = 0xfe81;
static const unsigned int XK_dead_e = 0xfe82;
static const unsigned int XK_dead_E = 0xfe83;
static const unsigned int XK_dead_i = 0xfe84;
static const unsigned int XK_dead_I = 0xfe85;
static const unsigned int XK_dead_o = 0xfe86;
static const unsigned int XK_dead_O = 0xfe87;
static const unsigned int XK_dead_u = 0xfe88;
static const unsigned int XK_dead_U = 0xfe89;
static const unsigned int XK_dead_small_schwa = 0xfe8a;
static const unsigned int XK_dead_capital_schwa = 0xfe8b;
static const unsigned int XK_dead_greek = 0xfe8c;
static const unsigned int XK_First_Virtual_Screen = 0xfed0;
static const unsigned int XK_Prev_Virtual_Screen = 0xfed1;
static const unsigned int XK_Next_Virtual_Screen = 0xfed2;
static const unsigned int XK_Last_Virtual_Screen = 0xfed4;
static const unsigned int XK_Terminate_Server = 0xfed5;
static const unsigned int XK_AccessX_Enable = 0xfe70;
static const unsigned int XK_AccessX_Feedback_Enable = 0xfe71;
static const unsigned int XK_RepeatKeys_Enable = 0xfe72;
static const unsigned int XK_SlowKeys_Enable = 0xfe73;
static const unsigned int XK_BounceKeys_Enable = 0xfe74;
static const unsigned int XK_StickyKeys_Enable = 0xfe75;
static const unsigned int XK_MouseKeys_Enable = 0xfe76;
static const unsigned int XK_MouseKeys_Accel_Enable = 0xfe77;
static const unsigned int XK_Overlay1_Enable = 0xfe78;
static const unsigned int XK_Overlay2_Enable = 0xfe79;
static const unsigned int XK_AudibleBell_Enable = 0xfe7a;
static const unsigned int XK_Pointer_Left = 0xfee0;
static const unsigned int XK_Pointer_Right = 0xfee1;
static const unsigned int XK_Pointer_Up = 0xfee2;
static const unsigned int XK_Pointer_Down = 0xfee3;
static const unsigned int XK_Pointer_UpLeft = 0xfee4;
static const unsigned int XK_Pointer_UpRight = 0xfee5;
static const unsigned int XK_Pointer_DownLeft = 0xfee6;
static const unsigned int XK_Pointer_DownRight = 0xfee7;
static const unsigned int XK_Pointer_Button_Dflt = 0xfee8;
static const unsigned int XK_Pointer_Button1 = 0xfee9;
static const unsigned int XK_Pointer_Button2 = 0xfeea;
static const unsigned int XK_Pointer_Button3 = 0xfeeb;
static const unsigned int XK_Pointer_Button4 = 0xfeec;
static const unsigned int XK_Pointer_Button5 = 0xfeed;
static const unsigned int XK_Pointer_DblClick_Dflt = 0xfeee;
static const unsigned int XK_Pointer_DblClick1 = 0xfeef;
static const unsigned int XK_Pointer_DblClick2 = 0xfef0;
static const unsigned int XK_Pointer_DblClick3 = 0xfef1;
static const unsigned int XK_Pointer_DblClick4 = 0xfef2;
static const unsigned int XK_Pointer_DblClick5 = 0xfef3;
static const unsigned int XK_Pointer_Drag_Dflt = 0xfef4;
static const unsigned int XK_Pointer_Drag1 = 0xfef5;
static const unsigned int XK_Pointer_Drag2 = 0xfef6;
static const unsigned int XK_Pointer_Drag3 = 0xfef7;
static const unsigned int XK_Pointer_Drag4 = 0xfef8;
static const unsigned int XK_Pointer_Drag5 = 0xfefd;
static const unsigned int XK_Pointer_EnableKeys = 0xfef9;
static const unsigned int XK_Pointer_Accelerate = 0xfefa;
static const unsigned int XK_Pointer_DfltBtnNext = 0xfefb;
static const unsigned int XK_Pointer_DfltBtnPrev = 0xfefc;
/* Single-Stroke Multiple-Character N-Graph Keysyms For The X Input Method */
static const unsigned int XK_ch = 0xfea0;
static const unsigned int XK_Ch = 0xfea1;
static const unsigned int XK_CH = 0xfea2;
static const unsigned int XK_c_h = 0xfea3;
static const unsigned int XK_C_h = 0xfea4;
static const unsigned int XK_C_H = 0xfea5;
/*
* 3270 Terminal Keys
* Byte 3 = 0xfd
*/
static const unsigned int XK_3270_Duplicate = 0xfd01;
static const unsigned int XK_3270_FieldMark = 0xfd02;
static const unsigned int XK_3270_Right2 = 0xfd03;
static const unsigned int XK_3270_Left2 = 0xfd04;
static const unsigned int XK_3270_BackTab = 0xfd05;
static const unsigned int XK_3270_EraseEOF = 0xfd06;
static const unsigned int XK_3270_EraseInput = 0xfd07;
static const unsigned int XK_3270_Reset = 0xfd08;
static const unsigned int XK_3270_Quit = 0xfd09;
static const unsigned int XK_3270_PA1 = 0xfd0a;
static const unsigned int XK_3270_PA2 = 0xfd0b;
static const unsigned int XK_3270_PA3 = 0xfd0c;
static const unsigned int XK_3270_Test = 0xfd0d;
static const unsigned int XK_3270_Attn = 0xfd0e;
static const unsigned int XK_3270_CursorBlink = 0xfd0f;
static const unsigned int XK_3270_AltCursor = 0xfd10;
static const unsigned int XK_3270_KeyClick = 0xfd11;
static const unsigned int XK_3270_Jump = 0xfd12;
static const unsigned int XK_3270_Ident = 0xfd13;
static const unsigned int XK_3270_Rule = 0xfd14;
static const unsigned int XK_3270_Copy = 0xfd15;
static const unsigned int XK_3270_Play = 0xfd16;
static const unsigned int XK_3270_Setup = 0xfd17;
static const unsigned int XK_3270_Record = 0xfd18;
static const unsigned int XK_3270_ChangeScreen = 0xfd19;
static const unsigned int XK_3270_DeleteWord = 0xfd1a;
static const unsigned int XK_3270_ExSelect = 0xfd1b;
static const unsigned int XK_3270_CursorSelect = 0xfd1c;
static const unsigned int XK_3270_PrintScreen = 0xfd1d;
static const unsigned int XK_3270_Enter = 0xfd1e;
/*
* Latin 1
* (ISO/IEC 8859-1 = Unicode U+0020..U+00FF)
* Byte 3 = 0
*/
static const unsigned int XK_space = 0x0020; /* U+0020 SPACE */
static const unsigned int XK_exclam = 0x0021; /* U+0021 EXCLAMATION MARK */
static const unsigned int XK_quotedbl = 0x0022; /* U+0022 QUOTATION MARK */
static const unsigned int XK_numbersign = 0x0023; /* U+0023 NUMBER SIGN */
static const unsigned int XK_dollar = 0x0024; /* U+0024 DOLLAR SIGN */
static const unsigned int XK_percent = 0x0025; /* U+0025 PERCENT SIGN */
static const unsigned int XK_ampersand = 0x0026; /* U+0026 AMPERSAND */
static const unsigned int XK_apostrophe = 0x0027; /* U+0027 APOSTROPHE */
static const unsigned int XK_quoteright = 0x0027; /* deprecated */
static const unsigned int XK_parenleft = 0x0028; /* U+0028 LEFT PARENTHESIS */
static const unsigned int XK_parenright = 0x0029; /* U+0029 RIGHT PARENTHESIS */
static const unsigned int XK_asterisk = 0x002a; /* U+002A ASTERISK */
static const unsigned int XK_plus = 0x002b; /* U+002B PLUS SIGN */
static const unsigned int XK_comma = 0x002c; /* U+002C COMMA */
static const unsigned int XK_minus = 0x002d; /* U+002D HYPHEN-MINUS */
static const unsigned int XK_period = 0x002e; /* U+002E FULL STOP */
static const unsigned int XK_slash = 0x002f; /* U+002F SOLIDUS */
static const unsigned int XK_0 = 0x0030; /* U+0030 DIGIT ZERO */
static const unsigned int XK_1 = 0x0031; /* U+0031 DIGIT ONE */
static const unsigned int XK_2 = 0x0032; /* U+0032 DIGIT TWO */
static const unsigned int XK_3 = 0x0033; /* U+0033 DIGIT THREE */
static const unsigned int XK_4 = 0x0034; /* U+0034 DIGIT FOUR */
static const unsigned int XK_5 = 0x0035; /* U+0035 DIGIT FIVE */
static const unsigned int XK_6 = 0x0036; /* U+0036 DIGIT SIX */
static const unsigned int XK_7 = 0x0037; /* U+0037 DIGIT SEVEN */
static const unsigned int XK_8 = 0x0038; /* U+0038 DIGIT EIGHT */
static const unsigned int XK_9 = 0x0039; /* U+0039 DIGIT NINE */
static const unsigned int XK_colon = 0x003a; /* U+003A COLON */
static const unsigned int XK_semicolon = 0x003b; /* U+003B SEMICOLON */
static const unsigned int XK_less = 0x003c; /* U+003C LESS-THAN SIGN */
static const unsigned int XK_equal = 0x003d; /* U+003D EQUALS SIGN */
static const unsigned int XK_greater = 0x003e; /* U+003E GREATER-THAN SIGN */
static const unsigned int XK_question = 0x003f; /* U+003F QUESTION MARK */
static const unsigned int XK_at = 0x0040; /* U+0040 COMMERCIAL AT */
static const unsigned int XK_A = 0x0041; /* U+0041 LATIN CAPITAL LETTER A */
static const unsigned int XK_B = 0x0042; /* U+0042 LATIN CAPITAL LETTER B */
static const unsigned int XK_C = 0x0043; /* U+0043 LATIN CAPITAL LETTER C */
static const unsigned int XK_D = 0x0044; /* U+0044 LATIN CAPITAL LETTER D */
static const unsigned int XK_E = 0x0045; /* U+0045 LATIN CAPITAL LETTER E */
static const unsigned int XK_F = 0x0046; /* U+0046 LATIN CAPITAL LETTER F */
static const unsigned int XK_G = 0x0047; /* U+0047 LATIN CAPITAL LETTER G */
static const unsigned int XK_H = 0x0048; /* U+0048 LATIN CAPITAL LETTER H */
static const unsigned int XK_I = 0x0049; /* U+0049 LATIN CAPITAL LETTER I */
static const unsigned int XK_J = 0x004a; /* U+004A LATIN CAPITAL LETTER J */
static const unsigned int XK_K = 0x004b; /* U+004B LATIN CAPITAL LETTER K */
static const unsigned int XK_L = 0x004c; /* U+004C LATIN CAPITAL LETTER L */
static const unsigned int XK_M = 0x004d; /* U+004D LATIN CAPITAL LETTER M */
static const unsigned int XK_N = 0x004e; /* U+004E LATIN CAPITAL LETTER N */
static const unsigned int XK_O = 0x004f; /* U+004F LATIN CAPITAL LETTER O */
static const unsigned int XK_P = 0x0050; /* U+0050 LATIN CAPITAL LETTER P */
static const unsigned int XK_Q = 0x0051; /* U+0051 LATIN CAPITAL LETTER Q */
static const unsigned int XK_R = 0x0052; /* U+0052 LATIN CAPITAL LETTER R */
static const unsigned int XK_S = 0x0053; /* U+0053 LATIN CAPITAL LETTER S */
static const unsigned int XK_T = 0x0054; /* U+0054 LATIN CAPITAL LETTER T */
static const unsigned int XK_U = 0x0055; /* U+0055 LATIN CAPITAL LETTER U */
static const unsigned int XK_V = 0x0056; /* U+0056 LATIN CAPITAL LETTER V */
static const unsigned int XK_W = 0x0057; /* U+0057 LATIN CAPITAL LETTER W */
static const unsigned int XK_X = 0x0058; /* U+0058 LATIN CAPITAL LETTER X */
static const unsigned int XK_Y = 0x0059; /* U+0059 LATIN CAPITAL LETTER Y */
static const unsigned int XK_Z = 0x005a; /* U+005A LATIN CAPITAL LETTER Z */
static const unsigned int XK_bracketleft = 0x005b; /* U+005B LEFT SQUARE BRACKET */
static const unsigned int XK_backslash = 0x005c; /* U+005C REVERSE SOLIDUS */
static const unsigned int XK_bracketright = 0x005d; /* U+005D RIGHT SQUARE BRACKET */
static const unsigned int XK_asciicircum = 0x005e; /* U+005E CIRCUMFLEX ACCENT */
static const unsigned int XK_underscore = 0x005f; /* U+005F LOW LINE */
static const unsigned int XK_grave = 0x0060; /* U+0060 GRAVE ACCENT */
static const unsigned int XK_quoteleft = 0x0060; /* deprecated */
static const unsigned int XK_a = 0x0061; /* U+0061 LATIN SMALL LETTER A */
static const unsigned int XK_b = 0x0062; /* U+0062 LATIN SMALL LETTER B */
static const unsigned int XK_c = 0x0063; /* U+0063 LATIN SMALL LETTER C */
static const unsigned int XK_d = 0x0064; /* U+0064 LATIN SMALL LETTER D */
static const unsigned int XK_e = 0x0065; /* U+0065 LATIN SMALL LETTER E */
static const unsigned int XK_f = 0x0066; /* U+0066 LATIN SMALL LETTER F */
static const unsigned int XK_g = 0x0067; /* U+0067 LATIN SMALL LETTER G */
static const unsigned int XK_h = 0x0068; /* U+0068 LATIN SMALL LETTER H */
static const unsigned int XK_i = 0x0069; /* U+0069 LATIN SMALL LETTER I */
static const unsigned int XK_j = 0x006a; /* U+006A LATIN SMALL LETTER J */
static const unsigned int XK_k = 0x006b; /* U+006B LATIN SMALL LETTER K */
static const unsigned int XK_l = 0x006c; /* U+006C LATIN SMALL LETTER L */
static const unsigned int XK_m = 0x006d; /* U+006D LATIN SMALL LETTER M */
static const unsigned int XK_n = 0x006e; /* U+006E LATIN SMALL LETTER N */
static const unsigned int XK_o = 0x006f; /* U+006F LATIN SMALL LETTER O */
static const unsigned int XK_p = 0x0070; /* U+0070 LATIN SMALL LETTER P */
static const unsigned int XK_q = 0x0071; /* U+0071 LATIN SMALL LETTER Q */
static const unsigned int XK_r = 0x0072; /* U+0072 LATIN SMALL LETTER R */
static const unsigned int XK_s = 0x0073; /* U+0073 LATIN SMALL LETTER S */
static const unsigned int XK_t = 0x0074; /* U+0074 LATIN SMALL LETTER T */
static const unsigned int XK_u = 0x0075; /* U+0075 LATIN SMALL LETTER U */
static const unsigned int XK_v = 0x0076; /* U+0076 LATIN SMALL LETTER V */
static const unsigned int XK_w = 0x0077; /* U+0077 LATIN SMALL LETTER W */
static const unsigned int XK_x = 0x0078; /* U+0078 LATIN SMALL LETTER X */
static const unsigned int XK_y = 0x0079; /* U+0079 LATIN SMALL LETTER Y */
static const unsigned int XK_z = 0x007a; /* U+007A LATIN SMALL LETTER Z */
static const unsigned int XK_braceleft = 0x007b; /* U+007B LEFT CURLY BRACKET */
static const unsigned int XK_bar = 0x007c; /* U+007C VERTICAL LINE */
static const unsigned int XK_braceright = 0x007d; /* U+007D RIGHT CURLY BRACKET */
static const unsigned int XK_asciitilde = 0x007e; /* U+007E TILDE */
static const unsigned int XK_nobreakspace = 0x00a0; /* U+00A0 NO-BREAK SPACE */
static const unsigned int XK_exclamdown = 0x00a1; /* U+00A1 INVERTED EXCLAMATION MARK */
static const unsigned int XK_cent = 0x00a2; /* U+00A2 CENT SIGN */
static const unsigned int XK_sterling = 0x00a3; /* U+00A3 POUND SIGN */
static const unsigned int XK_currency = 0x00a4; /* U+00A4 CURRENCY SIGN */
static const unsigned int XK_yen = 0x00a5; /* U+00A5 YEN SIGN */
static const unsigned int XK_brokenbar = 0x00a6; /* U+00A6 BROKEN BAR */
static const unsigned int XK_section = 0x00a7; /* U+00A7 SECTION SIGN */
static const unsigned int XK_diaeresis = 0x00a8; /* U+00A8 DIAERESIS */
static const unsigned int XK_copyright = 0x00a9; /* U+00A9 COPYRIGHT SIGN */
static const unsigned int XK_ordfeminine = 0x00aa; /* U+00AA FEMININE ORDINAL INDICATOR */
static const unsigned int XK_guillemotleft =
0x00ab; /* = U;+00AB LEFT-POINTING DOUBLE ANGLE QUOTATION MARK */
static const unsigned int XK_notsign = 0x00ac; /* U+00AC NOT SIGN */
static const unsigned int XK_hyphen = 0x00ad; /* U+00AD SOFT HYPHEN */
static const unsigned int XK_registered = 0x00ae; /* U+00AE REGISTERED SIGN */
static const unsigned int XK_macron = 0x00af; /* U+00AF MACRON */
static const unsigned int XK_degree = 0x00b0; /* U+00B0 DEGREE SIGN */
static const unsigned int XK_plusminus = 0x00b1; /* U+00B1 PLUS-MINUS SIGN */
static const unsigned int XK_twosuperior = 0x00b2; /* U+00B2 SUPERSCRIPT TWO */
static const unsigned int XK_threesuperior = 0x00b3; /* U+00B3 SUPERSCRIPT THREE */
static const unsigned int XK_acute = 0x00b4; /* U+00B4 ACUTE ACCENT */
static const unsigned int XK_mu = 0x00b5; /* U+00B5 MICRO SIGN */
static const unsigned int XK_paragraph = 0x00b6; /* U+00B6 PILCROW SIGN */
static const unsigned int XK_periodcentered = 0x00b7; /* U+00B7 MIDDLE DOT */
static const unsigned int XK_cedilla = 0x00b8; /* U+00B8 CEDILLA */
static const unsigned int XK_onesuperior = 0x00b9; /* U+00B9 SUPERSCRIPT ONE */
static const unsigned int XK_masculine = 0x00ba; /* U+00BA MASCULINE ORDINAL INDICATOR */
static const unsigned int XK_guillemotright
= 0x00bb; /* U+00BB RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK */
static const unsigned int XK_onequarter = 0x00bc; /* U+00BC VULGAR FRACTION ONE QUARTER */
static const unsigned int XK_onehalf = 0x00bd; /* U+00BD VULGAR FRACTION ONE HALF */
static const unsigned int XK_threequarters = 0x00be; /* U+00BE VULGAR FRACTION THREE QUARTERS */
static const unsigned int XK_questiondown = 0x00bf; /* U+00BF INVERTED QUESTION MARK */
static const unsigned int XK_Agrave = 0x00c0; /* U+00C0 LATIN CAPITAL LETTER A WITH GRAVE */
static const unsigned int XK_Aacute = 0x00c1; /* U+00C1 LATIN CAPITAL LETTER A WITH ACUTE */
static const unsigned int XK_Acircumflex \
= 0x00c2; /* U+00C2 LATIN CAPITAL LETTER A WITH CIRCUMFLEX */
static const unsigned int XK_Atilde = 0x00c3; /* U+00C3 LATIN CAPITAL LETTER A WITH TILDE */
static const unsigned int XK_Adiaeresis = 0x00c4; /* U+00C4 LATIN CAPITAL LETTER A WITH DIAERESIS \
*/
static const unsigned int XK_Aring = 0x00c5; /* U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE */
static const unsigned int XK_AE = 0x00c6; /* U+00C6 LATIN CAPITAL LETTER AE */
static const unsigned int XK_Ccedilla = 0x00c7; /* U+00C7 LATIN CAPITAL LETTER C WITH CEDILLA */
static const unsigned int XK_Egrave = 0x00c8; /* U+00C8 LATIN CAPITAL LETTER E WITH GRAVE */
static const unsigned int XK_Eacute = 0x00c9; /* U+00C9 LATIN CAPITAL LETTER E WITH ACUTE */
static const unsigned int XK_Ecircumflex \
= 0x00ca; /* U+00CA LATIN CAPITAL LETTER E WITH CIRCUMFLEX */
static const unsigned int XK_Ediaeresis = 0x00cb; /* U+00CB LATIN CAPITAL LETTER E WITH DIAERESIS \
*/
static const unsigned int XK_Igrave = 0x00cc; /* U+00CC LATIN CAPITAL LETTER I WITH GRAVE */
static const unsigned int XK_Iacute = 0x00cd; /* U+00CD LATIN CAPITAL LETTER I WITH ACUTE */
static const unsigned int XK_Icircumflex \
= 0x00ce; /* U+00CE LATIN CAPITAL LETTER I WITH CIRCUMFLEX */
static const unsigned int XK_Idiaeresis = 0x00cf; /* U+00CF LATIN CAPITAL LETTER I WITH DIAERESIS \
*/
static const unsigned int XK_ETH = 0x00d0; /* U+00D0 LATIN CAPITAL LETTER ETH */
static const unsigned int XK_Eth = 0x00d0; /* deprecated */
static const unsigned int XK_Ntilde = 0x00d1; /* U+00D1 LATIN CAPITAL LETTER N WITH TILDE */
static const unsigned int XK_Ograve = 0x00d2; /* U+00D2 LATIN CAPITAL LETTER O WITH GRAVE */
static const unsigned int XK_Oacute = 0x00d3; /* U+00D3 LATIN CAPITAL LETTER O WITH ACUTE */
static const unsigned int XK_Ocircumflex \
= 0x00d4; /* U+00D4 LATIN CAPITAL LETTER O WITH CIRCUMFLEX */
static const unsigned int XK_Otilde = 0x00d5; /* U+00D5 LATIN CAPITAL LETTER O WITH TILDE */
static const unsigned int XK_Odiaeresis = 0x00d6; /* U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS \
*/
static const unsigned int XK_multiply = 0x00d7; /* U+00D7 MULTIPLICATION SIGN */
static const unsigned int XK_Oslash = 0x00d8; /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */
static const unsigned int XK_Ooblique = 0x00d8; /* U+00D8 LATIN CAPITAL LETTER O WITH STROKE */
static const unsigned int XK_Ugrave = 0x00d9; /* U+00D9 LATIN CAPITAL LETTER U WITH GRAVE */
static const unsigned int XK_Uacute = 0x00da; /* U+00DA LATIN CAPITAL LETTER U WITH ACUTE */
static const unsigned int XK_Ucircumflex \
= 0x00db; /* U+00DB LATIN CAPITAL LETTER U WITH CIRCUMFLEX */
static const unsigned int XK_Udiaeresis = 0x00dc; /* U+00DC LATIN CAPITAL LETTER U WITH DIAERESIS \
*/
static const unsigned int XK_Yacute = 0x00dd; /* U+00DD LATIN CAPITAL LETTER Y WITH ACUTE */
static const unsigned int XK_THORN = 0x00de; /* U+00DE LATIN CAPITAL LETTER THORN */
static const unsigned int XK_Thorn = 0x00de; /* deprecated */
static const unsigned int XK_ssharp = 0x00df; /* U+00DF LATIN SMALL LETTER SHARP S */
static const unsigned int XK_agrave = 0x00e0; /* U+00E0 LATIN SMALL LETTER A WITH GRAVE */
static const unsigned int XK_aacute = 0x00e1; /* U+00E1 LATIN SMALL LETTER A WITH ACUTE */
static const unsigned int XK_acircumflex = 0x00e2; /* U+00E2 LATIN SMALL LETTER A WITH CIRCUMFLEX \
*/
static const unsigned int XK_atilde = 0x00e3; /* U+00E3 LATIN SMALL LETTER A WITH TILDE */
static const unsigned int XK_adiaeresis = 0x00e4; /* U+00E4 LATIN SMALL LETTER A WITH DIAERESIS */
static const unsigned int XK_aring = 0x00e5; /* U+00E5 LATIN SMALL LETTER A WITH RING ABOVE */
static const unsigned int XK_ae = 0x00e6; /* U+00E6 LATIN SMALL LETTER AE */
static const unsigned int XK_ccedilla = 0x00e7; /* U+00E7 LATIN SMALL LETTER C WITH CEDILLA */
static const unsigned int XK_egrave = 0x00e8; /* U+00E8 LATIN SMALL LETTER E WITH GRAVE */
static const unsigned int XK_eacute = 0x00e9; /* U+00E9 LATIN SMALL LETTER E WITH ACUTE */
static const unsigned int XK_ecircumflex = 0x00ea; /* U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX \
*/
static const unsigned int XK_ediaeresis = 0x00eb; /* U+00EB LATIN SMALL LETTER E WITH DIAERESIS */
static const unsigned int XK_igrave = 0x00ec; /* U+00EC LATIN SMALL LETTER I WITH GRAVE */
static const unsigned int XK_iacute = 0x00ed; /* U+00ED LATIN SMALL LETTER I WITH ACUTE */
static const unsigned int XK_icircumflex = 0x00ee; /* U+00EE LATIN SMALL LETTER I WITH CIRCUMFLEX \
*/
static const unsigned int XK_idiaeresis = 0x00ef; /* U+00EF LATIN SMALL LETTER I WITH DIAERESIS */
static const unsigned int XK_eth = 0x00f0; /* U+00F0 LATIN SMALL LETTER ETH */
static const unsigned int XK_ntilde = 0x00f1; /* U+00F1 LATIN SMALL LETTER N WITH TILDE */
static const unsigned int XK_ograve = 0x00f2; /* U+00F2 LATIN SMALL LETTER O WITH GRAVE */
static const unsigned int XK_oacute = 0x00f3; /* U+00F3 LATIN SMALL LETTER O WITH ACUTE */
static const unsigned int XK_ocircumflex = 0x00f4; /* U+00F4 LATIN SMALL LETTER O WITH CIRCUMFLEX \
*/
static const unsigned int XK_otilde = 0x00f5; /* U+00F5 LATIN SMALL LETTER O WITH TILDE */
static const unsigned int XK_odiaeresis = 0x00f6; /* U+00F6 LATIN SMALL LETTER O WITH DIAERESIS */
static const unsigned int XK_division = 0x00f7; /* U+00F7 DIVISION SIGN */
static const unsigned int XK_oslash = 0x00f8; /* U+00F8 LATIN SMALL LETTER O WITH STROKE */
static const unsigned int XK_ooblique = 0x00f8; /* U+00F8 LATIN SMALL LETTER O WITH STROKE */
static const unsigned int XK_ugrave = 0x00f9; /* U+00F9 LATIN SMALL LETTER U WITH GRAVE */
static const unsigned int XK_uacute = 0x00fa; /* U+00FA LATIN SMALL LETTER U WITH ACUTE */
static const unsigned int XK_ucircumflex = 0x00fb; /* U+00FB LATIN SMALL LETTER U WITH CIRCUMFLEX \
*/
static const unsigned int XK_udiaeresis = 0x00fc; /* U+00FC LATIN SMALL LETTER U WITH DIAERESIS */
static const unsigned int XK_yacute = 0x00fd; /* U+00FD LATIN SMALL LETTER Y WITH ACUTE */
static const unsigned int XK_thorn = 0x00fe; /* U+00FE LATIN SMALL LETTER THORN */
static const unsigned int XK_ydiaeresis = 0x00ff; /* U+00FF LATIN SMALL LETTER Y WITH DIAERESIS */
]]
-- Only the western characters (default ones) are included here. This file can
-- be expanded at will, but was kept short to improve load times.
return ffi.C
|
-- SPDX-License-Identifier: BSD-3-Clause
--
-- @todo:
-- need to handle: on_pre_player_mined_item, on_robot_pre_mined,
-- on_entity_died, script_raised_entity_destroy
-- for performance at some point split things into active and inactive lists
local glog = require("scripts.glog")
local assemblers = require("scripts.assemblers")
local drills = require("scripts.drills")
script.on_init(function()
glog.init()
assemblers.init()
drills.init()
end)
---
-- Register a new set of matches to call the given function when entities are built
-- @param[inout] list Modify this list of filter definitions
-- @param[in] mod Module object that must have on_built_match containing a list of
-- entity names and on_built as a function to call when one is built
-- @return void
--
local function register_built_filters(list, mod)
for k, v in pairs(mod.on_built_match) do
table.insert(list, {
name = v,
fn = mod.on_built
})
end
end
---
-- Convert our master filter list (which includes callbacks, for example) into a
-- filter that can be passed on_built to search for only the entities we care about
-- @param[in] filter Filter defined above, each entry has "name" at least which is an
-- entity name
-- @return filter table suitable for script.on_event
--
local function to_event_filter(filter)
local rtn = {}
for k, v in pairs(filter) do
table.insert(rtn, {filter = "name", name = v.name, mode = "or"})
end
return rtn
end
local all_filters = {}
register_built_filters(all_filters, drills)
register_built_filters(all_filters, assemblers)
---
-- Event handler for the on built class of events, which forwards to the appropriate
-- module to configure itself based on the entity name to callback relationships
-- established earlier
-- @param[in] event Event object/table with details
-- @return void
--
local function on_built(event)
local e = event.created_entity or event.entity
local found = false
if not e.valid then
return
end
for k,v in pairs(all_filters) do
if e.name == v.name then
v.fn(e)
found = true
end
end
if not found then
glog.log("filter matched entity named "..e.name.." without a matching handler")
end
end
---
-- Handle all of the built events the same way
-- @param fn Function to call when the entity was built
-- @param filter Filter to use for event registration
-- @return void
--
local function register_built_handler(fn, filter)
script.on_event(defines.events.on_built_entity, fn, filter)
script.on_event(defines.events.on_robot_built_entity, fn, filter)
script.on_event(defines.events.script_raised_built, fn, filter)
script.on_event(defines.events.script_raised_revive, fn, filter)
end
---
-- Called once per tick to do updates
-- @param event Event representing the tick
-- @return void
--
local function on_tick_handler(event)
assemblers.on_tick()
drills.on_tick()
end
register_built_handler(on_built, to_event_filter(all_filters))
script.on_event(defines.events.on_tick, on_tick_handler)
local function on_load(event)
end
script.on_load(on_load)
|
local class = require("pl.class")
local tablex = require("pl.tablex")
local EventEmitter = require("core.EventEmitter");
---@class Quest : EventEmitter
---@field goals table<QuestGoal,boolean>
---@field state table<QuestGoal, boolean>
local M = class(EventEmitter)
function M:_init(GameState, id, config, player)
self:super();
self.id = id;
self.entityReference = config.entityReference;
self.config = tablex.update({
title = "Missing Quest Title",
description = "Missing Quest Description",
completionMessage = nil,
requires = {},
level = 1,
autoComplete = false,
repeatable = false,
rewards = {},
goals = {},
}, config);
self.player = player;
self.goals = {};
self.state = {};
self.GameState = GameState;
end
function M:emit(event, ...)
EventEmitter.emit(self, event, ...)
if event == "progress" then return end
tablex.foreach(self.goals, function(_, goal, ...) goal:emit(event, ...) end,
...)
end
function M:addGoal(goal)
self.goals[goal] = true
goal:on("progress", function() self:onProgressUpdated() end)
end
function M:onProgressUpdated()
local progress = self:getProgress()
if progress.percent >= 100 then
if self.config.autoComplete then
self:complete()
else
self:emit("turn-in-ready")
end
return
end
self:emit("progress", progress)
end
function M:getProgress()
local overallPercent = 0;
local overallDisplay = {};
tablex.foreach(self.goals, function(_, goal)
local goalProgress = goal:getProgress()
overallPercent = overallPercent + goalProgress.percent
overallDisplay[#overallDisplay + 1] = goalProgress.dispaly
end)
return {
percent = math.floor(overallPercent / tablex.size(self.goals)),
display = table.concat(overallDisplay, "\r\n"),
};
end
function M:serialize()
return {
state = tablex.imap(function(goal) return goal:serialize() end,
tablex.keys(self.goals)),
progress = self:getProgress(),
config = {
desc = self.config.desc,
level = self.config.level,
titlex = self.config.title,
},
};
end
function M:hydrate()
tablex.foreach(self.state, function(goalState, i)
self.goals[i]:hydrate(goalState.state)
end)
end
function M:complete()
self:emit("complete")
for _, goal in ipairs(self.goals) do goal:complete() end
end
return M
|
--- Http library. Requests content from urls.
-- @shared
local http_library, _ = SF.Libraries.Register("http")
local http_interval = CreateConVar("sf_http_interval", "0.5", {FCVAR_ARCHIVE, FCVAR_REPLICATED}, "Interval in seconds in which one http request can be made")
local http_max_active = CreateConVar("sf_http_max_active", "3", {FCVAR_ARCHIVE, FCVAR_REPLICATED}, "The maximum amount of active http requests at the same time")
SF.Libraries.AddHook("initialize", function(instance)
instance.data.http = {
nextRequest = 0,
active = 0
}
end)
-- Raises an error when a http request was already triggered in the current interval
-- or if the maximum amount of simultaneous requests is currently active
local function httpRequestReady()
if not http_library.canRequest() then
SF.throw("You can't run a new http request yet", 2)
end
local httpData = SF.instance.data.http
httpData.active = httpData.active + 1
httpData.nextRequest = CurTime() + http_interval:GetFloat()
end
-- Runs the appropriate callback after a http request
local function runCallback(instance, callback, ...)
local httpData = instance.data.http
httpData.active = httpData.active - 1
if callback then
if IsValid(instance.data.entity) and not instance.error then
local ok, msg, tb = instance:runFunction(callback, ...)
if not ok then
instance:Error("http callback errored with: " .. msg, tb)
end
end
end
end
--- Checks if a new http request can be started
function http_library.canRequest()
local httpData = SF.instance.data.http
return httpData.nextRequest <= CurTime() and httpData.active < http_max_active:GetInt()
end
--- Runs a new http GET request
-- @param url http target url
-- @param callbackSuccess the function to be called on request success, taking the arguments body (string), length (number), headers (table) and code (number)
-- @param callbackFail the function to be called on request fail, taking the failing reason as an argument
function http_library.get(url, callbackSuccess, callbackFail)
SF.CheckType(url, "string")
SF.CheckType(callbackSuccess, "function")
if callbackFail ~= nil then
SF.CheckType(callbackFail, "function")
end
httpRequestReady()
http.Fetch(url, function(body, len, headers, code)
runCallback(instance, callbackSuccess, body, len, headers, code)
end, function (err)
runCallback(instance, callbackFail, err)
end)
end
--- Runs a new http POST request
-- @param url http target url
-- @param params POST parameters to be sent
-- @param callbackSuccess the function to be called on request success, taking the arguments body (string), length (number), headers (table) and code (number)
-- @param callbackFail the function to be called on request fail, taking the failing reason as an argument
function http_library.post(url, params, callbackSuccess, callbackFail)
SF.CheckType(url, "string")
SF.CheckType(callbackSuccess, "function")
if callbackFail ~= nil then
SF.CheckType(callbackFail, "function")
end
if params ~= nil then
SF.CheckType(params, "table")
for key, val in pairs(params) do
if type(key) .. type(val) ~= "stringstring" then
SF.throw("POST parameters can only contain string keys and values", 2)
end
end
end
httpRequestReady()
http.Post(url, params, function(body, len, headers, code)
runCallback(instance, callbackSuccess, body, len, headers, code)
end, function (err)
runCallback(instance, callbackFail, err)
end)
end
|
Script.Load("lua/Badges_Shared.lua")
local ClientId2Badges = {}
--cache owned badges
local ownedBadges = {}
--Assign badges to client based on the hive response
function Badges_FetchBadges(_, response)
local badges = response or {}
for _, badgeid in ipairs(gDLCBadges) do
local data = Badges_GetBadgeData(badgeid)
if GetHasDLC(data.productId) then
badges[#badges + 1] = gBadges[badgeid]
end
end
for _, badge in ipairs(badges) do
local badgeid = rawget(gBadges, badge)
local data = Badges_GetBadgeData(badgeid)
ownedBadges[badgeid] = data.columns
end
Badges_ApplyHive1Badges(response)
end
--Returns lookup table of by the client owned badges
function Badges_GetOwnedBadges()
return ownedBadges
end
local textures = {}
local badgeNames = {}
Client.HookNetworkMessage("DisplayBadge",
function(msg)
if not ClientId2Badges[msg.clientId] then
ClientId2Badges[ msg.clientId ] = {}
for i = 1, 10 do
ClientId2Badges[msg.clientId][i] = 1
end
end
ClientId2Badges[msg.clientId][msg.column] = msg.badge
--reset textures
textures[msg.clientId] = nil
badgeNames[msg.clientId] = nil
end)
--Converts column bitmask into a list
function Badges_GetBadgeColumns(bitmask)
local columns = {}
local acc = 1
for i = 1, kMaxBadgeColumns do
if bit.band(bitmask, acc) ~= 0 then
columns[#columns+1] = i
end
acc = acc * 2
end
return columns
end
--cache non empty columns
local selectedRows = {}
Client.HookNetworkMessage("BadgeRows",
function(msg)
if msg.columns == 0 then
ownedBadges[msg.badge] = nil
else
ownedBadges[msg.badge] = msg.columns
--Check for empty columns and autoselect avaible badge
local columns = Badges_GetBadgeColumns(msg.columns)
for i = 1, #columns do
local column = columns[i]
if not selectedRows[column] then
local badge = Client.GetOptionString( string.format("Badge%s", column), "" )
if badge == "" or badge == "none" then
SelectBadge(msg.badge, column)
break
else
selectedRows[column] = true
end
end
end
end
end)
Client.HookNetworkMessage("BadgeName",
function(msg)
Badges_SetName(msg.badge, msg.name)
end)
function Badges_GetBadgeTextures( clientId, usecase )
local badges = ClientId2Badges[clientId]
if badges then
if not textures[clientId] then
textures[clientId] = {}
badgeNames[clientId] = {}
for _, badge in ipairs(badges) do
local data = Badges_GetBadgeData(badge)
local textureTyp = usecase == "scoreboard" and "scoreboardTexture" or "unitStatusTexture"
if data then
textures[clientId][#textures[clientId] + 1] = data[textureTyp]
badgeNames[clientId][#badgeNames[clientId] + 1] = data.name
end
end
end
return textures[clientId], badgeNames[clientId]
else
return {}, {}
end
end
-- temp cache of often used function
local StringFormat = string.format
function SelectBadge(badgeId, column)
Client.SetOptionString( StringFormat( "Badge%s", column ), gBadges[badgeId] )
if Client.GetIsConnected() then
Client.SendNetworkMessage( "SelectBadge", BuildSelectBadgeMessage(badgeId, column), true)
end
end
local function OnConsoleBadge( badgename, column)
column = tonumber( column )
local badgeid = table.contains(gBadges, badgename) and gBadges[badgename]
if not column or column < 0 or column > 10 then column = 5 end
local sSavedBadge = Client.GetOptionString( StringFormat( "Badge%s", column ), "" )
if StringTrim( badgename ) == "" then
Print( StringFormat( "Saved Badge: %s", sSavedBadge or "none" ))
elseif badgename == "-" or badgeid and badgeid == 1 then
SelectBadge( gBadges.none, column )
elseif badgename == sSavedBadge then
Print( "You already have selected the requested badge" )
elseif badgeid and ownedBadges[badgeid] then
SelectBadge( badgeid, column )
else
Print( "Either you don't own the requested badge at this server or it doesn't exist." )
end
end
Event.Hook( "Console_badge", OnConsoleBadge)
function Badges_ApplyHive1Badges(badges)
local hiveOneApplied = Client.GetOptionBoolean( "Hive1BadgesConverted", false )
if hiveOneApplied then return end
Client.SetOptionBoolean( "Hive1BadgesConverted", true )
for i = 1, 3 do
if rawget(gBadges, badges[i]) then
SelectBadge(gBadges[badges[i]], 6 + i)
end
end
if badges[#badges] == "pax2012" then
SelectBadge(gBadges.pax2012, 10)
end
end
local function OnLoadComplete()
for i = 1, 10 do
local sSavedBadge = Client.GetOptionString( StringFormat("Badge%s", i), "" )
if sSavedBadge and sSavedBadge ~= "" and Client.GetIsConnected() then
local badgeid = table.contains(gBadges, sSavedBadge) and gBadges[sSavedBadge]
if badgeid then
Client.SendNetworkMessage( "SelectBadge", BuildSelectBadgeMessage(badgeid, i), true)
end
end
end
end
Event.Hook( "LoadComplete", OnLoadComplete )
|
local ls = require"luasnip"
local c = ls.choice_node
local d = ls.dynamic_node
local f = ls.function_node
local i = ls.insert_node
local s = ls.s
local sn = ls.snippet_node
local t = ls.text_node
local fmt = require("luasnip.extras.fmt").fmt
local function split_path(path)
local parts = vim.split(path, "[./]", false)
return parts[#parts] or ""
end
local function endif()
-- This function represents a snippet choice for
-- 1) `end`ing
-- 2) `else...end`ing
-- 3) `elseif...then...end`ing
-- an `if statement. If using the `elseif`, the `end` can recursively call itself
-- such that another `elseif...then...end` or `else...end` can be used.
return sn(nil, {
c(1, {
t("end"),
sn(nil, {
t("else"),
t({"", "\t"}),
i(1),
t({"", "end"})
}),
sn(nil, {
t("elseif "),
i(1),
t({" then", "\t"}),
i(2),
t({"", ""}),
d(3, endif, {})
})
})
})
end
return {
s("req",
fmt([[local {} = require('{}')]], { f(function(import_name)
return split_path(import_name[1][1])
end, { 1 }), i(1) })
),
s("func",
fmt(
[[
{} {}({})
{}
end
]],
{
c(1, {
t("function"),
t("local function")
}),
i(2, "name"),
i(3),
i(0)
}
)
),
s("if",
fmt(
[[
if {} then
{}
{}
]],
{
i(1),
i(2),
d(3, endif, {})
}
)
),
s("use",
fmt(
[[use {{{}}}]],
{
c(1, {
sn(1, {
t(" '"),
i(1),
t("' ")
}),
sn(1, {
t(" '"),
i(1),
t({"',", "\tconfig = function() require'plugin/"}),
f(function(name)
return split_path(name[1][1])
end, { 1 }),
t({"' end", ""})
})
})
}
)
)
}
|
-- Impregnates a creature
local args = {...}
function impregnate ()
local victim = dfhack.gui.getSelectedUnit()
local genes
if (victim == nil) then
return
end
genes = victim.appearance.genes:new()
if (victim.relations.pregnancy_timer > 0) then
print('Already pregnant!')
return
end
victim.relations.pregnancy_genes = genes;
victim.relations.pregnancy_timer = 30;
if (victim.relations.lover_id == 0) then
victim.relations.pregnancy_caste = 0;
else
victim.relations.pregnancy_caste = 1;
end
end
dfhack.with_suspend(impregnate)
|
package("wayland")
set_homepage("https://wayland.freedesktop.org/")
set_description("Wayland is a protocol for a compositor to talk to its clients as well as a C library implementation of that protocol.")
set_license("MIT")
add_urls("https://wayland.freedesktop.org/releases/wayland-$(version).tar.xz")
add_versions("1.18.0", "4675a79f091020817a98fd0484e7208c8762242266967f55a67776936c2e294d")
add_resources("1.x", "protocols", "https://wayland.freedesktop.org/releases/wayland-protocols-1.20.tar.xz", "9782b7a1a863d82d7c92478497d13c758f52e7da4f197aa16443f73de77e4de7")
add_deps("meson", "libxml2", "libffi", "expat")
on_install("linux", function (package)
-- imports
import("package.tools.meson")
import("package.tools.autoconf")
import("lib.detect.find_file")
-- set environment variables
package:addenv("PATH", "bin")
local LD_LIBRARY_PATH = package:installdir("lib")
local PKG_CONFIG_PATH = path.joinenv({package:installdir("lib", "pkgconfig"), package:installdir("share", "pkgconfig")})
local ACLOCAL_PATH = package:installdir("share", "aclocal")
local ACLOCAL = "aclocal -I " .. package:installdir("share", "aclocal")
os.mkdir(package:installdir("share", "aclocal"))
-- build wayland
local configs = {"-Ddocumentation=false", "-Dc_link_args=-lm"}
local envs = meson.buildenvs(package)
envs.LD_LIBRARY_PATH = path.joinenv(table.join(LD_LIBRARY_PATH, envs.LD_LIBRARY_PATH))
envs.PKG_CONFIG_PATH = path.joinenv(table.join(PKG_CONFIG_PATH, envs.PKG_CONFIG_PATH))
envs.ACLOCAL_PATH = path.joinenv(table.join(ACLOCAL_PATH, envs.ACLOCAL_PATH))
envs.ACLOCAL = ACLOCAL
meson.install(package, configs, {envs = envs})
-- add links
local arch = package:is_arch("x86_64", "x64") and "x86_64" or "x86"
package:add("linkdirs", path.join("lib", arch .. "-linux-gnu"))
package:add("links", "wayland-client", "wayland-server", "wayland-cursor", "wayland-egl")
os.mv(package:installdir("lib", arch .. "-linux-gnu", "pkgconfig"), package:installdir("lib"))
-- install wayland-protocols
local protocol = assert(package:resourcedir("protocols"), "wayland-protocols not found!")
local configfile = find_file("configure.ac", path.join(protocol, "**"))
os.cd(path.directory(configfile))
envs = autoconf.buildenvs(package)
envs.LD_LIBRARY_PATH = path.joinenv(table.join(LD_LIBRARY_PATH, envs.LD_LIBRARY_PATH))
envs.PKG_CONFIG_PATH = path.joinenv(table.join(PKG_CONFIG_PATH, envs.PKG_CONFIG_PATH))
envs.ACLOCAL_PATH = path.joinenv(table.join(ACLOCAL_PATH, envs.ACLOCAL_PATH))
envs.ACLOCAL = ACLOCAL
autoconf.install(package, {}, {envs = envs})
end)
on_test(function (package)
os.vrun("wayland-scanner --version")
assert(package:has_cfuncs("wl_list_init", {includes = "wayland-util.h"}))
end)
|
local telescope_ok, telescope = pcall(require, "telescope")
if not telescope_ok then
return
end
local trouble_ok, trouble = pcall(require, "trouble")
if not trouble_ok then
return
end
telescope.setup({
defaults = {
border = true,
layout_strategy = "bottom_pane",
layout_config = {
height = 0.30,
width = 1.00,
},
-- path_display = { "shorten" },
sorting_strategy = "ascending",
},
})
trouble.setup({
icons = false,
})
|
--
-- Created by IntelliJ IDEA.
-- User: hexaquat
-- Date: 08/11/17
-- Time: 17:48
-- To change this template use File | Settings | File Templates.
--
print("run shaders");
vertex_shader:main();
fragment_shader:main();
|
local skynet = require "skynet"
local env = require "faci.env"
local agent_info = require("agent.agent_info")
local service = env.service
function service.login(account)
-- 从数据库里加载数据
agent_info:init_agent(account.uid, 0, 1, "", 0, account, skynet.self())
agent_info:load_agent_info()
agent_info:update_agent_info()
agent_info:start_save_agent_info_timer(10)
return true
end
function service.logout(account)
agent_info:stop_save_agent_info_timer()
--是否要 取消 定时保存操作?
end
|
local Helper = require "datanet.helpers";
local Network = require "datanet.network";
local WorkerDaemon = require "datanet.daemon";
local Error = require "datanet.error";
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- CLASS DECLARATION --------------------------------------------------------
local _A = {};
_A.__index = _A;
-- AUTHORIZE-TYPE: [BASIC,READ,WRITE,STORE,SUBSCRIBE]
function _A.DoAuthorize(self, atype, kqk, rchans, schanid)
local jbody = Helper:CreateLocalAuthorizeJRB(atype, kqk, rchans, schanid);
local res, err = Helper:RunLocalClientMethod(jbody);
if (err ~= nil) then return nil, nil, err; end
local miss = res.miss;
local ok = res.ok;
-- READ & WRITE: NO CENTRAL REQUEST
local noc = (kqk ~= nil) and (rchans == nil) and (schanid == nil);
if (noc) then return res, miss, nil;
elseif (not miss) then return res, miss, nil;
else -- MISS: ASK CENTRAL
local config = WorkerDaemon.config;
local jreq = cjson.decode(jbody);
local id = jreq.id;
local abody = Helper:CreateAgentAuthorizeRequest(jreq);
local params = jreq.params;
local auth = params.authentication;
Helper:SetAuthentication(auth.username, auth.password);
local res, err = Network:SendCentralHttpsRequest(config, abody);
if (err ~= nil) then return nil, nil, err;
elseif (atype ~= "STORE") then return res, nil, nil;
else
local ok = Helper:HasAllWritePermissions(rchans, res.permissions);
local ares = {ok = ok};
return ares, nil, nil;
end
end
end
function _A.BasicAuthorize(self)
LT('Authorization:BasicAuthorize');
local err = Helper:CheckAuthentication();
if (err ~= nil) then return err; end
local ares, miss, err = self:DoAuthorize("BASIC", nil, nil, nil);
if (err ~= nil) then return err; end
if (not ares.ok) then return Error.BasicAuthFail; end
return nil;
end
function _A.KeyReadAuthorize(self, kqk)
LT('Authorization:KeyReadAuthorize');
local err = Helper:CheckAuthentication();
if (err ~= nil) then return err; end
local ares, miss, err = self:DoAuthorize("READ", kqk, nil, nil);
if (err ~= nil) then return err; end
if (not ares.ok) then
if (miss) then return Error.ReadNoDoc;
else return Error.ReadAuthFail;
end
end
return nil;
end
function _A.KeyCommitAuthorize(self, kqk)
LT('Authorization:KeyCommitAuthorize');
local err = Helper:CheckAuthentication();
if (err ~= nil) then return err; end
local ares, miss, err = self:DoAuthorize("WRITE", kqk, nil, nil);
if (err ~= nil) then return err; end
if (not ares.ok) then return Error.WriteAuthFail; end
return nil;
end
function _A.KeyStoreAuthorize(self, kqk, rchans)
LT('Authorization:KeyStoreAuthorize');
local err = Helper:CheckAuthentication();
if (err ~= nil) then return err; end
local ares, miss, err = self:DoAuthorize("STORE", kqk, rchans, nil);
if (err ~= nil) then return err; end
if (not ares.ok) then return Error.StoreAuthFail; end
return nil;
end
function _A.SubscribeAuthorize(self, schanid)
LT('Authorization:SubscribeAuthorize');
local ares, miss, err = self:DoAuthorize("SUBSCRIBE", nil, nil, schanid);
if (err ~= nil) then return err; end
if (not ares.ok) then return Error.SubscribeAuthFail; end
return nil;
end
return _A;
|
local skynet = require 'skynet'
return {
post = function(self)
if lwf.auth.user == 'Guest' then
ngx.print(_('You are not logined!'))
return
end
ngx.req.read_body()
local post = ngx.req.get_post_args()
local cjson = require 'cjson'
local inst = post.inst
local ext = post.ext
local version = post.version
assert(inst and ext)
assert(string.len(inst) > 0)
assert(string.len(ext) > 0)
local id = "from_web"
local args = {
version = version,
inst = inst,
name = ext,
}
skynet.call(".ioe_ext", "lua", "upgrade_ext", id, args)
ngx.print('Extension upgrade is done!')
end,
}
|
-- This overwrites a hash - intended for small hashes only
-- ARGV = [key, hkey1, hval1, (hkey2, hval2, ...)]
--
-- This will make the minimal changes required, not triggering
-- hset notifications for key<hkey:hval> pairs that arent modified
-- or hdel notifications unecessarily
local setkeys = {}
local hmset = {}
for i=2, #ARGV, 2 do
local value = redis.call('HGET', ARGV[1], ARGV[i])
if value ~= ARGV[i+1] then
hmset[#hmset + 1] = ARGV[i]
hmset[#hmset + 1] = ARGV[i+1]
end
setkeys[ARGV[i]] = true
end
local hkeys = redis.call('HKEYS', ARGV[1])
local hdel = {}
for i=1, #hkeys do
if not setkeys[hkeys[i]] then
hdel[#hdel + 1] = hkeys[i]
end
end
if #hdel > 0 then
redis.call('HDEL', ARGV[1], unpack(hdel))
end
if #hmset > 0 then
redis.call('HMSET', ARGV[1], unpack(hmset))
end
return 'OK'
|
---------------------------------------------------------------
-- Copyright 2020 Deviap (https://deviap.com/) --
---------------------------------------------------------------
-- Made available under the MIT License: --
-- https://github.com/deviap/sample-apps/blob/master/LICENSE --
---------------------------------------------------------------
print("Running " .. _VERSION .. " on device " .. _DEVICE)
-- Main container frame for this interface
local backdrop = core.construct("guiFrame", {
parent = core.interface,
size = guiCoord(1, 0, 1, 0),
backgroundColour = colour.rgb(255, 255, 255)
})
local triangles = {}
-- Create a 10x10 grid of triangles covering the screen
for x = 0, 1, 0.1 do
for y = 0, 1, 0.1 do
table.insert(triangles, core.construct("guiTriangle", {
parent = backdrop,
pointA = guiCoord(x, 0, y, 0),
pointB = guiCoord(x, 0, y + 0.1, 0),
pointC = guiCoord(x + 0.1, 0, y, 0),
backgroundColour = colour.random()
}))
end
end
while true do
-- 'flip' all the triangles
for _, v in pairs(triangles) do
core.tween:begin(v, 2, {
pointA = guiCoord(v.pointA.scale.x + 0.1, 0, v.pointA.scale.y + 0.1, 0)
}, "inOutQuad")
sleep()
end
sleep(0.125)
for _, v in pairs(triangles) do
core.tween:begin(v, 2, {
pointA = guiCoord(v.pointA.scale.x - 0.1, 0, v.pointA.scale.y - 0.1, 0)
}, "inOutQuad")
sleep()
end
sleep(0.125)
end
|
include("shared.lua")
function ENT:Initialize()
self.PixVis = util.GetPixelVisibleHandle()
self.Materials = {
"effects/halo3/fire_large",
"effects/halo3/fire_small",
"effects/halo3/muzzle_flash_round_fiery",
"effects/halo3/flash_large",
"effects/halo3/muzzle_flash_round_gaseous",
"effects/halo3/explosive_burst",
"effects/hce/plasma_noise",
"effects/hce/spark2",
"effects/hce/spark3",
"effects/hce/spark4",
"effects/halo_reach/plasma_mask",
"effects/halo_reach/pulse",
}
self.OldPos = self:GetPos()
self.emitter = ParticleEmitter(self.OldPos, false )
end
local mat = Material( "effects/halo3/fire_large" )
local rat = Material( "effects/halo3/electric_arcs" )
function ENT:Draw()
end
function ENT:Think()
local curtime = CurTime()
local pos = self:GetPos()
if pos ~= self.OldPos then
self:doFX( pos, self.OldPos )
self.OldPos = pos
end
return true
end
function ENT:doFX( newpos, oldpos )
if not self.emitter then return end
local Sub = (newpos - oldpos)
local Dir = Sub:GetNormalized()
local Len = Sub:Length()
for i = 1, Len, 10 do
local pos = oldpos + Dir * i
local particle = self.emitter:Add( self.Materials[math.random(1,12)], pos )
if particle then
particle:SetGravity( Vector(0,0,0) + VectorRand() * 150 )
particle:SetVelocity( -self:GetForward() * 500 )
particle:SetAirResistance( 200 )
particle:SetDieTime( math.Rand(0.1,0.1) )
particle:SetStartAlpha( 255 )
particle:SetStartSize( (math.Rand(6,12) / 20) * self:GetSize() )
particle:SetEndSize( (math.Rand(20,30) / 20) * self:GetSize() )
particle:SetRoll( math.Rand( -50, 50 ) )
particle:SetColor( 255,180,165 )
particle:SetCollide( false )
end
local particle = self.emitter:Add( rat, pos )
if particle then
particle:SetVelocity( -self:GetForward() * 1)
particle:SetDieTime( 0.3 )
particle:SetAirResistance( 0 )
particle:SetStartAlpha( 10 )
particle:SetStartSize( (math.Rand(50,100) / 1) )
particle:SetEndSize( 0 )
particle:SetRoll( math.Rand( -50, 50 ) )
particle:SetColor( 255,180,165 )
particle:SetGravity( Vector( 0, 0, 0 ) )
particle:SetCollide( false )
end
local particle = self.emitter:Add( "effects/halo3/8pt_ringed_star_flare", pos )
if particle then
particle:SetGravity( Vector(0,0,0) + VectorRand() * 50 )
particle:SetVelocity( -self:GetForward() * 1 )
particle:SetAirResistance( 600 )
particle:SetDieTime( math.Rand(0.1,0.5) )
particle:SetStartAlpha( 15 )
particle:SetStartSize( (math.Rand(25,25) / 5) * self:GetSize() )
particle:SetEndSize( (math.Rand(5,5) / 5) * self:GetSize() )
particle:SetRoll( math.Rand( -50, 50 ) )
particle:SetColor( 255,180,165 )
particle:SetCollide( false )
end
local particle = self.emitter:Add( "effects/halo3/8pt_ringed_star_flare", pos )
if particle then
particle:SetGravity( Vector(0,0,0) + VectorRand() * 50 )
particle:SetVelocity( -self:GetForward() * 1 )
particle:SetAirResistance( 600 )
particle:SetDieTime( math.Rand(0.1,0.3) )
particle:SetStartAlpha( 2 )
particle:SetStartSize( (math.Rand(25,25) / 1.5) * self:GetSize() )
particle:SetEndSize( (math.Rand(5,5) / 1.5) * self:GetSize() )
particle:SetRoll( math.Rand( -50, 50 ) )
particle:SetColor( 0,165,190 )
particle:SetCollide( false )
end
end
end
function ENT:OnRemove()
local effectdata = EffectData()
effectdata:SetOrigin( self:GetPos() )
util.Effect( self:GetBlastEffect(), effectdata )
if self.emitter then
self.emitter:Finish()
end
end
function ENT:Explosion( pos )
if not self.emitter then return end
for i = 0,60 do
local particle = self.emitter:Add( self.Materials[math.random(1,table.Count( self.Materials ))], pos )
if particle then
particle:SetVelocity( VectorRand() * 600 )
particle:SetDieTime( math.Rand(4,6) )
particle:SetAirResistance( math.Rand(200,600) )
particle:SetStartAlpha( 255 )
particle:SetStartSize( math.Rand(10,30) )
particle:SetEndSize( math.Rand(80,120) )
particle:SetRoll( math.Rand(-1,1) )
particle:SetColor( 100,100,100 )
particle:SetGravity( Vector( 0, 0, 100 ) )
particle:SetCollide( false )
end
end
for i = 0, 40 do
local particle = self.emitter:Add( "sprites/flamelet"..math.random(1,5), pos )
if particle then
particle:SetVelocity( VectorRand() * 500 )
particle:SetDieTime( 0.14 )
particle:SetStartAlpha( 255 )
particle:SetStartSize( 10 )
particle:SetEndSize( math.Rand(30,60) )
particle:SetEndAlpha( 100 )
particle:SetRoll( math.Rand( -1, 1 ) )
particle:SetColor( 200,150,150 )
particle:SetCollide( false )
end
end
local dlight = DynamicLight( math.random(0,9999) )
if dlight then
dlight.pos = pos
dlight.r = 255
dlight.g = 180
dlight.b = 100
dlight.brightness = 8
dlight.Decay = 2000
dlight.Size = 200
dlight.DieTime = CurTime() + 0.1
end
end
|
-- Zone: La Theine Plateau (102)
-- Desc: this file contains functions that are shared by multiple luas in this zone's directory
-----------------------------------
local ID = require("scripts/zones/La_Theine_Plateau/IDs");
require("scripts/globals/npc_util");
-----------------------------------
LA_THEINE_PLATEAU = {
--[[..............................................................................................
move the FallenEgg NPC. optionally hide for secondsHidden seconds.
..............................................................................................]]
moveFallenEgg = function(secondsHidden)
local fallenEggPositions =
{
[1] = {211.000, 24.000, 257.000},
[2] = {228.000, 25.000, 249.000},
[3] = {221.000, 24.000, 252.000},
[4] = {202.000, 23.000, 243.000},
[5] = {185.000, 21.000, 243.000},
[6] = {165.000, 16.000, 247.000},
[7] = {335.000, 40.000, 268.000},
[8] = {336.000, 40.000, 266.000},
[9] = {348.000, 40.000, 274.000},
[10] = {360.000, 40.000, 269.000},
[11] = {352.000, 40.000, 258.000},
[12] = {341.000, 40.000, 254.000},
[13] = {213.000, 24.000, 282.000},
[14] = {202.000, 24.000, 286.000},
[15] = {190.000, 23.000, 291.000},
[16] = {193.000, 24.000, 305.000},
[17] = {183.000, 23.000, 309.000},
[18] = {179.000, 23.000, 336.000},
[19] = {201.000, 24.000, 348.000},
[20] = {162.000, 24.000, 321.000},
[21] = {159.000, 22.000, 310.000},
[22] = {159.000, 17.000, 291.000},
[23] = {554.000, 24.000, 90.000},
[24] = {576.000, 24.000, 82.000},
[25] = {582.000, 23.000, 97.000},
[26] = {570.000, 23.000, 124.000},
[27] = {580.000, 23.000, 140.000},
[28] = {603.000, 23.000, 156.000},
[29] = {620.000, 24.000, 166.000},
[30] = {629.000, 26.000, 142.000},
[31] = {656.000, 30.000, 131.000},
[32] = {651.000, 31.000, 113.000},
[33] = {657.000, 31.000, 93.000},
[34] = {668.000, 31.000, 90.000},
[35] = {693.000, 30.000, 70.000},
[36] = {708.000, 30.000, 133.000},
[37] = {630.000, 24.000, 179.000},
[38] = {595.000, 24.000, 177.000},
[39] = {571.000, 24.000, 157.000},
[40] = {579.000, 40.000, -444.000},
[41] = {594.000, 40.000, -404.000},
[42] = {602.000, 40.000, -411.000},
[43] = {615.000, 39.000, -393.000},
[44] = {615.000, 37.000, -382.000},
[45] = {606.000, 39.000, -374.000},
[46] = {629.000, 40.000, -406.000},
[47] = {631.000, 40.000, -425.000},
[48] = {631.000, 40.000, -442.000},
[49] = {626.000, 40.000, -463.000},
[50] = {636.000, 40.000, -470.000},
[51] = {602.000, 40.000, -485.000},
[52] = {599.000, 40.000, -521.000},
[53] = {601.000, 40.000, -508.000},
[54] = {560.000, 24.000, -321.000},
[55] = {570.000, 26.000, -330.000},
[56] = {560.000, 24.000, -334.000},
[57] = {563.000, 24.000, -347.000},
[58] = {553.000, 24.000, -351.000},
[59] = {537.000, 24.000, -357.000},
[60] = {533.000, 25.000, -368.000},
[61] = {546.000, 25.000, -365.000},
[62] = {519.000, 24.000, -361.000}
}
local fallenEgg = GetNPCByID(ID.npc.FALLEN_EGG);
local newPosition = npcUtil.pickNewPosition(ID.npc.FALLEN_EGG, fallenEggPositions);
if (secondsHidden ~= nil and secondsHidden > 0) then
fallenEgg:hideNPC(secondsHidden);
end
fallenEgg:setPos(newPosition.x, newPosition.y, newPosition.z);
end
}
return LA_THEINE_PLATEAU;
|
--[[
Copyright 2014 Rackspace
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 {
require('./nginx_config'),
require('./connections'),
require('./iptables'),
require('./ip6tables'),
require('./autoupdates'),
require('./passwd'),
require('./pam'),
require('./cron'),
require('./kernel_modules'),
require('./cpu'),
require('./disk'),
require('./filesystem'),
require('./filesystem_state'),
require('./login'),
require('./memory'),
require('./network'),
require('./nil'),
require('./packages'),
require('./procs'),
require('./system'),
require('./who'),
require('./date'),
require('./sysctl'),
require('./sshd'),
require('./fstab'),
require('./fileperms'),
require('./services'),
require('./deleted_libs'),
require('./cve'),
require('./last_logins'),
require('./remote_services'),
require('./ip4routes'),
require('./ip6routes'),
require('./apache2'),
require('./fail2ban'),
require('./lsyncd'),
require('./wordpress'),
require('./magento'),
require('./php'),
require('./postfix'),
require('./hostname'),
require('./lshw')
}
|
local replacements = require "src.replacements"
local helper = require "test.helper"
-- luarocks install luaunit
luaunit = require('luaunit')
-- lua test/test_replacements.lua -v
TestReplacements = {} -- class
function TestReplacements:test_tansform_headers()
local headers = {
h1="v1",
h2={
"v21bla",
"v22bla"
},
h3="v3", -- headers are mode case insensitive by the system
location="http://internal-server.abc:1234/dir/"
}
local transformed_headers_expected = {
h1="v1",
h2={
"v2new1bla",
"v2new2bla"
},
h3="v3new",
location="https://external-server.tld/"
}
local header_replace_patterns = {
"h2:v2###v2new",
"h3:v3###v3new",
"location:http://internal%-server%.abc:1234/dir/###https://external-server.tld/"
}
replacements.tansform_headers(headers, header_replace_patterns)
luaunit.assertTrue(helper.deepcompare(headers, transformed_headers_expected, true))
luaunit.assertEquals(replacements.tansform_headers(nil, nil), nil)
luaunit.assertEquals(replacements.tansform_headers(headers, nil), headers)
end
function TestReplacements:test_matches_one_of()
local uri_patterns_empty = {}
local uri_patterns_one = { "bc" }
local uri_patterns_many = { "abc", "%.html$" }
local uri1 = "blabla"
local uri2 = "test.html"
local uri3 = "abc"
luaunit.assertFalse(replacements.matches_one_of(uri1, uri_patterns_empty))
luaunit.assertFalse(replacements.matches_one_of(uri1, uri_patterns_one))
luaunit.assertFalse(replacements.matches_one_of(uri1, uri_patterns_many))
luaunit.assertFalse(replacements.matches_one_of(uri2, uri_patterns_empty))
luaunit.assertFalse(replacements.matches_one_of(uri2, uri_patterns_one))
luaunit.assertTrue(replacements.matches_one_of(uri2, uri_patterns_many))
luaunit.assertFalse(replacements.matches_one_of(uri3, uri_patterns_empty))
luaunit.assertTrue(replacements.matches_one_of(uri3, uri_patterns_one))
luaunit.assertTrue(replacements.matches_one_of(uri3, uri_patterns_many))
luaunit.assertFalse(replacements.matches_one_of(uri1, nil))
end
function TestReplacements:test_transform_body()
local replace_patterns_empty = {}
local replace_patterns = { "abc###123", "xyz###DEF" }
local body = "xabcdefghijklmnopqrstuvwxyzx-x123defghijklmnopqrstuvwDEFx"
local body_transformed_expected = "x123defghijklmnopqrstuvwDEFx-x123defghijklmnopqrstuvwDEFx"
luaunit.assertEquals(body, replacements.transform_body(replace_patterns_empty, body))
luaunit.assertEquals(body_transformed_expected, replacements.transform_body(replace_patterns, body))
luaunit.assertEquals(body, replacements.transform_body(nil, body))
end
function TestReplacements.test_is_content_type()
local content_types_empty = {}
local content_types = { "abc", "def" }
luaunit.assertFalse(replacements.is_content_type("testvalue", content_types_empty))
luaunit.assertFalse(replacements.is_content_type("testvalue", content_types))
luaunit.assertTrue(replacements.is_content_type("abc", content_types))
luaunit.assertFalse(replacements.is_content_type("abcdef", content_types))
luaunit.assertTrue(replacements.is_content_type("abc; xyz", content_types))
luaunit.assertTrue(replacements.is_content_type("abc ; xyz", content_types))
luaunit.assertTrue(replacements.is_content_type(" abc ; xyz", content_types))
luaunit.assertTrue(replacements.is_content_type("def;xyz", content_types))
luaunit.assertFalse(replacements.is_content_type(nil, nil))
luaunit.assertFalse(replacements.is_content_type(nil, content_types))
luaunit.assertFalse(replacements.is_content_type("aaa", nil))
end
os.exit( luaunit.LuaUnit.run() )
|
--------------------------------
-- @module ToggleVisibility
-- @extend ActionInstant
--------------------------------
-- @function [parent=#ToggleVisibility] create
-- @param self
-- @return ToggleVisibility#ToggleVisibility ret (return value: cc.ToggleVisibility)
--------------------------------
-- @function [parent=#ToggleVisibility] clone
-- @param self
-- @return ToggleVisibility#ToggleVisibility ret (return value: cc.ToggleVisibility)
--------------------------------
-- @function [parent=#ToggleVisibility] update
-- @param self
-- @param #float float
--------------------------------
-- @function [parent=#ToggleVisibility] reverse
-- @param self
-- @return ToggleVisibility#ToggleVisibility ret (return value: cc.ToggleVisibility)
return nil
|
--[[-- variables type --]]
print(type("Hello, world!"))
print(type(1.4 * 3))
print(type(print))
print(type(type))
print(type(true))
print(type(nil))
print(type(type(_not_exists_variable)))
--[[-- common operations --]]
do
local a = {x = 1}
local b = {x = 1}
print(a == b) --> false (different pointers)
print(a == a) --> true (the same pointers)
print("123" < "1234") --> true
print(123 < 1234) --> true
end
do
local x = 1
local y = 2
local max = (x > y) and x or y;
print(max) --> 2
end
do
local x, y = 1, 2
y, x = x, y --> swap values
print(x) --> 2
end
--[[-- tables --]]
do
local d = {}
d["name"] = "Ivan"
d["surname"] = "Ivanov"
print(d.name, d.surname) --> Ivan Ivanov
end
do
local d = {name = "Ivan", surname = "Ivanov"}
print(d.name, d.surname) --> Ivan Ivanov
end
do
local d = {}
for i = 1, 10 do
d[#d + 1] = i
end
print(#d) --> 10
end
do
local some_table = {x=10, y=20}
print(some_table["x"]) --> 10
print(some_table.x) --> 10
some_table.x = nil --> remove field 'x'
print(some_table.x) --> nil
end
do
-- implement `linked list` with the `tables` mechanism
local list = nil
for i = 1, 3 do
list = {next=list, value=i}
end
local current_node = list
while current_node do
print(current_node.value)
current_node = current_node.next
end
end
do
local poly_line = {
color = "blue",
{x = 0, y = 0}
};
print(poly_line.color)
print(poly_line[1].x)
-- initialize table with non proper keys
local opnames = {
["+"] = "add",
["-"] = "sub",
["*"] = "mul",
["/"] = "div",
}
end
do
local d = {x = 1, y = 2, z = 3}
for key, value in pairs(d) do
print(key, value)
end
end
do
local network = {
{name = "grauna", ip = "210.26.30.34"},
{name = "arraial", ip = "210.26.30.23"},
{name = "lua", ip = "210.26.23.12"},
{name = "derain", ip = "210.26.23.20"},
}
table.sort(network, function (a, b) return a.name > b.name; end)
for _, item in ipairs(network) do
print(item.name, item.ip)
end
end
do
print(table.concat({"one", "two"}, " "))
local s = "abcde"
print(string.byte(s, 1, #s))
print(s:byte(1, -1))
print(table.concat({s:byte(1, -1)}, " "))
end
do
local t = {}
for i = 1, 10, 1 do
t[i] = i
end
print("t[1]: " .. t[1]) --> 1
print("#t: " .. #t) --> 10
table.insert(t, 1, 0)
print("t[1]: " .. t[1]) --> 0
print("#t: " .. #t) --> 11
print("table.concat(t, ', '): " .. table.concat(t, ', ')) --> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
table.remove(t, 1)
print("table.concat(t, ', '): " .. table.concat(t, ', ')) --> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
end
--[[-- strings --]]
do
local s = "Hello, "
print(s) --> Hello
print(s .. "world!") --> Hello, world!
print("Hello, " .. "world!")
print(1 .. 2) --> converts to the string and concatenates
end
do
local s = "Some random string with random words"
for word in string.gmatch(s, "[a-zA-Z]+") do
print(word)
end
end
do
print([[a multi line
message]])
-- secure option for automatically quoting long strings
print([=[asdasdasd"asd'asd]=])
end
do
local quote = "my some Random"
print(quote) --> my some Random
print(#quote) --> 14
print(string.len(quote)) --> 14
print(string.gsub(quote, "my", "your")) --> your some Random 1
print(string.find(quote, "Random")) --> 9 14
print(string.upper(quote)) --> MY SOME RANDOM
print(string.lower(quote)) --> my some random
print(tonumber("123")) --> 123
print(tonumber("123asd")) --> nil
print(string.format("5 + 2 = %d", 7)) --> 5 + 2 = 7
print "without braces" --> without braces
print {i = 1, j = 2}
for matched in string.gmatch(quote, "my") do
print(matched)
end
end
do
local function split (value, pattern)
local result = {}
for word in string.gmatch(value, pattern) do
table.insert(result, word)
end
return result
end
print(table.concat(split("some random with words", "[^%s]+"), ", ")) --> some, random, with, words
end
--[[-- arrays --]]
do
local some_array = {1, 2, 3 ,4}
end
do
local arr = {11, 22, 33, 44}
for i, value in ipairs(arr) do
print(i, value)
end
end
do
local days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}
local reverse_days = {}
for key, value in pairs(days) do
reverse_days[value] = key --> values are indicies numbers 1, 2, 3, ...
end
end
--[[-- functions --]]
do
local function factorial (n)
if n == 0 then
return 1
else
return n * factorial(n - 1)
end
end
print(factorial(3))
end
do
local function add (a)
local sum = 0
for _, value in ipairs(a) do
sum = sum + value
end
return sum
end
print(add({1, 2, 3, 4}))
end
do
local function unpack (list, i)
local i = i or 1
if list[i] then
return list[i], unpack(list, i + 1)
end
end
local d = {1, 2, 3}
local a, b, c = unpack(d)
print(a, b, c) --> 1 2 3
end
do
local function add (...)
local result = 0
for _, value in ipairs({...}) do
result = result + value
end
return result
end
print(add(1, 2, 3, 4)) --> 10
end
do
local function foo (...)
local a, b = ...
print(a, b) --> 1 2
end
foo(1, 2, 3)
end
do
local function interate_on_vararg (...)
for i = 1, select('#', ...) do -- iterate over total numbers of the args
local arg = select(i, ...)
print(arg)
end
end
interate_on_vararg(1, 2, 3)
end
do
-- clojures
local function counter()
local i = 0
return function ()
i = i + 1
return i
end
end
local c = counter()
print(c())
print(c())
end
do
local function chain_print (...)
print(...)
return chain_print
end
chain_print (1) ("alpha") (2) ("beta") (3) ("gamma")
chain_print (1) "alpha" (2) "beta" (3) "gamma"
end
do
local function is_valid_type (param)
local types = {
"self",
"table",
"nil",
"boolean",
"number",
"string"
}
for i = 1, #types do
if types[i] == param then
return true
end
end
return false
end
local function check_arguments (...)
local arguments_count = select("#", ...)
if arguments_count % 2 ~= 0 then
error("Error! Wrong arguments count `" .. arguments_count .. "' (must be even)")
end
for i = 1, arguments_count, 2 do
local expected_type, value = select(i, ...)
if not is_valid_type(expected_type) then
error("Error! Requested wrong data type: `" .. expected_type .. "'")
end
if type(value) ~= expected_type then
error("bad argument #" .. ((i + 1) / 2) .. " type: expected `" .. expected_type ..
"', got `" .. type(value) .. "'")
end
end
end
local function function_with_check_arguments (s, n)
check_arguments(
"string", s,
"number", n
)
print("s = " .. s .. ", n = " .. n)
end
function_with_check_arguments("q", 1)
end
--[[-- iterators --]]
do
local function values (list)
local i = 0
return function ()
i = i + 1
return list[i]
end
end
for value in values{1, 2, 3} do
print(value)
end
end
do
local lines = [[one two
three
four five
six
]]
local function all_words(lines)
local lines_iterator = string.gmatch(lines, "[^\n]+")
local line = lines_iterator()
local pos = 1
return function ()
while line do
local s, e = string.find(line, "%w+", pos)
if s then
pos = e + 1
return string.sub(line, s, e)
else
line = lines_iterator()
pos = 1
end
end
return nil
end
end
for word in all_words(lines) do
print(word)
end
end
-- stateless iterators
do
local function iter (array, i)
i = i + 1
local value = array[i]
if value then
return i, value
end
end
local function ipairs (array)
return iter, array, 0
end
end
--[[-- exceptions --]]
do
assert(true, "wrong value!")
local function always_error ()
error("always throw error")
end
-- always_error() --> throw an error
local result, errorMessage = pcall(always_error) --> suppress an error
print(result, errorMessage)
end
--[[-- coroutines --]]
do
local co = coroutine.create(function () print("Hello!") end)
print(co)
print(coroutine.status(co)) --> suspended
coroutine.resume(co)
print(coroutine.status(co)) --> dead
end
do
local co = coroutine.create(function ()
for i = 1, 2 do
print("co", i)
coroutine.yield(i)
end
return nil
end)
print(coroutine.resume(co))
print(coroutine.resume(co))
print(coroutine.resume(co))
end
do
local co = coroutine.create(function (a, b)
while (true) do
coroutine.yield(a + b)
end
return nil
end)
print(coroutine.resume(co, 1, 2)) -- true 3
end
--[[-- modules --]]
do
-- global environment _G
for n in pairs(_G) do print(n) end
end
do
-- which modules loaded in that session
for key, value in pairs(package.loaded) do
print(key)
end
end
do
-- force to unload package
-- package.loaded["io"] = nil
-- load package again
-- require "io"
-- where Lua searches modules
-- print(package.path)
end
do
local convert = require "convert"
print(convert.ft_to_cm(12)) --> 42.48
end
--[[-- metatables --]]
--[[--
__add(a, b) for a + b
__sub(a, b) for a - b
__mul(a, b) for a * b
__div(a, b) for a / b
__mod(a, b) for a % b
__pow(a, b) for a ^ b
__unm(a) for -a
__concat(a, b) for a .. b
__len(a) for #a
__eq(a, b) for a == b
__lt(a, b) for a < b
__le(a, b) for a <= b
__index(a, b) <fn or a table> for a.b
__newindex(a, b, c) for a.b = c
__call(a, ...) for a(...)
--]]
do
-- Lua create new tables without metatables
local d = {}
assert(getmetatable(d) == nil)
-- Set new metable d2 for the table d
local d2 = {}
setmetatable(d, d2)
assert(getmetatable(d) == d2)
-- metatables have only tables and strings
print(getmetatable("hi"))
end
do
local Set = {}
function Set.new (array)
local result = setmetatable({}, Set.metatable)
for _, value in ipairs(array) do
result[value] = true
end
return result
end
function Set.check_table (table1)
if getmetatable(table1) ~= Set.metatable then
error("Set operations must be on tables only!", 2)
end
end
function Set.union (table1, table2)
Set.check_table(table1)
Set.check_table(table2)
local result = Set.new{}
for key, _ in pairs(table1) do result[key] = true end
for key, _ in pairs(table2) do result[key] = true end
return result
end
function Set.intersection (table1, table2)
Set.check_table(table1)
Set.check_table(table2)
local result = Set.new{}
for key, _ in pairs(table1) do result[key] = table2[key] end
return result
end
function Set.tostring (set)
Set.check_table(set)
local result = {}
for key, _ in pairs(set) do result[#result + 1] = key end
return "{" .. table.concat(result, ", ") .. "}"
end
Set.metatable = {
__add = Set.union,
__mul = Set.intersection,
__tostring = Set.tostring,
}
local s1 = Set.new{10, 20, 30}
local s2 = Set.new{20, 1}
assert(getmetatable(s1) == getmetatable(s2))
local s3 = s1 + s2
print(s3)
local s4 = s1 * s2
print(s4)
end
do
-- prototypes
local Window = {}
Window.prototype = {x = 0, y = 0, width = 100, height = 100}
Window.metatable = {}
function Window.new (o)
setmetatable(o, Window.metatable)
return o
end
Window.metatable.__index = function (table, key) -- when Lua can't find key in the table
return Window.prototype[key]
end
-- shortcut for function before
-- when Lua can't find the key it try to call __index function if it's not nil
-- but whe Lua see that __index is a table Lua try to search key in that table
Window.metatable.__index = Window.prototype
-- the same as __index but for setting values
-- if it's a table the Lua set name/value to that table
-- otherwise, Lua call the __newindex if it's a function
Window.metatable.__newindex = Window.prototype
local window = Window.new{x = 10, y = 20}
print(window.height)
end
do
-- Object Oriented Programming
-- Base class
local Account = {
balance = 0
}
function Account:new (param)
local result = setmetatable(param or {}, self)
self.__index = self
return result
end
function Account:withdraw (value)
self.balance = self.balance - value
end
function Account:deposit (value)
self.balance = self.balance + value
end
a = Account:new({balance = 0})
a:deposit(100)
assert(a.balance == 100)
assert(Account.balance == 0)
a:withdraw(10)
assert(a.balance == 90)
assert(Account.balance == 0)
-- Derived class
local SpecialAccount = Account:new({limit = 1000})
function SpecialAccount:deposit (value)
self.balance = self.balance + value + 10
end
-- s uses SpecialAccount :deposit method
local s = SpecialAccount:new()
s:deposit(10)
assert(s.balance == 20)
assert(Account.balance == 0)
-- a uses Account :deposit method
a.balance = 0
a:deposit(100)
assert(a.balance == 100)
assert(Account.balance == 0)
end
do
concurrent = require 'concurrent'
function hello_world(times)
for i = 1, times do print('hello world') end
print('done')
end
concurrent.spawn(hello_world, 3)
concurrent.loop()
end
|
--[[
Copyright (c) 2015 Calvin Rose
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local lg = love.graphics
local EMPTY = {}
local function floor(x, y)
return math.floor(x / y) * y
end
local function mod(x, y)
return x - floor(x, y)
end
local function checkType(x, typename, name)
assert(
type(x) == typename,
"Expected "..name.." (type = "..type(x)..") to be a "..typename.."."
)
return x
end
local function unpackCamera(t)
local sx, sy, sw, sh
if t.getWindow then -- assume t is a gamera camera
sx, sy, sw, sh = t:getWindow()
else
sx, sy, sw, sh =
t.sx or 0,
t.sy or 0,
t.sw or lg.getWidth(),
t.sh or lg.getHeight()
end
return
t.x or 0,
t.y or 0,
t.scale or t.zoom or 1,
t.angle or t.rot or 0,
sx, sy, sw, sh
end
local DEFAULT_COLOR = {0.97, 0.97, 0.97}
local DEFAULT_X_COLOR = {1, 0, 0}
local DEFAULT_Y_COLOR = {0, 1, 0}
local function unpackVisuals(t, zoom)
local size = t.size or 256
if type(size) == "function" then
size = size(zoom)
end
local sds = t.subdivisions or 4
if type(sds) == "function" then
sds = sds(size, zoom)
end
local color = t.color or DEFAULT_COLOR
local drawScale
if t.drawScale == nil then
drawScale = true
else
drawScale = t.drawScale
end
local xColor = t.xColor or DEFAULT_X_COLOR
local yColor = t.yColor or DEFAULT_Y_COLOR
local fadeFactor = t.fadeFactor or 0.5
local textFadeFactor = t.textFadeFactor or 1.0
local hideOrigin = t.hideOrigin
return size, sds, drawScale, color, xColor, yColor, fadeFactor, textFadeFactor, hideOrigin
end
local function getGridInterval(visuals, zoom)
if visuals.interval then
return visuals.interval
else
local size, sds = unpackVisuals(visuals, zoom)
return size * math.pow(sds, -math.ceil(math.log(zoom, sds)))
end
end
local function visible(camera)
camera = checkType(camera or EMPTY, "table", "camera")
local camx, camy, zoom, angle, sx, sy, sw, sh = unpackCamera(camera)
local w, h = sw / zoom, sh / zoom
if angle ~= 0 then
local sin, cos = math.abs(math.sin(angle)), math.abs(math.cos(angle))
w, h = cos * w + sin * h, sin * w + cos * h
end
return camx - w * 0.5, camy - h * 0.5, w, h
end
local function toWorld(camera, screenx, screeny)
checkType(screenx, "number", "screenx")
checkType(screeny, "number", "screeny")
camera = checkType(camera or EMPTY, "table", "camera")
local camx, camy, zoom, angle, sx, sy, sw, sh = unpackCamera(camera)
local sin, cos = math.sin(angle), math.cos(angle)
local x, y = (screenx - sw/2 - sx) / zoom, (screeny - sh/2 - sy) / zoom
x, y = cos * x - sin * y, sin * x + cos * y
return x + camx, y + camy
end
local function toScreen(camera, worldx, worldy)
checkType(worldx, "number", "worldx")
checkType(worldy, "number", "worldy")
camera = checkType(camera or EMPTY, "table", "camera")
local camx, camy, zoom, angle, sx, sy, sw, sh = unpackCamera(camera)
local sin, cos = math.sin(angle), math.cos(angle)
local x, y = worldx - camx, worldy - camy
x, y = cos * x + sin * y, -sin * x + cos * y
return zoom * x + sw/2 + sx, zoom * y + sh/2 + sy
end
local function minorInterval(camera, visuals)
camera = checkType(camera or EMPTY, "table", "camera")
visuals = checkType(visuals or EMPTY, "table", "visuals")
local zoom = select(3, unpackCamera(camera))
return getGridInterval(visuals, zoom)
end
local function majorInterval(camera, visuals)
camera = checkType(camera or EMPTY, "table", "camera")
visuals = checkType(visuals or EMPTY, "table", "visuals")
local zoom = select(3, unpackCamera(camera))
local sds = select(2, unpackVisuals(visuals, zoom))
return sds * minorInterval(camera, visuals)
end
local function cellToWorld(camera, visuals, x, y)
local d = minorInterval(camera, visuals)
return math.floor(x) * d, math.floor(y) * d
end
local function cellToScreen(camera, visuals, x, y)
return cellToWorld(camera, visuals, toWorld(camera, x, y))
end
local function worldToCell(camera, visuals, x, y)
local d = minorInterval(camera, visuals)
return math.floor(x / d), math.floor(y / d)
end
local function screenToCell(camera, visuals, x, y)
return worldToCell(camera, visuals, toWorld(camera, x, y))
end
local function convertCoords(camera, visuals, src, dest, x, y)
checkType(x, "number", "x")
checkType(y, "number", "y")
camera = checkType(camera or EMPTY, "table", "camera")
visuals = checkType(visuals or EMPTY, "table", "visuals")
assert(
src == "screen" or src == "world" or src == "cell",
"Unrecognized src " .. tostring(src) .. "."
)
assert(
dest == "screen" or dest == "world" or dest == "cell",
"Unrecognized dest " .. tostring(dest) .. "."
)
if src == dest then return x, y end
if src == "screen" then
if dest == "cell" then
return screenToCell(camera, visuals, x, y)
else -- dest == "world"
return toWorld(camera, x, y)
end
elseif src == "cell" then
if dest == "screen" then
return cellToScreen(camera, visuals, x, y)
else -- dest == "world"
return cellToWorld(camera, visuals, x, y)
end
elseif src == "world" then
if dest == "cell" then
return worldToCell(camera, visuals, x, y)
else -- dest == "screen"
return toScreen(camera, x, y)
end
end
end
local function getCorners(camera)
local sx, sy, sw, sh = select(5, unpackCamera(camera))
local x1, y1 = toWorld(camera, sx, sy) -- top left
local x2, y2 = toWorld(camera, sx + sw, sy) -- top right
local x3, y3 = toWorld(camera, sx + sw, sy + sh) -- bottom right
local x4, y4 = toWorld(camera, sx, sy + sh) -- bottom left
return x1, y1, x2, y2, x3, y3, x4, y4
end
local function intersect(x1, y1, x2, y2, x3, y3, x4, y4)
local x21, x43 = x2 - x1, x4 - x3
local y21, y43 = y2 - y1, y4 - y3
local d = x21 * y43 - y21 * x43
if d == 0 then return false end
local xy34 = x3 * y4 - y3 * x4
local xy12 = x1 * y2 - y1 * x2
local a = xy34 * x21 - xy12 * x43
local b = xy34 * y21 - xy12 * y43
return a / d, b / d
end
local function drawLabel(camera, worldx, worly, label)
lg.push()
lg.origin()
local x, y = toScreen(camera, worldx, worly)
lg.printf(label, x + 2, y + 2, 400, "left")
lg.pop()
end
local function push(camera)
camera = checkType(camera or EMPTY, "table", "camera")
local camx, camy, zoom, angle, sx, sy, sw, sh = unpackCamera(camera)
lg.push()
lg.scale(zoom)
lg.translate((sw / 2 + sx) / zoom, (sh / 2 + sy) / zoom)
lg.rotate(-angle)
lg.translate(-camx, -camy)
end
local function pop()
lg.pop()
end
local function draw(camera, visuals)
camera = checkType(camera or EMPTY, "table", "camera")
visuals = checkType(visuals or EMPTY, "table", "visuals")
local camx, camy, zoom, angle, sx, sy, sw, sh = unpackCamera(camera)
local size, sds, ds, color, xColor, yColor, ff, tf, hideOrigin = unpackVisuals(visuals, zoom)
local x1, y1, x2, y2, x3, y3, x4, y4 = getCorners(camera)
local swapXYLabels = mod(angle + math.pi/4, math.pi) > math.pi/2
lg.setScissor(sx, sy, sw, sh)
local vx, vy, vw, vh = visible(camera)
local d = getGridInterval(visuals, zoom)
local delta = d / 2
push(camera)
local oldLineWidth = lg.getLineWidth()
lg.setLineWidth(1 / zoom)
-- lines parallel to y axis
local xc = sds
for x = floor(vx, d * sds), vx + vw, d do
if xc >= sds then
lg.setColor(color[1], color[2], color[3], 1)
xc = 1
else
lg.setColor(color[1] * ff, color[2] * ff, color[3] * ff, 1)
xc = xc + 1
end
lg.line(x, vy, x, vy + vh)
end
-- lines parallel to x axis
local yc = sds
for y = floor(vy, d * sds), vy + vh, d do
if yc >= sds then
lg.setColor(color[1], color[2], color[3], 1)
yc = 1
else
lg.setColor(color[1] * ff, color[2] * ff, color[3] * ff, 1)
yc = yc + 1
end
if math.abs(y) > delta then
lg.line(vx, y, vx + vw, y)
end
end
-- draw labels
for x = floor(vx, d * sds), vx + vw, d do
if math.abs(x) < delta then
lg.setColor(yColor[1] * tf, yColor[2] * tf, yColor[3] * tf, 1)
lg.line(x, vy, x, vy + vh)
else
lg.setColor(color[1] * tf, color[2] * tf, color[3] * tf, 1)
end
if ds then
local cx, cy
if swapXYLabels then
cx, cy = x4, y4
else
cx, cy = x2, y2
end
local ix, iy = intersect(x1, y1, cx, cy, x, vy, x, vy + vh)
if ix then
drawLabel(camera, ix, iy, "x=" .. x)
end
end
end
for y = floor(vy, d * sds), vy + vh, d do
if math.abs(y) < delta then
lg.setColor(xColor[1] * tf, xColor[2] * tf, xColor[3] * tf, 1)
lg.line(vx, y, vx + vw, y)
else
lg.setColor(color[1] * tf, color[2] * tf, color[3] * tf, 1)
end
if ds then
local cx, cy
if swapXYLabels then
cx, cy = x2, y2
else
cx, cy = x4, y4
end
local ix, iy = intersect(x1, y1, cx, cy, vx, y, vx + vw, y)
if ix then
drawLabel(camera, ix, iy, "y=" .. y)
end
end
end
lg.pop()
lg.setLineWidth(1)
-- draw origin
if not hideOrigin then
lg.setColor(1, 1, 1, 1)
local ox, oy = toScreen(camera, 0, 0)
lg.rectangle("fill", ox - 1, oy - 1, 2, 2)
lg.circle("line", ox, oy, 8)
end
lg.setLineWidth(oldLineWidth)
lg.setColor(1, 1, 1, 1)
lg.setScissor()
end
local gridIndex = {
toWorld = function (self, x, y) return toWorld(self.camera, x, y) end,
toScreen = function (self, x, y) return toScreen(self.camera, x, y) end,
convertCoords = function (self, src, dest, x, y)
return convertCoords(self.camera, self.visuals, src, dest, x, y)
end,
draw = function (self) return draw(self.camera, self.visuals) end,
minorInterval = function (self)
return minorInterval(self.camera, self.visuals)
end,
majorInterval = function (self)
return majorInterval(self.camera, self.visuals)
end,
visible = function (self) return visible(self.camera) end,
push = function (self) return push(self.camera) end
}
local gridMt = {
__index = gridIndex
}
local function grid(camera, visuals)
camera = checkType(camera or {}, "table", "camera")
visuals = checkType(visuals or {}, "table", "visuals")
return setmetatable({
camera = camera,
visuals = visuals
}, gridMt)
end
return {
toWorld = toWorld,
toScreen = toScreen,
convertCoords = convertCoords,
draw = draw,
visible = visible,
minorInterval = minorInterval,
majorInterval = majorInterval,
grid = grid,
push = push,
pop = pop,
}
|
--function containers
local game = {}
--variables
data = {}
aimable_spell = nil
direction = DIRECTIONS.none
--init
function game.new_game(class)
local class_factory = require("resources/script/classes")
local dun_gen = require("game/dungeon/dungeongen")
console.setFullscreen(config.fullscreen)
data.console_log = {}
--Welcome message
game.print("Welcome stranger, be prepared to perish in the tombs of LOVE!", colors.red)
local map, coords = dun_gen.generate(1)
data.map = map
data.player = class_factory[class](coords.x, coords.y)
data.camera = camera.init(78, 43)
data.player:visible_range()
for k,v in pairs(data.player.inventory) do
if v.equipment then
v.equipment:equip()
end
end
console.draw()
end
function game.save_game()
bitser.dumpLoveFile(SAVE_FILE, data)
game.print("Game Saved.")
end
function game.load_game()
if love.filesystem.isFile(SAVE_FILE) then
console.setFullscreen(config.fullscreen)
data = bitser.loadLoveFile(SAVE_FILE)
data.player:visible_range()
else
print("no save data could be found.")
end
console.draw()
end
function game.update()
for key,value in pairs(data.map.objects) do
if value.ai then
for k, v in pairs(value.fighter.invocations) do
v:invoke()
end
value.ai:take_turn()
end
end
for k, v in pairs(data.player.character.fighter.invocations) do
v:invoke()
end
if data.map.floor == END_FLOOR and data.map.monster_count <= 0 then
screenmanager.push("gameover", "A WINNER IS YOU!")
end
end
function game.next_level()
local dun_gen = require("game/dungeon/dungeongen")
game.print("You take a moment to rest...", colors.red)
local map, coords = dun_gen.generate(data.map.floor + 1)
data.map = map
data.player.character.x = coords.x
data.player.character.y = coords.y
data.player.character.fighter:heal(math.round(data.player.character.fighter:max_hp() / 2))
data.player:visible_range()
console.draw()
end
--console
function game.print(string, color)
print(string)
table.insert(data.console_log, {string, color})
end
--util
function fov_cast_light(row, cstart, cend, xx, xy, yx, yy, range)
local startx, starty = data.player.character.x, data.player.character.y
local radius = range
local start = cstart
local new_start = 0
if start < cend then
return
end
local width = table.maxn(data.map.tiles)
local height = table.maxn(data.map.tiles[1])
local blocked = false
for distance = row, radius do
local deltay = distance * -1
for deltax = distance * -1, 0 do
local currentx = startx + deltax * xx + deltay * xy
local currenty = starty + deltax * yx + deltay * yy
local leftslope = (deltax - .5) / (deltay +.5)
local rightslope = (deltax + .5) / (deltay - .5)
if not (currentx >= 0 and currenty >= 0 and currentx < width and currenty < height) or start < rightslope then
--Continue
elseif cend > leftslope then
break;
else
if math.circle_radius(deltax, deltay, 0) <= radius then
data.map.tiles[currentx][currenty].visibility = special_colors.fov_visible
end
if blocked then
if data.map.tiles[currentx][currenty].block_sight then
new_start = rightslope
--Continue
else
blocked = false
start = new_start
end
else
if data.map.tiles[currentx][currenty].block_sight and distance < radius then
blocked = true
fov_cast_light(distance + 1, start, leftslope, xx, xy, yx, yy, range)
new_start = rightslope
end
end
end
end
if blocked then
break
end
end
end
function random_choice(collection)
local sum = 0
for k,v in pairs(collection) do
sum = sum + v
end
local dice = love.math.random(1, sum)
sum = 0
for k,v in pairs(collection) do
sum = sum + v
if dice <= sum then
return k
end
end
end
return game
|
local fail = false
print("Test: rshift...")
if a8 >> a8 ~= uint.u8(0) then
print("\tFail: a8 >> a8 ~= 0")
fail = true
end
if b8 >> 4 ~= uint.u8(8) then
print("\tFail: b8 >> 4 ~= 8")
fail = true
end
if (9923 >> c8):asnumber() ~= 0 then
print("\tFail: 9 >> c8 ~= 0")
fail = true
end
if not fail then
print("\tPass")
end
|
local parser = require'pegparser.parser'
local first = require'pegparser.first'
local unique = require'pegparser.unique'
local pretty = require'pegparser.pretty'
local label = require'pegparser.label'
local ban = require'pegparser.ban'
local newNode = parser.newNode
local calcfirst = first.calcfirst
local disjoint = first.disjoint
local matchEmpty = parser.matchEmpty
local calck = first.calck
local labelgrammar = label.labelgrammar
local matchUnique = unique.matchUnique
local matchUPath = unique.matchUPath
local matchUniqueEq = unique.matchUniqueEq
local union = first.union
local calcfirst = first.calcfirst
local function annotateUniqueAux (g, p, seq, afterU, flw)
if ((p.tag == 'var' and not matchEmpty(p)) or p.tag == 'char' or p.tag == 'any') and seq and afterU then
return label.markerror(p, flw)
elseif ((p.tag == 'var' and not matchEmpty(p)) or p.tag == 'char' or p.tag == 'any') and p.uniqueEq then
return label.markerror(p, flw)
elseif p.tag == 'con' then
local p1 = annotateUniqueAux(g, p.p1, seq, afterU, calck(g, p.p2, flw))
local p2 = annotateUniqueAux(g, p.p2, seq or not matchEmpty(p.p1), afterU or matchUnique(g, p.p1), flw)
return newNode(p, p1, p2)
elseif p.tag == 'ord' then
local flagDisjoint = disjoint(calcfirst(g, p.p1), calck(g, p.p2, flw))
local p1 = annotateUniqueAux(g, p.p1, false, flagDisjoint and afterU, flw)
local p2 = annotateUniqueAux(g, p.p2, false, afterU, flw)
if seq and afterU and not matchEmpty(p) then
return label.markerror(newNode(p, p1, p2), flw)
else
return newNode(p, p1, p2)
end
elseif (p.tag == 'star' or p.tag == 'opt' or p.tag == 'plus') then
local flagDisjoint = disjoint(calcfirst(g, p.p1), flw)
--local newp = annotateUniqueAux(g, p.p1, false, flagDisjoint and afterU, flw)
if p.tag == 'star' or p.tag == 'plus' then
flw = union(calcfirst(g, p.p1), flw)
end
local newp = annotateUniqueAux(g, p.p1, false, flagDisjoint and afterU, flw)
if p.tag == 'star' or p.tag == 'opt' then
return newNode(p, newp)
else --plus
if seq and afterU then
return label.markerror(newNode(p, newp), flw)
else
return newNode(p, newp)
end
end
else
return p
end
end
local function annotateUnique (g)
local fst = first.calcFst(g)
local flw = first.calcFlw(g)
g.unique = unique.uniqueTk(g)
local newg = parser.initgrammar(g)
for i, v in ipairs(g.plist) do
if not parser.isLexRule(v) then
newg.prules[v] = annotateUniqueAux(g, g.prules[v], false, false, flw[v])
end
end
return newg
end
local function annotateUPathAux (g, p, seq, afterU, flw, afterUEq)
--print("UPathAux", p.tag, p.p1, seq, afterU, afterUEq)
if ((p.tag == 'var' and not matchEmpty(p)) or p.tag == 'char' or p.tag == 'any') and afterU and seq then
return label.markerror(p, flw)
elseif ((p.tag == 'var' and not matchEmpty(p)) or p.tag == 'char' or p.tag == 'any') and afterUEq and seq and p.uniqueEq then
print("addEq", p.p1, p.throw, g.symRule[p])
return label.markerror(p, flw)
elseif p.tag == 'con' then
--print("con", p.p1.tag, p.p2.tag, matchUniqueEq(p.p1))
local p1 = annotateUPathAux(g, p.p1, seq, afterU, calck(g, p.p2, flw), afterUEq)
seq = seq or not parser.matchEmpty(p.p1)
local p2 = annotateUPathAux(g, p.p2, seq, afterU or matchUPath(p.p1), flw, matchUniqueEq(p.p1))
return newNode(p, p1, p2)
elseif p.tag == 'ord' then
local flagDisjoint = disjoint(calcfirst(g, p.p1), calck(g, p.p2, flw))
local p1 = annotateUPathAux(g, p.p1, false, afterU and flagDisjont, flw, afterUEq and flagDisjoint)
local p2 = annotateUPathAux(g, p.p2, seq and p.p2.tag ~= 'ord', afterU, flw, afterUEq)
if afterU and not matchEmpty(p) and seq then
return label.markerror(newNode(p, p1, p2), flw)
else
return newNode(p, p1, p2)
end
--elseif (p.tag == 'star' or p.tag == 'opt' or p.tag == 'plus') and disjoint(calcfirst(g, p.p1), flw) then
--local newp = annotateUPathAux(g, p.p1, false, afterU, flw)
elseif (p.tag == 'star' or p.tag == 'opt' or p.tag == 'plus') then
local flagDisjoint = disjoint(calcfirst(g, p.p1), flw)
--local newp = annotateUPathAux(g, p.p1, false, flagDisjoint and afterU, flw)
local flwRep = flw
if p.tag == 'star' or p.tag == 'plus' then
flwRep = union(calcfirst(g, p.p1), flw)
end
local newp = annotateUPathAux(g, p.p1, false, afterU and flagDisjoint, flwRep, afterUEq and flagDisjoint)
if p.tag == 'star' or p.tag == 'opt' then
if afterU then
return label.markerror(newNode(p, newp), flw)
else
return newNode(p, newp)
end
else --plus
--if afterU and seq then
if afterU then
return label.markerror(newNode(p, newp), flwRep)
else
return newNode(p, newp)
end
end
else
return p
end
end
local function annotateUPath (g)
local fst = first.calcFst(g)
local flw = first.calcFlw(g)
unique.calcUniquePath(g)
local newg = parser.initgrammar(g)
for i, v in ipairs(g.plist) do
if not parser.isLexRule(v) then
newg.prules[v] = annotateUPathAux(g, g.prules[v], g.uniqueVar[v].upath, g.uniqueVar[v].seq, flw[v])
end
end
return newg
end
local function addlabAll (g, p, seq, flw)
if ((p.tag == 'var' and not matchEmpty(p)) or p.tag == 'char' or p.tag == 'any') and seq and not p.ban then
return label.markerror(p, flw)
elseif p.tag == 'con' then
local newseq = seq or not matchEmpty(p.p1)
--return newSeq(addlab(g, p.p1, seq, calck(g, p.p2, flw)), addlab(g, p.p2, newseq, flw))
return newNode(p, addlabAll(g, p.p1, seq, calck(g, p.p2, flw)), addlabAll(g, p.p2, newseq, flw))
elseif p.tag == 'ord' then
local flagDisjoint = disjoint(calcfirst(g, p.p1), calck(g, p.p2, flw))
local p1 = p.p1
--if flagDisjoint then
p1 = addlabAll(g, p.p1, false, flw)
--end
local p2 = addlabAll(g, p.p2, false, flw)
if seq and not matchEmpty(p) and not p.ban then
return label.markerror(newNode(p, p1, p2), flw)
else
return newNode(p, p1, p2)
end
elseif (p.tag == 'star' or p.tag == 'opt' or p.tag == 'plus') then --and disjoint(calcfirst(g, p.p1), flw) then
--local newp = addlabAll(g, p.p1, false, flw)
if p.tag == 'star' or p.tag == 'plus' then
flw = union(calcfirst(g, p.p1), flw)
end
local newp = addlabAll(g, p.p1, false, flw)
if p.tag == 'star' or p.tag == 'opt' then
return newNode(p, newp)
else --plus
if seq and not p.ban then
return label.markerror(newNode(p, newp), flw)
else
return newNode(p, newp)
end
end
else
return p
end
end
local function annotateAll (g)
local fst = first.calcFst(g)
local flw = first.calcFlw(g)
local newg = parser.initgrammar(g)
for i, v in ipairs(g.plist) do
if not parser.isLexRule(v) then
newg.prules[v] = addlabAll(g, g.prules[v], false, flw[v])
end
end
return newg
end
local function putlabels (g, f, rec)
if f == 'unique' then
return labelgrammar(annotateUnique(g), rec)
elseif f == 'upath' then
return labelgrammar(annotateUPath(g), rec)
elseif f == 'deep' then
ban.ban(g, f)
return labelgrammar(ban.annotateBan(g), rec)
elseif f == 'deepupath' then
ban.ban(g, 'deep')
local newg = ban.annotateBan(g)
return labelgrammar(annotateUPath(newg), rec) --tanto faz passar 'g' ou 'newg' (normalizar uso de funções que alteram ou não 'g')
elseif f == 'upathdeep' then
local newg = annotateUPath(g)
ban.ban(newg, 'upathdeep')
newg = ban.annotateBan(newg)
return labelgrammar(newg, rec)
elseif f == 'all' then -- regular
return labelgrammar(annotateAll(g), rec)
else -- regular
return labelgrammar(ban.annotateBan(g), rec)
end
end
return {
putlabels = putlabels,
}
|
return require "skynet.socketchannel"
|
local fs = require("stardust/filesystem")
local io = {}
function io.open(filename, mode)
if not fs.isDirectory(filename) then
local h, err = fs.open(filename, mode)
if not h then
return nil, err
end
return require("buffer").from(h)
end
return nil, "is directory"
end
function io.input(file)
if not file then
return io.stdin
else
if type(file) == "string" then -- file name
io.input(io.open(file, "r"))
else
local proc = require("tasks").getCurrentProcess()
proc.io.stdin = file
end
end
end
function io.output(file)
if not file then
return io.stdout
else
if type(file) == "string" then -- file name
io.input(io.open(file, "w"))
else
local proc = require("tasks").getCurrentProcess()
proc.io.stdout = file
proc.io.stderr = io.createStdErr() -- recreate stderr to be matching stdout
end
end
end
function io.flush()
if io.stdout.flush then -- if the stream is buffered
io.stdout:flush()
end
end
function io.read()
return io.stdin:read()
end
function io.close(file)
if file then
file:close()
else
io.stdout:close()
end
end
function io.type(obj)
if type(obj) == "table" then
if obj.closed then
return "closed file"
elseif (obj.read or obj.write) and obj.close then
return "file"
end
end
return nil
end
function io.write(msg)
io.stdout:write(tostring(msg))
end
io.stdin = _G.io.stdin
io.stdout = _G.io.stdout
io.stderr = _G.io.stderr
return io
|
--[[ Generated with https://github.com/TypeScriptToLua/TypeScriptToLua ]]
local ____exports = {}
local ____hud = require("constants.hud")
local HUD = ____hud.default
local ____events = require("constants.events")
local Events = ____events.default
local ____main_2Dhud = require("gui.main-hud")
local toggleInterface = ____main_2Dhud.toggleInterface
local ____constants = require("constants.index")
local Entity = ____constants.Entity
local ____debug = require("lib.debug")
local setup_gvv = ____debug.setup_gvv
local ____global_2Dsave_2Ddata = require("data.global-save-data")
local Global = ____global_2Dsave_2Ddata.default
local ____player_2Ddata = require("data.player-data")
local getPlayerData = ____player_2Ddata.getPlayerData
local initPlayer = ____player_2Ddata.initPlayer
local initPlayers = ____player_2Ddata.initPlayers
local ____resource_2Dtracker = require("lib.resource-tracker")
local ResourceTracker = ____resource_2Dtracker.default
local ____resource_2Dcache = require("lib.resource-cache")
local ResourceCache = ____resource_2Dcache.default
local ____global_2Dtemp_2Ddata = require("data.global-temp-data")
local GlobalTemp = ____global_2Dtemp_2Ddata.default
local ____settings_2Ddata = require("data.settings-data")
local SettingsData = ____settings_2Ddata.default
local ____yarm_2Dimport = require("lib.yarm-import")
local importYarmData = ____yarm_2Dimport.importYarmData
local ____resource_2Dsite_2Dcreator = require("lib.resource-site-creator")
local addResourcesToDraftResourceSite = ____resource_2Dsite_2Dcreator.addResourcesToDraftResourceSite
local startResourceSiteCreation = ____resource_2Dsite_2Dcreator.startResourceSiteCreation
setup_gvv(nil)
script.on_init(function()
SettingsData:OnInit()
Global:OnInit()
GlobalTemp:OnInit()
initPlayers(nil)
importYarmData(nil)
end)
script.on_configuration_changed(function()
Global:OnInit()
SettingsData:OnLoad()
initPlayers(nil)
end)
script.on_load(function()
SettingsData:OnLoad()
GlobalTemp:OnLoad()
end)
script.on_event(
Events.OnTick,
function(event)
ResourceCache:OnTick(event)
ResourceTracker:OnTick(event)
ResourceTracker:updatePlayers(event)
end
)
script.on_event(
defines.events.on_gui_closed,
function(event)
if event.element and event.element.name == HUD.MainFrame then
local player = game.get_player(event.player_index)
if player then
toggleInterface(nil, player)
end
end
end
)
script.on_event(
Events.Toggle_Interface,
function(event)
local player = game.get_player(event.player_index)
if player then
toggleInterface(nil, player)
end
end
)
script.on_event(
defines.events.on_player_selected_area,
function(event)
if event.item ~= Entity.SelectorTool then
return
end
local playerData = getPlayerData(nil, event.player_index)
if not playerData then
return
end
if not playerData.draftResourceSite then
startResourceSiteCreation(nil, event)
else
addResourcesToDraftResourceSite(nil, playerData.index, event.entities)
end
end
)
script.on_event(
defines.events.on_player_created,
function(event)
initPlayer(nil, event.player_index)
end
)
return ____exports
|
solution "muduo"
projectdir = basedir()
builddir = path.join(projectdir, '../build')
installdir = path.join(projectdir, '../install')
bindir = path.join(installdir, 'bin')
libdir = path.join(installdir, 'lib')
includedir = path.join(installdir, 'include')
curheadersdir = includedir
-- set the sub header dir to install files
function headersdir(dir)
curheadersdir = dir
end
-- install header files
function headers(files)
if type(files) == 'string' then
files = { files }
end
local finalfiles = {}
for _, file in ipairs(files) do
if file:find('*') then
file = os.matchfiles(file)
end
finalfiles = table.join(finalfiles, file)
end
local source = table.concat(finalfiles, ' ')
local target = path.join(includedir, curheadersdir)
assert(os.mkdir(target))
assert(os.execute('cp ' .. source .. ' ' .. target))
end
-- solution level settings
configurations { "Debug", "Release" }
location(builddir)
includedirs(includedir)
defines '_FILE_OFFSET_BITS=64'
flags {"ExtraWarnings", "FatalWarnings", "Symbols"}
buildoptions { '-g',
'-march=native',
'-rdynamic',
'-Wconversion',
'-Wno-unused-parameter',
'-Wold-style-cast',
'-Woverloaded-virtual',
'-Wpointer-arith',
'-Wshadow',
'-Wwrite-strings',
}
configuration "Debug"
buildoptions {'-O0'}
targetsuffix('-g')
configuration "Release"
buildoptions {'-finline-limit=1000'}
defines { "NDEBUG" }
flags { "Optimize" }
-- filter by kind not support in premake4.4 .4 .4 .4 beta
-- configuration {"*App"}
-- targetdir(bindir)
-- configuration { "*Lib" }
-- targetdir(libdir)
-- configuration {}
include 'muduo/base'
include 'muduo/net'
include 'examples/simple'
|
-- SquigDemos
-- Play around with Squigs!
--
-- Scott Lawrence - yorgle@gmail.com
-------------------------------------------------
-- standard stuffs
import "CoreLibs/object"
import "CoreLibs/graphics"
import "CoreLibs/sprites"
import "CoreLibs/math"
import "CoreLibs/timer"
-- our classes
import "Cursor/cursor"
import "utilities.lua"
import "squigs.lua"
-- shortcuts
gfx = playdate.graphics
displayW = playdate.display.getWidth()
displayH = playdate.display.getHeight()
-- general settings
appcfg = {
gridsize = 8,
gridsnap = 8,
grid_x = 4,
grid_y = 4,
};
|
--[[
Save Table to File
Load Table from File
v 1.0
Lua 5.2 compatible
Only Saves Tables, Numbers and Strings
Insides Table References are saved
Does not save Userdata, Metatables, Functions and indices of these
----------------------------------------------------
table.save( table , filename )
on failure: returns an error msg
----------------------------------------------------
table.load( filename or stringtable )
Loads a table that has been saved via the table.save function
on success: returns a previously saved table
on failure: returns as second argument an error msg
----------------------------------------------------
Licensed under the same terms as Lua itself.
]]--
do
-- declare local variables
--// exportstring( string )
--// returns a "Lua" portable version of the string
local function exportstring( s )
return string.format("%q", s)
end
--// The Save Function
function table.save( tbl,filename )
local charS,charE = " ","\n"
local file,err = io.open( filename, "wb" )
if err then return err end
-- initiate variables for save procedure
local tables,lookup = { tbl },{ [tbl] = 1 }
file:write( "return {"..charE )
for idx,t in ipairs( tables ) do
file:write( "-- Table: {"..idx.."}"..charE )
file:write( "{"..charE )
local thandled = {}
for i,v in ipairs( t ) do
thandled[i] = true
local stype = type( v )
-- only handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables, v )
lookup[v] = #tables
end
file:write( charS.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( charS..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( charS..tostring( v )..","..charE )
end
end
for i,v in pairs( t ) do
-- escape handled values
if (not thandled[i]) then
local str = ""
local stype = type( i )
-- handle index
if stype == "table" then
if not lookup[i] then
table.insert( tables,i )
lookup[i] = #tables
end
str = charS.."[{"..lookup[i].."}]="
elseif stype == "string" then
str = charS.."["..exportstring( i ).."]="
elseif stype == "number" then
str = charS.."["..tostring( i ).."]="
end
if str ~= "" then
stype = type( v )
-- handle value
if stype == "table" then
if not lookup[v] then
table.insert( tables,v )
lookup[v] = #tables
end
file:write( str.."{"..lookup[v].."},"..charE )
elseif stype == "string" then
file:write( str..exportstring( v )..","..charE )
elseif stype == "number" then
file:write( str..tostring( v )..","..charE )
end
end
end
end
file:write( "},"..charE )
end
file:write( "}" )
file:close()
end
--// The Load Function
function table.load( sfile )
local ftables,err = loadfile( sfile )
if err then return _,err end
local tables = ftables()
for idx = 1,#tables do
local tolinki = {}
for i,v in pairs( tables[idx] ) do
if type( v ) == "table" then
tables[idx][i] = tables[v[1]]
end
if type( i ) == "table" and tables[i[1]] then
table.insert( tolinki,{ i,tables[i[1]] } )
end
end
-- link indices
for _,v in ipairs( tolinki ) do
tables[idx][v[2]],tables[idx][v[1]] = tables[idx][v[1]],nil
end
end
return tables[1]
end
-- close do
end
-- ChillCode
|
-- sponsorblock.lua
--
-- This script skips sponsored segments of YouTube videos
-- using data from https://github.com/ajayyy/SponsorBlock
local ON_WINDOWS = package.config:sub(1,1) ~= "/"
local options = {
server_address = "https://sponsor.ajay.app",
python_path = ON_WINDOWS and "python" or "python3",
-- Categories to fetch
categories = "sponsor,intro,outro,interaction,selfpromo,preview,poi_highlight,music_offtopic",
-- Categories to skip automatically
skip_categories = "sponsor,intro,outro,interaction,selfpromo,preview,music_offtopic",
-- If true, sponsored segments will only be skipped once
skip_once = true,
-- Note that sponsored segments may ocasionally be inaccurate if this is turned off
-- see https://blog.ajay.app/voting-and-pseudo-randomness-or-sponsorblock-or-youtube-sponsorship-segment-blocker
local_database = true,
-- Update database on first run, does nothing if local_database is false
auto_update = true,
-- How long to wait between local database updates
-- Format: "X[d,h,m]", leave blank to update on every mpv run
auto_update_interval = "6h",
-- User ID used to submit sponsored segments, leave blank for random
user_id = "",
-- Name to display on the stats page https://sponsor.ajay.app/stats/ leave blank to keep current name
display_name = "",
-- Tell the server when a skip happens
report_views = true,
-- Auto upvote skipped sponsors
auto_upvote = false,
-- Use sponsor times from server if they're more up to date than our local database
server_fallback = true,
-- Create chapters at sponsor boundaries for OSC display and manual skipping
make_chapters = true,
-- Minimum duration for sponsors (in seconds), segments under that threshold will be ignored
min_duration = 1,
-- Fade audio for smoother transitions
audio_fade = false,
-- Audio fade step, applied once every 100ms until cap is reached
audio_fade_step = 10,
-- Audio fade cap
audio_fade_cap = 0,
-- Fast forward through sponsors instead of skipping
fast_forward = false,
-- Playback speed modifier when fast forwarding, applied once every second until cap is reached
fast_forward_increase = .2,
-- Playback speed cap
fast_forward_cap = 2,
-- Length of the sha256 prefix (3-32) when querying server, 0 to disable
sha256_length = 4,
-- Pattern for video id in local files, ignored if blank
-- Recommended value for base youtube-dl is "-([%w-_]+)%.[mw][kpe][v4b]m?$"
local_pattern = "-([%w-_]+)%.[mw][kpe][v4b]m?$",
-- Legacy option, use skip_categories instead
skip = true
}
mp.options = require "mp.options"
mp.options.read_options(options, "sponsorblock")
local legacy = mp.command_native_async == nil
if legacy then
options.local_database = false
end
local utils = require "mp.utils"
scripts_dir = mp.find_config_file("scripts")
local sponsorblock = utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.py")
local uid_path = utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.txt")
local database_file = options.local_database and utils.join_path(scripts_dir, "sponsorblock_shared/sponsorblock.db") or ""
local youtube_id = nil
local ranges = {}
local init = false
local segment = {a = 0, b = 0, progress = 0, first = true}
local retrying = false
local last_skip = {uuid = "", dir = nil}
local speed_timer = nil
local fade_timer = nil
local fade_dir = nil
local volume_before = mp.get_property_number("volume")
local categories = {}
local all_categories = {"sponsor", "intro", "outro", "interaction", "selfpromo", "music_offtopic"}
local chapter_cache = {}
for category in string.gmatch(options.skip_categories, "([^,]+)") do
categories[category] = true
end
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then io.close(f) return true else return false end
end
function t_count(t)
local count = 0
for _ in pairs(t) do count = count + 1 end
return count
end
function time_sort(a, b)
if a.time == b.time then
return string.match(a.title, "segment end")
end
return a.time < b.time
end
function parse_update_interval()
local s = options.auto_update_interval
if s == "" then return 0 end -- Interval Disabled
local num, mod = s:match "^(%d+)([hdm])$"
if num == nil or mod == nil then
mp.osd_message("[sponsorblock] auto_update_interval " .. s .. " is invalid", 5)
return nil
end
local time_table = {
m = 60,
h = 60 * 60,
d = 60 * 60 * 24,
}
return num * time_table[mod]
end
function clean_chapters()
local chapters = mp.get_property_native("chapter-list")
local new_chapters = {}
for _, chapter in pairs(chapters) do
if chapter.title ~= "Preview segment start" and chapter.title ~= "Preview segment end" then
table.insert(new_chapters, chapter)
end
end
mp.set_property_native("chapter-list", new_chapters)
end
function create_chapter(chapter_title, chapter_time)
local chapters = mp.get_property_native("chapter-list")
local duration = mp.get_property_native("duration")
table.insert(chapters, {title=chapter_title, time=(duration == nil or duration > chapter_time) and chapter_time or duration - .001})
table.sort(chapters, time_sort)
mp.set_property_native("chapter-list", chapters)
end
function process(uuid, t, new_ranges)
start_time = tonumber(string.match(t, "[^,]+"))
end_time = tonumber(string.sub(string.match(t, ",[^,]+"), 2))
for o_uuid, o_t in pairs(ranges) do
if (start_time >= o_t.start_time and start_time <= o_t.end_time) or (o_t.start_time >= start_time and o_t.start_time <= end_time) then
new_ranges[o_uuid] = o_t
return
end
end
category = string.match(t, "[^,]+$")
if categories[category] and end_time - start_time >= options.min_duration then
new_ranges[uuid] = {
start_time = start_time,
end_time = end_time,
category = category,
skipped = false
}
end
if options.make_chapters and not chapter_cache[uuid] then
chapter_cache[uuid] = true
local category_title = (category:gsub("^%l", string.upper):gsub("_", " "))
create_chapter(category_title .. " segment start (" .. string.sub(uuid, 1, 6) .. ")", start_time)
create_chapter(category_title .. " segment end (" .. string.sub(uuid, 1, 6) .. ")", end_time)
end
end
function getranges(_, exists, db, more)
if type(exists) == "table" and exists["status"] == "1" then
if options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end)
else
return mp.osd_message("[sponsorblock] database update failed, gave up")
end
end
if db ~= "" and db ~= database_file then db = database_file end
if exists ~= true and not file_exists(db) then
if not retrying then
mp.osd_message("[sponsorblock] database update failed, retrying...")
retrying = true
end
return update()
end
if retrying then
mp.osd_message("[sponsorblock] database update succeeded")
retrying = false
end
local sponsors
local args = {
options.python_path,
sponsorblock,
"ranges",
db,
options.server_address,
youtube_id,
options.categories,
tostring(options.sha256_length)
}
if not legacy then
sponsors = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args})
else
sponsors = utils.subprocess({args = args})
end
mp.msg.debug("Got: " .. string.gsub(sponsors.stdout, "[\n\r]", ""))
if not string.match(sponsors.stdout, "^%s*(.*%S)") then return end
if string.match(sponsors.stdout, "error") then return getranges(true, true) end
local new_ranges = {}
local r_count = 0
if more then r_count = -1 end
for t in string.gmatch(sponsors.stdout, "[^:%s]+") do
uuid = string.match(t, "([^,]+),[^,]+$")
if ranges[uuid] then
new_ranges[uuid] = ranges[uuid]
else
process(uuid, t, new_ranges)
end
r_count = r_count + 1
end
local c_count = t_count(ranges)
if c_count == 0 or r_count >= c_count then
ranges = new_ranges
end
end
function fast_forward()
if options.fast_forward and options.fast_forward == true then
speed_timer = nil
mp.set_property("speed", 1)
end
local last_speed = mp.get_property_number("speed")
local new_speed = math.min(last_speed + options.fast_forward_increase, options.fast_forward_cap)
if new_speed <= last_speed then return end
mp.set_property("speed", new_speed)
end
function fade_audio(step)
local last_volume = mp.get_property_number("volume")
local new_volume = math.max(options.audio_fade_cap, math.min(last_volume + step, volume_before))
if new_volume == last_volume then
if step >= 0 then fade_dir = nil end
if fade_timer ~= nil then fade_timer:kill() end
fade_timer = nil
return
end
mp.set_property("volume", new_volume)
end
function skip_ads(name, pos)
if pos == nil then return end
local sponsor_ahead = false
for uuid, t in pairs(ranges) do
if (options.fast_forward == uuid or not options.skip_once or not t.skipped) and t.start_time <= pos and t.end_time > pos then
if options.fast_forward == uuid then return end
if options.fast_forward == false then
mp.osd_message("[sponsorblock] " .. t.category .. " skipped")
mp.set_property("time-pos", t.end_time)
else
mp.osd_message("[sponsorblock] skipping " .. t.category)
end
t.skipped = true
last_skip = {uuid = uuid, dir = nil}
if options.report_views or options.auto_upvote then
local args = {
options.python_path,
sponsorblock,
"stats",
database_file,
options.server_address,
youtube_id,
uuid,
options.report_views and "1" or "",
uid_path,
options.user_id,
options.auto_upvote and "1" or ""
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
else
utils.subprocess_detached({args = args})
end
end
if options.fast_forward ~= false then
options.fast_forward = uuid
if speed_timer ~= nil then speed_timer:kill() end
speed_timer = mp.add_periodic_timer(1, fast_forward)
end
return
elseif (not options.skip_once or not t.skipped) and t.start_time <= pos + 1 and t.end_time > pos + 1 then
sponsor_ahead = true
end
end
if options.audio_fade then
if sponsor_ahead then
if fade_dir ~= false then
if fade_dir == nil then volume_before = mp.get_property_number("volume") end
if fade_timer ~= nil then fade_timer:kill() end
fade_dir = false
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(-options.audio_fade_step) end)
end
elseif fade_dir == false then
fade_dir = true
if fade_timer ~= nil then fade_timer:kill() end
fade_timer = mp.add_periodic_timer(.1, function() fade_audio(options.audio_fade_step) end)
end
end
if options.fast_forward and options.fast_forward ~= true then
options.fast_forward = true
speed_timer:kill()
speed_timer = nil
mp.set_property("speed", 1)
end
end
function vote(dir)
if last_skip.uuid == "" then return mp.osd_message("[sponsorblock] no sponsors skipped, can't submit vote") end
local updown = dir == "1" and "up" or "down"
if last_skip.dir == dir then return mp.osd_message("[sponsorblock] " .. updown .. "vote already submitted") end
last_skip.dir = dir
local args = {
options.python_path,
sponsorblock,
"stats",
database_file,
options.server_address,
youtube_id,
last_skip.uuid,
"",
uid_path,
options.user_id,
dir
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
else
utils.subprocess({args = args})
end
mp.osd_message("[sponsorblock] " .. updown .. "vote submitted")
end
function update()
mp.command_native_async({name = "subprocess", playback_only = false, args = {
options.python_path,
sponsorblock,
"update",
database_file,
options.server_address
}}, getranges)
end
function file_loaded()
local initialized = init
ranges = {}
segment = {a = 0, b = 0, progress = 0, first = true}
last_skip = {uuid = "", dir = nil}
chapter_cache = {}
local video_path = mp.get_property("path", "")
mp.msg.debug("Path: " .. video_path)
local video_referer = string.match(mp.get_property("http-header-fields", ""), "Referer:([^,]+)") or ""
mp.msg.debug("Referer: " .. video_referer)
local urls = {
"https?://youtu%.be/([%w-_]+).*",
"https?://w?w?w?%.?youtube%.com/v/([%w-_]+).*",
"/watch.*[?&]v=([%w-_]+).*",
"/embed/([%w-_]+).*"
}
youtube_id = nil
for i,url in ipairs(urls) do
youtube_id = youtube_id or string.match(video_path, url) or string.match(video_referer, url)
end
youtube_id = youtube_id or string.match(video_path, options.local_pattern)
if not youtube_id or string.len(youtube_id) < 11 or (local_pattern and string.len(youtube_id) ~= 11) then return end
youtube_id = string.sub(youtube_id, 1, 11)
mp.msg.debug("Found YouTube ID: " .. youtube_id)
init = true
if not options.local_database then
getranges(true, true)
else
local exists = file_exists(database_file)
if exists and options.server_fallback then
getranges(true, true)
mp.add_timeout(0, function() getranges(true, true, "", true) end)
elseif exists then
getranges(true, true)
elseif options.server_fallback then
mp.add_timeout(0, function() getranges(true, true, "") end)
end
end
if initialized then return end
if options.skip then
mp.observe_property("time-pos", "native", skip_ads)
end
if options.display_name ~= "" then
local args = {
options.python_path,
sponsorblock,
"username",
database_file,
options.server_address,
youtube_id,
"",
"",
uid_path,
options.user_id,
options.display_name
}
if not legacy then
mp.command_native_async({name = "subprocess", playback_only = false, args = args}, function () end)
else
utils.subprocess_detached({args = args})
end
end
if not options.local_database or (not options.auto_update and file_exists(database_file)) then return end
if file_exists(database_file) then
local db_info = utils.file_info(database_file)
local cur_time = os.time(os.date("*t"))
local upd_interval = parse_update_interval()
if upd_interval == nil or os.difftime(cur_time, db_info.mtime) < upd_interval then return end
end
update()
end
function set_segment()
if not youtube_id then return end
local pos = mp.get_property_number("time-pos")
if pos == nil then return end
if segment.progress > 1 then
segment.progress = segment.progress - 2
end
if segment.progress == 1 then
segment.progress = 0
segment.b = pos
mp.osd_message("[sponsorblock] segment boundary B set, press again for boundary A", 3)
else
segment.progress = 1
segment.a = pos
mp.osd_message("[sponsorblock] segment boundary A set, press again for boundary B", 3)
end
if options.make_chapters and not segment.first then
local start_time = math.min(segment.a, segment.b)
local end_time = math.max(segment.a, segment.b)
if end_time - start_time ~= 0 and end_time ~= 0 then
clean_chapters()
create_chapter("Preview segment start", start_time)
create_chapter("Preview segment end", end_time)
end
end
segment.first = false
end
function select_category(selected)
for category in string.gmatch(options.categories, "([^,]+)") do
mp.remove_key_binding("select_category_"..category)
mp.remove_key_binding("kp_select_category_"..category)
end
submit_segment(selected)
end
function submit_segment(category)
if not youtube_id then return end
local start_time = math.min(segment.a, segment.b)
local end_time = math.max(segment.a, segment.b)
if end_time - start_time == 0 or end_time == 0 then
mp.osd_message("[sponsorblock] empty segment, not submitting")
elseif segment.progress <= 1 then
segment.progress = segment.progress + 2
local category_list = ""
for category_id, category in pairs(all_categories) do
local category_title = (category:gsub("^%l", string.upper):gsub("_", " "))
category_list = category_list .. category_id .. ": " .. category_title .. "\n"
mp.add_forced_key_binding(tostring(category_id), "select_category_"..category, function() select_category(category) end)
mp.add_forced_key_binding("KP"..tostring(category_id), "kp_select_category_"..category, function() select_category(category) end)
end
mp.osd_message(string.format("[sponsorblock] press a number to select category for segment: %.2d:%.2d:%.2d to %.2d:%.2d:%.2d\n\n" .. category_list .. "\nyou can press Shift+G again for default (Sponsor) or hide this message with g", math.floor(start_time/(60*60)), math.floor(start_time/60%60), math.floor(start_time%60), math.floor(end_time/(60*60)), math.floor(end_time/60%60), math.floor(end_time%60)), 30)
else
mp.osd_message("[sponsorblock] submitting segment...", 30)
local submit
local args = {
options.python_path,
sponsorblock,
"submit",
database_file,
options.server_address,
youtube_id,
tostring(start_time),
tostring(end_time),
uid_path,
options.user_id,
category or "sponsor"
}
if not legacy then
submit = mp.command_native({name = "subprocess", capture_stdout = true, playback_only = false, args = args})
else
submit = utils.subprocess({args = args})
end
if string.match(submit.stdout, "success") then
segment = {a = 0, b = 0, progress = 0, first = true}
mp.osd_message("[sponsorblock] segment submitted")
if options.make_chapters then
clean_chapters()
create_chapter("Submitted segment start", start_time)
create_chapter("Submitted segment end", end_time)
end
elseif string.match(submit.stdout, "error") then
mp.osd_message("[sponsorblock] segment submission failed, server may be down. try again", 5)
elseif string.match(submit.stdout, "502") then
mp.osd_message("[sponsorblock] segment submission failed, server is down. try again", 5)
elseif string.match(submit.stdout, "400") then
mp.osd_message("[sponsorblock] segment submission failed, impossible inputs", 5)
segment = {a = 0, b = 0, progress = 0, first = true}
elseif string.match(submit.stdout, "429") then
mp.osd_message("[sponsorblock] segment submission failed, rate limited. try again", 5)
elseif string.match(submit.stdout, "409") then
mp.osd_message("[sponsorblock] segment already submitted", 3)
segment = {a = 0, b = 0, progress = 0, first = true}
else
mp.osd_message("[sponsorblock] segment submission failed", 5)
end
end
end
mp.register_event("file-loaded", file_loaded)
mp.add_key_binding("g", "set_segment", set_segment)
mp.add_key_binding("G", "submit_segment", submit_segment)
mp.add_key_binding("h", "upvote_segment", function() return vote("1") end)
mp.add_key_binding("H", "downvote_segment", function() return vote("0") end)
-- Bindings below are for backwards compatibility and could be removed at any time
mp.add_key_binding(nil, "sponsorblock_set_segment", set_segment)
mp.add_key_binding(nil, "sponsorblock_submit_segment", submit_segment)
mp.add_key_binding(nil, "sponsorblock_upvote", function() return vote("1") end)
mp.add_key_binding(nil, "sponsorblock_downvote", function() return vote("0") end)
|
local Helper = require( 'lctags.Helper' )
local mqueue = Helper.createMQueue( "test" )
print( mqueue:get() )
|
-- TEMP FILES SHOULD NOT BE LOADED FROM HERE
function ClearTempFiles()
local WriteFile = "$TMG_tempsquadmenu.lua"
writeto(WriteFile)
write("")
writeto()
WriteFile = "$TMG_tempsectormap.lua"
writeto(WriteFile)
write("")
writeto()
WriteFile = "$TMG_tempdialoguestatus.lua"
writeto(WriteFile)
write("")
writeto()
end
function ReloadVisibleScreens()
local sectormap = ""
local squadmenu = ""
if (gametypeScope == "minor") then
sectormap = "SectorMapScreenMinor"
squadmenu = "SquadMenuScreenMinor"
elseif (gametypeScope == "major") then
sectormap = "SectorMapScreenMajor"
squadmenu = "SquadMenuScreenMajor"
end
-- todo: fails sometimes, for instance when the screen turns into a letterbox
-- if (UI_IsScreenActive(sectormap) == 1) then
-- UI_ReloadScreen(sectormap)
-- elseif (UI_IsScreenActive(squadmenu) == 1) then
-- UI_ReloadScreen(squadmenu)
-- end
if (isSectorMapScreenActive == 1) then
UI_ReloadScreen(sectormap)
elseif (isSquadMenuScreenActive == 1) then
UI_ReloadScreen(squadmenu)
end
end
function ReloadAllScreens()
local sectormap = ""
local squadmenu = ""
if (gametypeScope == "minor") then
sectormap = "SectorMapScreenMinor"
squadmenu = "SquadMenuScreenMinor"
elseif (gametypeScope == "major") then
sectormap = "SectorMapScreenMajor"
squadmenu = "SquadMenuScreenMajor"
end
UI_ReloadScreen(sectormap)
UI_ReloadScreen(squadmenu)
end
--------------------------------------------------------------------------------
-- Screen toggles
--
function ObjectivesListScreenToggleFunc()
if (gametypeScope == "minor") then
if (UI_IsScreenActive("ObjectivesList") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnObjectives", 0)
UI_HideScreen("ObjectivesList")
else
UI_SetButtonPressed("NewTaskbar", "btnObjectives", 1)
UI_ShowScreen("ObjectivesList", ePopup)
if (UI_IsScreenActive("SquadMenuScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 0)
UI_HideScreen("SquadMenuScreenMinor")
isSquadMenuScreenActive = 0
end
if (UI_IsScreenActive("SectorMapScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 0)
UI_HideScreen("SectorMapScreenMinor")
isSectorMapScreenActive = 0
end
if (UI_IsScreenActive("SpeechRecall") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnRecall", 0)
UI_HideScreen("SpeechRecall")
end
end
end
end
function SpeechRecallScreenToggleFunc()
if (gametypeScope == "minor") then
if (UI_IsScreenActive("SpeechRecall") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnRecall", 0)
UI_HideScreen("SpeechRecall")
else
UI_SetButtonPressed("NewTaskbar", "btnRecall", 1)
UI_ShowScreen("SpeechRecall", ePopup)
if (UI_IsScreenActive("ObjectivesList") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnObjectives", 0)
UI_HideScreen("ObjectivesList")
end
if (UI_IsScreenActive("SquadMenuScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 0)
UI_HideScreen("SquadMenuScreenMinor")
isSquadMenuScreenActive = 0
end
if (UI_IsScreenActive("SectorMapScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 0)
UI_HideScreen("SectorMapScreenMinor")
isSectorMapScreenActive = 0
end
end
end
end
function SectorMapScreenToggleFunc()
if (gametypeScope == "minor") then
if (UI_IsScreenActive("SectorMapScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 0)
UI_HideScreen("SectorMapScreenMinor")
isSectorMapScreenActive = 0
else
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 1)
UI_ShowScreen("SectorMapScreenMinor", ePopup)
UI_ReloadScreen("SectorMapScreenMinor")
isSectorMapScreenActive = 1
if (UI_IsScreenActive("SpeechRecall") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnRecall", 0)
UI_HideScreen("SpeechRecall")
end
if (UI_IsScreenActive("ObjectivesList") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnObjectives", 0)
UI_HideScreen("ObjectivesList")
end
if (UI_IsScreenActive("SquadMenuScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 0)
UI_HideScreen("SquadMenuScreenMinor")
isSquadMenuScreenActive = 0
end
end
elseif (gametypeScope == "major") then
SectorMapSquadMenuSwitchFunc()
end
end
function SquadMenuScreenToggleFunc()
if (gametypeScope == "minor") then
if (UI_IsScreenActive("SquadMenuScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 0)
UI_HideScreen("SquadMenuScreenMinor")
isSquadMenuScreenActive = 0
else
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 1)
UI_ShowScreen("SquadMenuScreenMinor", ePopup)
UI_ReloadScreen("SquadMenuScreenMinor")
isSquadMenuScreenActive = 1
if (UI_IsScreenActive("SectorMapScreenMinor") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 0)
UI_HideScreen("SectorMapScreenMinor")
isSectorMapScreenActive = 0
end
if (UI_IsScreenActive("SpeechRecall") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnRecall", 0)
UI_HideScreen("SpeechRecall")
end
if (UI_IsScreenActive("ObjectivesList") == 1) then
UI_SetButtonPressed("NewTaskbar", "btnObjectives", 0)
UI_HideScreen("ObjectivesList")
end
end
elseif (gametypeScope == "major") then
SectorMapSquadMenuSwitchFunc()
end
end
function SectorMapSquadMenuSwitchFunc()
if (gametypeScope == "minor") then
if (UI_IsScreenActive("SectorMapScreenMinor") == 1) then
UI_HideScreen("SectorMapScreenMinor")
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 0)
isSectorMapScreenActive = 0
UI_ShowScreen("SquadMenuScreenMinor", ePopup)
UI_ReloadScreen("SquadMenuScreenMinor")
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 1)
isSquadMenuScreenActive = 1
elseif (UI_IsScreenActive("SquadMenuScreenMinor") == 1) then
UI_HideScreen("SquadMenuScreenMinor")
UI_SetButtonPressed("NewTaskbar", "btnSquadMenu", 0)
isSquadMenuScreenActive = 0
UI_ShowScreen("SectorMapScreenMinor", ePopup)
UI_ReloadScreen("SectorMapScreenMinor")
UI_SetButtonPressed("NewTaskbar", "btnSectorMap", 1)
isSectorMapScreenActive = 1
end
elseif (gametypeScope == "major") then
if (UI_IsScreenActive("SectorMapScreenMajor") == 1) then
UI_HideScreen("SectorMapScreenMajor")
isSectorMapScreenActive = 0
UI_ShowScreen("SquadMenuScreenMajor", ePopup)
UI_ReloadScreen("SquadMenuScreenMajor")
isSquadMenuScreenActive = 1
elseif (UI_IsScreenActive("SquadMenuScreenMajor") == 1) then
UI_HideScreen("SquadMenuScreenMajor")
isSquadMenuScreenActive = 0
UI_ShowScreen("SectorMapScreenMajor", ePopup)
UI_ReloadScreen("SectorMapScreenMajor")
isSectorMapScreenActive = 1
end
end
end
function UpdateTimeLabelFunc()
UI_SetLabelTextHotkey("SectorMapScreenMajor", "txtTimeShowRate", newGameTimeText, 666)
end
--------------------------------------------------------------------------------
-- save persistant data
--
function SavePersistentData()
print("Gametype: Saving campaign status...")
local WriteFile = "$TMG_savegame.lua"
writeto(WriteFile)
print("Gametype: Writing map progress...")
write("colLabels = {\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",} -- sector column labels\n")
write("modVersion = \"" .. currentModVersion .. "\" -- mod version number, hopefully correct ;)\n")
write("campaignIsStarted = 1\t\t-- 0 or 1\n")
write("loadSectorMap = " .. loadSectorMap .. "\n")
write("playerRUs = " .. Player_GetRU(0) .. "\n")
write("currentGameTime = " .. currentGameTime .. "\n")
write("legibleGameTime = \"" .. legibleGameTime .. "\"\n\n")
write("currentSectorRow = " .. currentSectorRow .. "\t\t-- 1 to 4\n")
write("currentSectorCol = " .. currentSectorCol .. "\t\t-- 1 to 4\n")
write("sectorCode = colLabels[currentSectorCol] .. currentSectorRow\t\t-- for instance \"A1\" or \"D3\"\n")
write("sectorName = \"Sector \" .. sectorCode\t\t-- for instance \"Sector A1\" or \"Sector D3\"\n\n")
print("Gametype: Done writing map progress!")
write("-- sectors you have visited\n")
WriteSectorsExplored()
write("-- sector missions you have completed\n")
WriteObjectivesClear()
print("Gametype: Writing quest progress...")
WriteQuestsStatus()
print("Gametype: Done writing quest progress!")
print("Gametype: Writing global time queue...")
WriteGlobalTimeQueue()
print("Gametype: Done writing global time queue!")
print("Gametype: Writing squad ships...")
WriteSquadShips()
print("Gametype: Done writing squad ships!")
print("Gametype: Writing local ships...")
WriteLocalShips()
print("Gametype: Done writing local ships!")
print("Gametype: Writing local sobgroups...")
WriteLocalSobgroups()
print("Gametype: Done writing local sobgroups!")
writeto()
print("Gametype: Done saving campaign status!")
end
--------------------------------------------------------------------------------
-- save game and show confirmation dialog (confirmation dialog is triggered elsewhere)
--
function SaveGameWithDialog()
if (gametypeScope == "minor") then
UpdateSquadShips()
UpdateLocalShips()
SavePersistentData()
elseif (gametypeScope == "major") then
SavePersistentData()
end
end
--------------------------------------------------------------------------------
--
--
function SobGroup_Separate(outgroup, fromgroup)
-- created by shadowwinterknig
local c, i, n = SobGroup_Count(fromgroup), 0, 0
SobGroup_CreateIfNotExist("temp")
SobGroup_Clear("temp")
while i < c do
SobGroup_FillShipsByIndexRange("temp", fromgroup, i, 1)
if (SobGroup_Count("temp") > 0) then
SobGroup_CreateIfNotExist(outgroup .. n)
SobGroup_Clear(outgroup .. n)
SobGroup_SobGroupAdd(outgroup .. n, "temp")
i = i + SobGroup_Count("temp")
n = n + 1
else
i = i + 1
end
end
return n
end
|
function start (song)
print("Song: " .. song .. " @ " .. bpm .. " donwscroll: " .. downscroll)
setActorAlpha(0, 'tordBG')
end
local defaultHudX = 0
local defaultHudY = 0
local defaultWindowX = 0
local defaultWindowY = 0
local lastStep = 0
function update (elapsed)
local currentBeat = (songPos / 1000)*(bpm/60)
if l1 then
for i=0,7 do
setActorX(_G['defaultStrum'..i..'X'] + 50 * math.sin((currentBeat + i*0.32)), i)
setActorY(_G['defaultStrum'..i..'Y'] + 10 * math.cos((currentBeat + i*0.25) * math.pi), i)
end
end
end
function beatHit (beat)
if curBeat == 135 then
dadAltAnim = true
end
end
function stepHit (step)
if curStep == 192 then
setActorAlpha(0, 'bfBG')
setActorAlpha(1, 'tordBG')
changeDadCharacter('bf', 100, 400)
end
if curStep == 256 then
changeBoyfriendCharacter('bf-gf', 1096, 271)
end
if curStep == 320 then
setActorAlpha(1, 'bfBG')
changeDadCharacter('tabi', 100, 0)
end
if curStep == 384 then
changeBoyfriendCharacter('bf-exgf', 1000, -103)
end
if curStep == 448 then
changeDadCharacter('pico', 100, 300)
end
if curStep == 480 then
changeBoyfriendCharacter('cassandra', 1096, 0)
end
if curStep == 512 then
changeDadCharacter('cj', 100, 0)
end
if curStep == 544 then
dadAltAnim = false
changeBoyfriendCharacter('ruby', 1096, 0)
end
if curStep == 576 then
changeDadCharacter('coco', 100, 0)
end
if curStep == 608 then
changeBoyfriendCharacter('gura-amelia', 1096, 200)
end
if curStep == 640 then
changeDadCharacter('tankman', 100, 180)
end
if curStep == 672 then
changeBoyfriendCharacter('hd-senpai', 1096, 0)
end
if curStep == 640 then
changeDadCharacter('tankman', 100, 180)
end
if curStep == 672 then
changeBoyfriendCharacter('hd-senpai', 1096, 0)
end
end
|
-- Slope Environment
--
-- local Base = require 'src.entities.entity'
-- local Slope = Base:extend()
-- -- New slope bounds
-- --
-- function Slope:new(name, data)
-- assert(data.shape == 'polyline', 'Must be a polyline shape.')
-- --
-- -- properties
-- self.segment = Segment(
-- Vec2(data.polyline[1]),
-- Vec2(data.polyline[2])
-- )
-- self.order = 1
-- local bounds = self.segment:aabb()
-- local cx, cy = bounds:center()
-- local w, h = bounds:dimensions()
-- --
-- Base.new(self, name, _:merge(data, {
-- color = { _:color('blue-300') },
-- x = cx,
-- y = cy,
-- width = w,
-- height = h
-- }))
-- end
-- -- Resolve collision
-- --
-- function Slope:resolve(con, target)
-- local cx, cy = con.item:center()
-- local w, h = con.item:dimensions()
-- local base = Vec2(cx, cy + h/2)
-- local segment = Segment(cx, base.y+5, cx, cy)
-- local anchor = self.segment:vsSegment(segment)
-- if anchor then
-- con.item:onGroundContact(con.other, con)
-- --
-- con.item:vx(con.item:vx() * 0.95)
-- con.item:vy(0)
-- target.y = target.y + (anchor - base).y
-- return false
-- end
-- end
-- -- Are bounding boxes touching?
-- --
-- function Slope:isTouching(other)
-- return self:aabb():contains(other:aabb())
-- end
-- -- Draw
-- --
-- function Slope:draw()
-- lg.setColor(1,1,1,1)
-- lg.line(self.segment:unpack())
-- --
-- Base.draw(self)
-- end
-- return Slope
return {}
|
--====================================================================--
-- Styled TextField
--
-- Shows styled use of the DMC TextField Widget
--
-- Sample code is MIT licensed, the same license which covers Lua itself
-- http://en.wikipedia.org/wiki/MIT_License
-- Copyright (C) 2015 David McCuskey. All Rights Reserved.
--====================================================================--
print( "\n\n#########################################################\n\n" )
--===================================================================--
--== Imports
local dUI = require 'lib.dmc_ui'
local Utils = require 'dmc_utils'
--===================================================================--
--== Setup, Constants
local W, H = display.contentWidth, display.contentHeight
local H_CENTER, V_CENTER = W*0.5, H*0.5
--===================================================================--
--== Support Functions
--======================================================--
-- Setup Visual Screen Items
local function setupBackground()
local width, height = 100, 50
local o
o = display.newRect(0,0,W,H)
o:setFillColor(1,1,1)
o.x, o.y = H_CENTER, V_CENTER
o = display.newRect(0,0,width+4,height+4)
o:setStrokeColor(0,0,0)
o.strokeWidth=2
o.x, o.y = H_CENTER, V_CENTER
o = display.newRect( 0,0,10,10)
o:setFillColor(1,0,0)
o.x, o.y = H_CENTER, V_CENTER
end
--======================================================--
-- Widget Handlers
local function widgetOnPropertyEvent_handler( event )
print( 'Main: widgetOnPropertyEvent_handler', event.id, event.phase )
local etype= event.type
local property= event.property
local value = event.value
print( "Widget Property Changed", etype, property, value )
end
local function widgetEvent_handler( event )
print( 'Main: widgetEvent_handler', event.id, event.phase )
local etype= event.type
print( "Widget Event", etype )
end
--===================================================================--
--== Main
--===================================================================--
setupBackground()
local delegate = {
-- shouldChangeCharacters = function( self, event )
-- print("main:shouldChangeCharacters", event )
-- Utils.print( event )
-- return true
-- end,
-- shouldBeginEditing = function( self )
-- print("main:shouldBeginEditing" )
-- return true
-- end
}
--======================================================--
--== create textfield widget, default style
function run_example1()
local bw1
tf1 = dUI.newTextField{
text="",
hintText="Pizza Topping:",
delegate=delegate
}
-- tf1:addEventListener( tf1.EVENT, widgetEvent_handler )
-- tf1.onProperty = widgetOnPropertyEvent_handler
tf1.debugOn = true
tf1.x = H_CENTER
tf1.y = V_CENTER
tf1:setAnchor( {0,0} )
tf1:setAnchor( {0.5,0.5} )
-- tf1:setAnchor( {1,1} )
-- tf1.y = 300
tf1.width=300
tf1.height=60
tf1.align='left'
tf1.marginX=10
tf1.hintFontSize=18
tf1:setBackgroundFillColor( 1,0.5,0.2,0.3 )
-- tf1.isSecure=true
-- tf1.isHitActive=true
timer.performWithDelay( 1000, function()
print("\n\n Update Properties")
-- test background props
-- tf1.x = H_CENTER-50
-- tf1.y = V_CENTER+100
-- tf1.isSecure=false
tf1.align='center'
tf1.text="hello"
-- tf1.marginX=10
-- tf1.width=200
-- tf1.height=100
-- -- tf1.isHitActive=false
-- tf1:setHintTextColor( 1,1,0 )
-- tf1.hintFontSize = 18
-- tf1:setAnchor( {0,0} )
-- tf1:setBackgroundStrokeColor( 0.2,0.2,0.9,0.5 )
-- tf1:setBackgroundFillColor( 0.2,0.2,0.2,0.2 )
-- tf1.backgroundStrokeWidth = 10
-- tf1:setBackgroundStrokeColor( 0.2,0.2,0.9,0.5 )
-- tf1:setBackgroundFillColor( 0.2,0.2,0.2,0.2 )
-- tf1.backgroundStrokeWidth = 10
-- tf1.hintFont = native.systemFontBold
-- tf1.hintFontSize = 30
-- tf1:setHintTextColor(1,0,0,1)
-- tf1.displayFont = native.systemFontBold
-- tf1.displayFontSize = 30
-- tf1:setDisplayTextColor(1,0,0,1)
end)
timer.performWithDelay( 2000, function()
print("\n\n Update Properties")
-- test background props
-- tf1.width=100
-- tf1.height=80
-- tf1.x = 100
-- tf1.isSecure=true
-- tf1.x = H_CENTER+50
-- tf1.y = V_CENTER+50
-- tf1.isHitActive=false
end)
end
-- run_example1()
--======================================================--
--== create textfield widget, default style
function run_example2()
local w1
w1 = dUI.newTextField{
text="",
hintText="Pizza Topping:",
}
w1.x = H_CENTER
w1.y = V_CENTER
w1:setAnchor( {0,0} )
w1:setAnchor( {0.5,0.5} )
-- w1:setAnchor( {1,1} )
w1:setBackgroundFillColor( 1,0.5,0.2,1 )
w1.marginX = 10
w1.align = 'left'
timer.performWithDelay( 2000, function()
print("\n\n Update Properties")
w1:setAnchor( {1,1} )
w1.align='right'
end)
end
-- run_example2()
function run_example3()
-- tf1.text="hamburger"
-- tf1:_startEdit()
-- tf1:setAnchor( {0,0} )
-- tf1:setAnchor( {0.5,0.5} )
-- tf1:setAnchor( {1,1} )
-- timer.performWithDelay( 1000, function()
-- print("\n\n Update Properties")
-- -- test input-text props
-- -- tf1.x = H_CENTER
-- -- tf1.y = V_CENTER
-- -- testing text properties
-- -- tf1.text="hotdog"
-- tf1.align='center'
-- -- tf1.marginX=5
-- -- tf1.marginY=10
-- -- tf1.width=200
-- -- tf1.height=60
-- -- tf1:setAnchor( {0,0} )
-- -- tf1:setAnchor( {0,1} )
-- tf1:setAnchor( {1,1} )
-- tf1:setBackgroundFillColor( 1,0.5,0.2,0.5 )
-- -- tf1:setBackgroundStrokeColor( 2,0,0,1 )
-- -- tf1.backgroundStrokeWidth = 1
-- tf1.textFont = native.systemFontBold
-- tf1.textFontSize = 24
-- tf1:setTextColor( 1,0.5,0.5, 1)
-- end)
-- timer.performWithDelay( 3000, function()
-- -- tf1.style=nil -- shouldn't change, already default
-- end)
end
-- run_example3()
--======================================================--
--== create textfield widget, zipcode formatter
-- create formatter
function run_example4()
-- formatter = dUI.newFormatter( dUI.Formatter.US_ZIPCODE )
-- style = dUI.newTextFieldStyle{
-- name="text-field-default",
-- width=200,
-- height=40,
-- }
-- -- create text field
-- textfield = dUI.newTextField{
-- text="",
-- hintText = "Zipcode",
-- style=nil,
-- formatter=formatter
-- }
-- -- textfield.formatter = formatter
-- textfield.x = H_CENTER
-- textfield.y = V_CENTER
-- --== Main Text Field Tests
-- if true then
-- timer.performWithDelay( 1000, function()
-- print("\n\n\n UPDATED")
-- -- textfield.x = 100
-- -- textfield.y = 350
-- -- textfield.y = 350
-- textfield:setAnchor( {0,0} )
-- -- textfield:setAnchor( {0.5,0.5} )
-- -- textfield:setAnchor( {1,1} )
-- -- textfield.width = 300
-- -- textfield.height = 100
-- -- textfield.align = 'left'
-- -- textfield.align = 'center'
-- -- textfield.align = 'right'
-- -- textfield.marginX = 10
-- -- textfield.marginY = 10
-- textfield.text = "331122" -- ok
-- -- textfield:setEditActive( true )
-- end)
-- end
-- --== Background Tests
-- if false then
-- timer.performWithDelay( 1000, function()
-- textfield.y = V_CENTER-100
-- print("\n\n\n UPDATED")
-- -- textfield.backgroundStrokeWidth = 6
-- -- textfield:setBackgroundFillColor( 0,0.5,1,1)
-- -- textfield:setBackgroundStrokeColor( 0,0,1,1)
-- -- textfield.width = 400
-- -- textfield.height = 200
-- -- !!! no text to test hint !!!
-- textfield.text = ""
-- textfield.hintText = "zebra"
-- textfield.align = 'right'
-- textfield.hintFont = native.systemFontBold
-- textfield.hintFontSize = 40
-- textfield:setHintColor( 0.5,0.5,0.5,1)
-- -- textfield.text = "89122"
-- -- textfield.textFont = native.systemFontBold
-- -- textfield.textFontSize = 30
-- -- textfield:setTextColor( 0.5,0.5,0.5,1)
-- -- textfield:setEditActive( true )
-- -- textfield:setTextColor( 0.5, 0.2, 0.1 )
-- -- textfield.hintFontSize = 40
-- end)
-- end
-- if false then
-- timer.performWithDelay( 1000, function()
-- textfield.y = V_CENTER-100
-- print("\n\n\n UPDATED")
-- -- textfield.backgroundStrokeWidth = 6
-- -- textfield:setBackgroundFillColor( 0,0.5,1,1)
-- -- textfield:setBackgroundStrokeColor( 0,0,1,1)
-- -- textfield.width = 400
-- -- textfield.height = 200
-- -- !!! no text to test hint !!!
-- textfield.text = ""
-- textfield.hintText = "zebra"
-- textfield.align = 'right'
-- textfield.hintFont = native.systemFontBold
-- textfield.hintFontSize = 40
-- textfield:setHintColor( 0.5,0.5,0.5,1)
-- -- textfield.text = "89122"
-- -- textfield.textFont = native.systemFontBold
-- -- textfield.textFontSize = 30
-- -- textfield:setTextColor( 0.5,0.5,0.5,1)
-- -- textfield:setEditActive( true )
-- -- textfield:setTextColor( 0.5, 0.2, 0.1 )
-- -- textfield.hintFontSize = 40
-- end)
-- end
-- textfield.onEvent = textFieldOnEvent_handler
-- textfield:addEventListener( textfield.EVENT, textFieldOnEvent_handler )
-- timer.performWithDelay( 1, function() textfield.width( 0.5, 0.2, 0.1 ) end)
-- create a theme
-- textfield.x = H_CENTER
-- textfield.y = V_CENTER
-- textfield:setAnchor( {0,0} )
-- textfield:setAnchor( {0.5,0.5} )
-- textfield:setAnchor( {1,1} )
-- --== APIT
-- textfield.x = 200
-- textfield.y = 200
-- textfield.width = 150
-- textfield.height = 75
-- textfield.align = 'center'
-- textfield.anchorX = 0.5
-- textfield.anchorY = 0.5
-- textfield.backgroundStyle = 'none'
-- textfield.inputType = 'password'
-- textfield.marginX = 10
-- textfield.marginY = 10
-- textfield.returnKey = 'done'
-- textfield.backgroundStrokeWidth = 4
-- textfield:setBackgroundStrokeColor( 1,0,1)
-- textfield:setBackgroundFillColor( 1,0,1)
-- textfield.hintFont = native.systemFont
-- textfield.hintFontSize = 30
-- textfield:setHintColor( 0,1,1)
-- textfield.textFont = native.systemFont
-- textfield.textFontSize = 40
-- textfield:setTextColor( 1,1,0)
-- theme = dUI.newTextFieldTheme{
-- placeholder={
-- font=
-- fontSize=
-- color
-- },
-- text={
-- font=
-- fontSize=
-- color
-- },
-- }
-- theme.default.width
-- theme.default.placeholder.font
-- theme = dUI.newTheme( 'textfield' )
-- theme.
end
-- run_example4()
function run_example5()
local w1, w2, w3
w1 = dUI.newTextField{
text="",
hintText="Username:",
style = {
width=270,
height=40,
marginX=10,
align='left',
fontSize=16,
textColor='#663366',
font='Optima-Italic',
background={
type='9-slice',
view={
sheetInfo='asset.textfield-pink-sheet',
sheetImage='asset/textfield-pink-sheet.png',
}
},
display={
font='Optima-Bold',
}
}
}
w1.x, w1.y = H_CENTER, V_CENTER-150
w2 = dUI.newTextField{
text="",
hintText="Email",
style = {
width=280,
marginX=15,
height=45,
fontSize=16,
align='left',
background={
type='9-slice',
view={
sheetInfo='asset.textfield-nice-sheet',
sheetImage='asset/textfield-nice-sheet.png',
}
},
hint={
align='right',
textColor='#999999',
},
display={
align='left',
textColor='#444444',
}
}
}
w2.x, w2.y = H_CENTER, V_CENTER-90
w3 = dUI.newTextField{
text="",
hintText="Address",
}
w3.x, w3.y = H_CENTER, V_CENTER
local narrow, wide, pause
pause = function( f )
timer.performWithDelay( 1000, f )
end
wide = function()
transition.to( w1, {time=3000, width=270, onComplete=function() pause(narrow) end } )
end
narrow = function()
transition.to( w1, {time=3000, width=60, onComplete=function() pause(wide) end} )
end
narrow()
end
run_example5()
|
globals = getfenv(0)
MUI_GLOBAL_FONT_TABLE =
{
"Interface\\AddOns\\minimalUI\\fonts\\8_Bit_Madness.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\alterebro.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\apple.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\Asai-Analogue.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\big_noodle_titling.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\BMSPA___.TTF",
"Interface\\AddOns\\minimalUI\\fonts\\capture.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\CaviarDreams.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\homespun.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\LiberationMono-Bold.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\LiberationMono-Regular.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\macromedia.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\ostrich.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\pixelade.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\pixelbold.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\pricedown bl.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\silkscreen.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\uni.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\upheavtt.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\visitor1.ttf",
"Interface\\AddOns\\minimalUI\\fonts\\visitor2.ttf"
}
MUI_GLOBAL_TEXTURE_TABLE =
{
"Interface\\AddOns\\minimalUI\\img\\Aluminium.tga",
"Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
"Interface\\AddOns\\minimalUI\\img\\BantoBar.tga",
"Interface\\AddOns\\minimalUI\\img\\Bars.tga",
"Interface\\AddOns\\minimalUI\\img\\BorderGlow.tga",
"Interface\\AddOns\\minimalUI\\img\\BorderShadow.tga",
"Interface\\AddOns\\minimalUI\\img\\Gloss.tga",
"Interface\\AddOns\\minimalUI\\img\\Healbot.tga",
"Interface\\AddOns\\minimalUI\\img\\Luna.tga",
"Interface\\AddOns\\minimalUI\\img\\Otravi.tga",
"Interface\\AddOns\\minimalUI\\img\\Smooth.tga",
"Interface\\AddOns\\minimalUI\\img\\Striped.tga"
}
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
ScriptErrors:SetScript("OnShow", function(msg)
local error_message = ScriptErrors_Message:GetText()
mUI_DebugError(error_message)
ScriptErrors:Hide()
end)
function mUI_RGBToHex(value)
local hex = ""
while(value > 0) do
local index = math.fmod(value, 16) + 1
value = math.floor(value / 16)
hex = string.sub('0123456789ABCDEF', index, index) .. hex
end
if(string.len(hex) == 0) then hex = '00'
elseif(string.len(hex) == 1) then hex = hex .. '0'
end
return hex
end
function mUI_HexFromColorTable(color_table) -- #ARGB
return format("#%s%s%s%s",
mUI_RGBToHex(color_table.a * 255),
mUI_RGBToHex(color_table.r * 255),
mUI_RGBToHex(color_table.g * 255),
mUI_RGBToHex(color_table.b * 255)
)
end
function mUI_HexFromColorTableToString(color_table) -- #ARGB
return format("|c%s%s%s%s",
mUI_RGBToHex(color_table.a * 255),
mUI_RGBToHex(color_table.r * 255),
mUI_RGBToHex(color_table.g * 255),
mUI_RGBToHex(color_table.b * 255)
)
end
function mUI_HexFromColors(a,r,g,b) -- #ARGB
return format("#%s%s%s%s", mUI_RGBToHex(a * 255), mUI_RGBToHex(r * 255), mUI_RGBToHex(g * 255), mUI_RGBToHex(b * 255))
end
function mUI_HexToARGB(hex)
hex = hex:gsub("#","")
return tonumber("0x"..hex:sub(1,2)), tonumber("0x"..hex:sub(3,4)), tonumber("0x"..hex:sub(5,6)), tonumber("0x"..hex:sub(7,8))
end
function mUI_HexToARGBFloats(hex)
hex = hex:gsub("#","")
return tonumber("0x"..hex:sub(1,2)) / 255.0, tonumber("0x"..hex:sub(3,4)) / 255.0, tonumber("0x"..hex:sub(5,6)) / 255.0, tonumber("0x"..hex:sub(7,8)) / 255.0
end
function mUI_GetColor(color)
return color.r, color.g, color.b, color.a
end
function mUI_DebugError(message, debugstack_depth)
--if(mui_global==nil or mUI_GetVariableValue(mui_global["DEBUG"]) == false) then return end
local debugmessage = debugstack(debugstack_depth or 2,1,1) or ""
DEFAULT_CHAT_FRAME:AddMessage("|cffff5555Error: " .. tostring(message) .."\n"..debugmessage)
--if(MUI_DEBUG_STACK_DEPTH > 0) then DEFAULT_CHAT_FRAME:AddMessage("|cffffaaaa " .. debugmessage) end
end
function mUI_DebugMessage(message)
if(mui_global==nil or mUI_GetVariableValue(mui_global["DEBUG"]) == false) then return end
DEFAULT_CHAT_FRAME:AddMessage("|cffffff22DEBUG:|r |cffffff88" .. tostring(message))
end
function mUI_PrintMessage(message)
DEFAULT_CHAT_FRAME:AddMessage(tostring(message))
end
function mUI_EventIsEither(evt, ...)
local args = {...}
for i, v in ipairs(args) do
if(evt == v) then return true end
end
return false
end
function mUI_EventRegisterList(frame, ...)
local args = {...}
for i, v in ipairs(args) do
frame:RegisterEvent(v)
end
end
function mUI_GetClassColor(target)
local _, class = UnitClass(target)
local colortable = mui_global["ClassColors"].value
local color = colortable[class]
if(color ~= nil)
then
return color
else
if(UnitIsEnemy("player", target)) then
return {r=0.72, g=0.0, b=0.0, a=1.0}
else
return {r=.0, g=0.72, b=0.0, a=1.0}
end
end
end
function mUI_GetPowerColor(target)
local power = UnitPowerType(target) + 1
local colortable = mUI_GetVariableValue(mui_global["PowerColors"])
local color = colortable[power]
if(color ~= nil)
then
return color
else
return {r=0.1, g=0.1, b=0.1, a=1.0}
end
end
-- General UI stuff
--
function mUI_AddHighlight(frame, highlight_color, botattach)
frame:EnableMouse(true)
local highlight = frame:CreateTexture()
highlight:SetHeight(1)
highlight:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 1, -1)
highlight:SetPoint("BOTTOMRIGHT", botattach or frame, "BOTTOMRIGHT", -1, 1)
if(highlight_color ~= nil)
then
highlight:SetTexture(highlight_color.r, highlight_color.g, highlight_color.b, highlight_color.a)
else
highlight:SetTexture(.5, .5, .5, .1)
end
highlight:Hide()
frame:SetScript("OnEnter", function () highlight:Show() end)
frame:SetScript("OnLeave", function () highlight:Hide() end)
end
function mUI_CreateDefaultFrame(parent, name, width, height, strata, backdrop, bg_color, border_color)
local default_backdrop = {
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 8,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
}
local frame = CreateFrame("Frame", name, parent or UIParent)
frame:SetFrameStrata(strata or "LOW")
frame:SetWidth(width or 64)
frame:SetHeight(height or 64)
frame:SetPoint("CENTER", UIParent, "CENTER")
frame:SetBackdrop(backdrop or default_backdrop)
if(bg_color ~= nil)
then
frame:SetBackdropColor(bg_color.r, bg_color.g, bg_color.b, bg_color.a)
else
frame:SetBackdropColor(.1, .1, .1, 1)
end
if(border_color ~= nil)
then
frame:SetBackdropBorderColor(border_color.r, border_color.g, border_color.b, border_color.a)
else
frame:SetBackdropBorderColor(.6, .6, .6, 1)
end
return frame
end
function mUI_CreateDefaultButton(parent, name, text, width, height, fontsize, highlight_color)
--local font = "Interface\\Addons\\minimalUI\\Fonts\\homespun.ttf"
local font = "Interface\\Addons\\minimalUI\\Fonts\\visitor1.ttf"
local default_backdrop = {
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 16,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
}
local button = CreateFrame("Button", nil, parent)
button:SetPoint("CENTER", parent, "CENTER", 0, 0)
button:SetHeight(height or 18)
button:SetWidth(width or 64)
button:SetBackdrop(default_backdrop)
button:SetBackdropColor(.15, .15, .15, 1)
button:SetBackdropBorderColor(.4, .4, .4, 1)
button:SetFont(font, fontsize or 12)
button:SetText(text)
button:SetTextColor(1, 1, 1, 1)
local highlight = button:CreateTexture()
highlight:SetPoint("TOPLEFT", button, "TOPLEFT", 1, -1)
highlight:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", -1, 1)
if(highlight_color ~= nil)
then
highlight:SetTexture(highlight_color.r, highlight_color.g, highlight_color.b, highlight_color.a)
else
highlight:SetTexture(.5, .5, .5, .1)
end
button:SetHighlightTexture(highlight)
return button
end
function mUI_CreateDefaultScrollframe(parent, name, width, height)
local default_backdrop = {
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 16,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
}
local frame = CreateFrame("Frame", name, UIParent)
frame:SetWidth(width or 120)
frame:SetHeight(height or 120)
frame:SetPoint("LEFT", UIParent, 'LEFT', 0, 0)
frame:SetFrameStrata('DIALOG')
frame:SetBackdrop(default_backdrop)
frame:SetBackdropColor(.1, .1, .1, 1)
frame:SetBackdropBorderColor(.25, .25, .25, 1)
local scroll = CreateFrame("ScrollFrame", name.."ScrollFrame", UIParent, "UIPanelScrollFrameTemplate")
scroll:SetPoint('TOPLEFT', frame, 'TOPLEFT', 10, -7)
scroll:SetPoint('BOTTOMRIGHT', frame, 'BOTTOMRIGHT', -30, 5)
frame.scroll = scroll
return frame
end
function mUI_CreateDefaultEditbox(parent, value, width, height, justifiyV, justifiyH)
local font = "Interface\\Addons\\minimalUI\\Fonts\\LiberationMono-Regular.ttf"
local default_backdrop = {
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 16,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
}
local editbox = CreateFrame("Editbox", nil, parent)
editbox:SetHeight(height or 18)
editbox:SetWidth(width or 64)
editbox:SetFont(font, 11)
editbox:SetTextInsets(4,4,4,4)
editbox:SetAutoFocus(false)
editbox:SetPoint("CENTER", parent, "CENTER", 0, 0)
editbox:SetScript("OnEscapePressed", function() this:ClearFocus() end)
editbox:SetScript("OnTabPressed", function() if this.next then this.next:SetFocus() end end)
editbox:SetScript("OnEditFocusGained", function() this.hasFocus = true this:HighlightText() end)
editbox:SetScript("OnEditFocusLost", function() this.hasFocus = false this:HighlightText(0,0) end)
editbox.hasFocus = false
editbox:SetBackdrop(default_backdrop)
editbox:SetBackdropColor(.25, .25, .25, .9)
editbox:SetBackdropBorderColor(.4, .4, .4, 1)
editbox:SetText(value)
if(justifiyV ~= nil and justifiyV ~= "") then editbox:SetJustifyV(justifiyV) end
if(justifiyH ~= nil and justifiyH ~= "") then editbox:SetJustifyH(justifiyH) end
return editbox
end
function mUI_CreateColorPicker(parent, callback, width, height, initial_color)
local default_backdrop = {
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 16,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
}
local picker = CreateFrame("Button", nil, parent)
picker:SetWidth(width or 18)
picker:SetHeight(height or 18)
picker:SetBackdrop(default_backdrop)
if(initial_color ~= nil)
then
picker:SetBackdropColor(initial_color.r, initial_color.g, initial_color.b, initial_color.a)
else
picker:SetBackdropColor(1, 1, 1, 1)
end
picker:SetPoint("CENTER", parent)
picker.callback = callback
local picker_interval = 10
picker.internal = function()
if(picker_current == nil) then picker_current = 0 end
if(picker_current > picker_interval or picker.released_mouse) then
local a, r, g, b = OpacitySliderFrame:GetValue(), ColorPickerFrame:GetColorRGB();
picker:SetBackdropColor(r, g, b, a)
if picker.callback then picker:callback(r, g, b, a) end
picker_current = 0
else
picker_current = picker_current + 1
end
end
picker.cancel = function ()
picker:SetBackdropColor(unpack(ColorPickerFrame.previousValues))
if picker.callback then picker:callback(unpack(ColorPickerFrame.previousValues)) end
end
picker:SetScript("OnClick", function()
local r,g,b,a = picker:GetBackdropColor()
ColorPickerFrame.hasOpacity = true
ColorPickerFrame.opacity = a
ColorPickerFrame.func = this.internal
ColorPickerFrame.cancelFunc = this.cancel
ColorPickerFrame.previousValues = {r,g,b,a};
ColorPickerFrame.opacityFunc = this.internal
ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG")
ColorPickerFrame:Hide(); -- Need to run the OnShow handler.
OpacitySliderFrame:SetValue(a)
ColorPickerFrame:Show();
ColorPickerFrame:SetColorRGB(r,g,b);
end)
if(firstInit == nil) then
firstInit = true
ColorPickerFrame:SetScript("OnMouseUp", function()
picker.released_mouse = true
end)
ColorPickerFrame:SetScript("OnMouseDown", function()
picker.released_mouse = false
end)
OpacitySliderFrame:SetScript("OnMouseUp", function()
--picker.released_mouse = true
picker_current = 1
end)
OpacitySliderFrame:SetScript("OnMouseDown", function()
picker.released_mouse = false
end)
end
local highlight = picker:CreateTexture()
highlight:SetPoint("TOPLEFT", picker, "TOPLEFT", 1, -1)
highlight:SetPoint("BOTTOMRIGHT", picker, "BOTTOMRIGHT", -1, 1)
highlight:SetTexture(.3, .3, .3, .5)
picker:SetHighlightTexture(highlight)
picker:EnableMouse(true)
return picker
end
function mUI_FontString(frame, font, size, color, text, justifiyV, justifiyH)
--local deffont = "Interface\\Addons\\minimalUI\\Fonts\\visitor1.ttf"
local deffont = "Interface\\Addons\\minimalUI\\Fonts\\LiberationMono-Bold.ttf"
if(frame == nil) then return end
local fontstring = frame:CreateFontString(nil)
fontstring:SetAllPoints(frame)
fontstring:SetFont(font or deffont, 11)
if(color ~= nil)
then
fontstring:SetTextColor(color.r, color.g, color.b, color.a)
else
fontstring:SetTextColor(1,1,1,1)
end
fontstring:SetShadowColor(0,0,0,1)
fontstring:SetShadowOffset(1,-1)
fontstring:SetText(text or "")
if(justifiyV ~= nil and justifiyV ~= "") then fontstring:SetJustifyV(justifiyV) end
if(justifiyH ~= nil and justifiyH ~= "") then fontstring:SetJustifyH(justifiyH) end
return fontstring
end
function mUI_CreateCheckButton(parent)
local checkbutton = CreateFrame("CheckButton", nil, parent)
checkbutton:SetCheckedTexture("Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga")
local tex = checkbutton:GetCheckedTexture()
tex:ClearAllPoints()
tex:SetPoint("TOPLEFT", checkbutton, "TOPLEFT", 3, -3)
tex:SetPoint("BOTTOMRIGHT", checkbutton, "BOTTOMRIGHT", -3, 3)
tex:SetVertexColor(0.0,0.5,1.0,1)
local highlight = checkbutton:CreateTexture()
highlight:SetPoint("TOPLEFT", checkbutton, "TOPLEFT", 1, -1)
highlight:SetPoint("BOTTOMRIGHT", checkbutton, "BOTTOMRIGHT", -1, 1)
highlight:SetTexture(.3, .3, .3, .5)
checkbutton:SetHighlightTexture(highlight)
return checkbutton
end
function mUI_ComboBox(parent, combo_type, callback)
-- initialze a global set of dropdown menu items
if(MUI_COMBO_DROPDOWN == nil) then
MUI_COMBO_DROPDOWN = CreateFrame("Frame")
MUI_COMBO_DROPDOWN:SetBackdrop({
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 16,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
})
MUI_COMBO_DROPDOWN:SetFrameStrata("DIALOG")
MUI_COMBO_DROPDOWN:SetFrameLevel(5)
MUI_COMBO_DROPDOWN:SetBackdropColor(0,0,0,1)
MUI_COMBO_DROPDOWN:SetScript("OnUpdate", function (this, elapsed)
if(this.dt == nil) then this.dt = 0 end
if(MouseIsOver(this) or MouseIsOver(this.PARENT)) then
this.dt = 0
else
this.dt = this.dt + elapsed
if(this.dt >= .25) then
this:Hide()
this.dt = 0
end
end
end)
MUI_COMBO_DROPDOWN.FIELDS = {}
for index=1, 20 do
MUI_COMBO_DROPDOWN.FIELDS[index] = CreateFrame("Button", nil, MUI_COMBO_DROPDOWN)
MUI_COMBO_DROPDOWN.FIELDS[index].index = index
MUI_COMBO_DROPDOWN.FIELDS[index]:SetScript("OnClick", function (this, button)
if(MUI_COMBO_DROPDOWN.CALLBACK and MUI_COMBO_DROPDOWN._VALUES) then
local value = MUI_COMBO_DROPDOWN._VALUES[this.index]
MUI_COMBO_DROPDOWN.CALLBACK(MUI_COMBO_DROPDOWN.PARENT, this.index, value)
end
MUI_COMBO_DROPDOWN:Hide()
MUI_COMBO_DROPDOWN.dt = 0
end)
local highlight = MUI_COMBO_DROPDOWN.FIELDS[index]:CreateTexture()
highlight:SetPoint("TOPLEFT", MUI_COMBO_DROPDOWN.FIELDS[index], "TOPLEFT", 1, -1)
highlight:SetPoint("BOTTOMRIGHT", MUI_COMBO_DROPDOWN.FIELDS[index], "BOTTOMRIGHT", -1, 1)
highlight:SetTexture(.5, .5, .5, .1)
MUI_COMBO_DROPDOWN.FIELDS[index]:SetHighlightTexture(highlight)
end
MUI_COMBO_DROPDOWN:Hide()
end
local function MUI_COMBO_SET_VALUES(combobox, values, combo_type)
MUI_COMBO_DROPDOWN._VALUES = values
local height = 0
local last = MUI_COMBO_DROPDOWN
local offset = 0
for index, field in ipairs(MUI_COMBO_DROPDOWN.FIELDS) do
local value = values[index]
if(values[index]) then
field:SetPoint("TOPLEFT", last, "TOPLEFT", 0, offset)
field:SetPoint("TOPRIGHT", last, "TOPRIGHT", 0, offset)
if(combo_type == "FONT") then
field:SetNormalTexture("")
field:SetFont(value, combobox.value_height - 4)
local _,_,fontfile = strfind(value, "([^\\]+)[.]")
if(fontfile) then field:SetText(fontfile) end
elseif(combo_type == "TEXTURE") then
field:SetFont("Interface\\Addons\\minimalUI\\Fonts\\visitor1.ttf", 12, "OUTLINE")
field:SetText("")
field:SetNormalTexture(value)
local _,_,texturefile = strfind(value, "([^\\]+)[.]")
if(texturefile) then field:SetText(texturefile) end
else
field:SetFont("Interface\\Addons\\minimalUI\\Fonts\\visitor1.ttf", 12)
field:SetText(value)
end
field:SetHeight(combobox.value_height)
field:Show()
height = height + combobox.value_height
last = field
offset = -combobox.value_height
else
field:Hide()
end
end
MUI_COMBO_DROPDOWN:SetHeight(height)
end
-- Where callback gets this parameters passed CALLBACK(self, index, value)
local function MUI_COMBO_SET_CALLBACK(parent, callback)
MUI_COMBO_DROPDOWN.CALLBACK = callback
MUI_COMBO_DROPDOWN.PARENT = parent
end
local function MUI_COMBO_SET_BACKDROPCOLOR(r,g,b,a)
MUI_COMBO_DROPDOWN:SetBackdropColor(r,g,b,a-.05)
end
local function MUI_COMBO_SHOW(cbx)
MUI_COMBO_DROPDOWN:SetPoint("TOPLEFT", cbx, "BOTTOMLEFT")
MUI_COMBO_DROPDOWN:SetPoint("TOPRIGHT", cbx, "BOTTOMRIGHT")
MUI_COMBO_DROPDOWN:Show()
end
-----------------------------------------------------------------
local combobox = CreateFrame("Button", nil, parent)
combobox:SetFont("Interface\\Addons\\minimalUI\\Fonts\\visitor1.ttf", 16, "OUTLINE")
combobox.callback = callback
combobox.combo_type = combo_type
combobox.SetValueHeight = function (self, height)
self.value_height = height
end
combobox:SetValueHeight(18)
combobox:SetBackdrop({
bgFile = "Interface\\AddOns\\minimalUI\\img\\BackdropSolid.tga",
edgeFile = "",
tile = false, tileSize = 0, edgeSize = 16,
insets = { left = 0, right = 0, top = 0, bottom = 0 }
})
combobox:SetScript("OnClick", function ()
MUI_COMBO_SET_BACKDROPCOLOR(this:GetBackdropColor())
MUI_COMBO_SET_CALLBACK(this, this.callback)
if(this.combo_type == "FONT") then
MUI_COMBO_SET_VALUES(this, MUI_GLOBAL_FONT_TABLE, "FONT", this.value_height)
elseif(this.combo_type == "TEXTURE") then
MUI_COMBO_SET_VALUES(this, MUI_GLOBAL_TEXTURE_TABLE, "TEXTURE", this.value_height)
else
mUI_DebugMessage("unsupported dropdown type: " .. this.combo_type)
end
MUI_COMBO_SHOW(this)
end)
return combobox
end
|
local M = {}
function M.starts_with(str, start)
return str:sub(1, #start) == start
end
function M.end_with(str, ending)
return ending == "" or str:sub(-#ending) == ending
end
function M.split(s, delimiter)
local result = {}
for match in (s .. delimiter):gmatch("(.-)" .. delimiter) do
table.insert(result, match)
end
return result
end
function M.handle_job_data(data)
if not data then
return nil
end
if data[#data] == "" then
table.remove(data, #data)
end
if #data < 1 then
return nil
end
return data
end
function M.log(message)
vim.notify("[git] " .. message)
end
function M.jobstart(cmd, on_finish)
local has_error = false
local lines = {}
local function on_event(_, data, event)
if event == "stdout" then
data = M.handle_job_data(data)
if not data then
return
end
for i = 1, #data do
table.insert(lines, data[i])
end
elseif event == "stderr" then
data = M.handle_job_data(data)
if not data then
return
end
has_error = true
local error_message = ""
for _, line in ipairs(data) do
error_message = error_message .. line
end
M.log("Error during running a job: " .. error_message)
elseif event == "exit" then
if not has_error then
on_finish(lines)
end
end
end
vim.fn.jobstart(cmd, {
on_stderr = on_event,
on_stdout = on_event,
on_exit = on_event,
stdout_buffered = true,
stderr_buffered = true,
})
end
return M
|
local PlayersInGarage = {}
AddEvent("OnDimensionCreated", function(id, name)
if name == "base" then
for i, v in ipairs(garages) do
local obj = CreatePickupTrigger(2, v.entrance[1], v.entrance[2], v.entrance[3], false)
AddPickupInDimension(obj, id)
local text = CreateText3D("Garage " .. tostring(i), 16, v.entrance[1], v.entrance[2], v.entrance[3] + 100, 0, 0, 0)
AddText3DInDimension(text, id)
end
end
end)
function GetPlayerGarageId(ply)
for i,v in ipairs(PlayersInGarage) do
if v.ply == ply then
return i, v.garageid
end
end
return false
end
AddEvent("OnPlayerQuit", function(ply)
local i, garageid = GetPlayerGarageId(ply)
if i then
table.remove(PlayersInGarage, i)
end
end)
AddEvent("OnPlayerGarageAction", function(ply, pickup)
local garageid
local x, y, z = GetPickupLocation(pickup)
for i,v in ipairs(garages) do
if (v.entrance[1] == x and v.entrance[2] == y and v.entrance[3] == z) then
garageid = i
end
end
if garageid then
local owngarage
for i,v in ipairs(PlayerData[ply].garages) do
if v.id == garageid then
owngarage = true
SetPlayerLocation(ply, garages[garageid].exit[1], garages[garageid].exit[2], garages[garageid].exit[3])
local id = CreateDimension("garage", true)
AddPlayerInDimension(ply, id)
local tbl = {}
tbl.ply = ply
tbl.garageid = garageid
table.insert(PlayersInGarage, tbl)
local pickup = CreatePickupTrigger(2, garages[garageid].exit[1], garages[garageid].exit[2], garages[garageid].exit[3], false)
AddPickupInDimension(pickup, id)
local etext = CreateText3D("Exit", 16, garages[garageid].exit[1], garages[garageid].exit[2], garages[garageid].exit[3] + 100, 0, 0, 0)
AddText3DInDimension(etext, id)
local mobj = CreateObject(340, garages[garageid].manage[1], garages[garageid].manage[2], garages[garageid].manage[3] - 50, 0, 0, 0, 1, 1, 2)
AddObjectInDimension(mobj, id)
local text = CreateText3D("Manage Vehicles [E]", 16, garages[garageid].manage[1], garages[garageid].manage[2], garages[garageid].manage[3] + 100, 0, 0, 0)
AddText3DInDimension(text, id)
for k, v in pairs(v.vehicles) do
local veh = CreateVehicle(v.model, garages[garageid].vehicles[k][1], garages[garageid].vehicles[k][2], garages[garageid].vehicles[k][3]-50, garages[garageid].vehicles[k][4])
SetVehicleColor(veh, RGB(v.color[1], v.color[2], v.color[3], v.color[4]))
EnableVehicleBackfire(veh, true)
AttachVehicleNitro(veh, v.nitro)
SetVehiclePropertyValue(veh, "HasNitro", v.nitro, false)
SetVehiclePropertyValue(veh, "VehArmor", v.armor, false)
SetVehicleRespawnParams(veh, false)
--print(HexToRGBA(GetVehicleColor(veh)))
AddVehicleInDimension(veh, id)
end
end
end
if not owngarage then
if HasEnoughMoney(ply, garages[garageid].price) then
CallRemoteEvent(ply, "BuyGarageUI", garageid)
else
CallRemoteEvent(ply, "CreateNotification", "Garage", "You need " .. tostring(garages[garageid].price) .. "$ to buy this garage", 5000)
end
end
else
for i,v in ipairs(garages) do
if (v.exit[1] == x and v.exit[2] == y and v.exit[3] == z) then
garageid = i
end
end
if garageid then
SetPlayerLocation(ply, garages[garageid].entrance[1], garages[garageid].entrance[2], garages[garageid].entrance[3])
AddPlayerInDimension(ply, GetDimensionByName("base"))
table.remove(PlayersInGarage, GetPlayerGarageId(ply))
else
print("Error : Can't determine GarageAction Garage")
end
end
end)
AddRemoteEvent("BuyGarage", function(ply, garageid)
if Buy(ply, garages[garageid].price) then
local tbl = {}
tbl.id = garageid
tbl.vehicles = {}
table.insert(PlayerData[ply].garages, tbl)
CallRemoteEvent(ply, "CreateNotification", "Garage", "You bought this garage", 5000)
else
CallRemoteEvent(ply, "CreateNotification", "Garage", "You can't buy this garage", 5000)
end
end)
AddEvent("OnPlayerEnterVehicle", function(ply, veh, seat)
if GetDimensionName(GetPlayerDimension(ply)) == "garage" then
local i, garageid = GetPlayerGarageId(ply)
AddVehicleInDimension(veh, GetDimensionByName("base"))
SetVehiclePropertyValue(veh, "FromGarage", garageid, false)
SetVehicleLocation(veh, garages[garageid].vexit[1], garages[garageid].vexit[2], garages[garageid].vexit[3])
SetVehicleRotation(veh, 0, garages[garageid].vexit[4], 0)
AddPlayerInDimension(ply, GetDimensionByName("base"))
SetPlayerInVehicle(ply, veh, 1)
SetPlayerStoredVehicle(ply, veh)
table.remove(PlayersInGarage, i)
end
end)
AddRemoteEvent("SellVehicle", function(ply, veh)
if (IsValidPlayer(ply) and IsValidVehicle(veh)) then
local index, garageid = GetPlayerGarageId(ply)
if index then
if PlayerData[ply] then
if PlayerData[ply].garages[garageid] then
local price
for i, v in ipairs(car_dealer_vehicles) do
if v[1] == GetVehicleModel(veh) then
price = math.floor(v[2]*sell_vehicle_percentage/100)
end
end
if price then
for i, v in ipairs(PlayerData[ply].garages[garageid].vehicles) do
if v.model == GetVehicleModel(veh) then
local r, g, b, a = HexToRGBA(GetVehicleColor(veh))
if (v.color[1] == r and v.color[2] == g and v.color[3] == b and v.color[4] == a and v.nitro == GetVehiclePropertyValue(veh, "HasNitro") and v.armor == GetVehiclePropertyValue(veh, "VehArmor")) then
DestroyVehicle(veh)
table.remove(PlayerData[ply].garages[garageid].vehicles, i)
Sell(ply, price)
CallRemoteEvent(ply, "CreateNotification", "Garage", "You sold the vehicle for " .. tostring(price) .. "$", 5000)
break
end
end
end
end
end
end
end
end
end)
AddRemoteEvent("GetGaragesMove", function(ply)
if IsValidPlayer(ply) then
local index, garageid = GetPlayerGarageId(ply)
if (index and PlayerData[ply]) then
local tbl = {}
for i,v in ipairs(PlayerData[ply].garages) do
if v.id ~= garageid then
local tblinsert = {}
tblinsert.id = v.id
tblinsert.freeslots = table_count(garages[v.id].vehicles) - table_count(v.vehicles)
if tblinsert.freeslots > 0 then
table.insert(tbl, tblinsert)
end
end
end
if table_count(tbl) > 0 then
CallRemoteEvent(ply,"SendGaragesMove", tbl)
else
CallRemoteEvent(ply,"SendGaragesMove", false)
end
else
CallRemoteEvent(ply,"SendGaragesMove", false)
end
end
end)
AddRemoteEvent("MoveGarageVehicle", function(ply, veh, movegarageid)
if (IsValidPlayer(ply) and IsValidVehicle(veh)) then
local index, garageid = GetPlayerGarageId(ply)
if index then
if PlayerData[ply] then
local movegarageid2
for i,v in ipairs(PlayerData[ply].garages) do
if v.id == movegarageid then
movegarageid2 = i
end
end
if (PlayerData[ply].garages[garageid] and movegarageid2) then
local vehicletbl
for i, v in ipairs(PlayerData[ply].garages[garageid].vehicles) do
if v.model == GetVehicleModel(veh) then
local r, g, b, a = HexToRGBA(GetVehicleColor(veh))
if (v.color[1] == r and v.color[2] == g and v.color[3] == b and v.color[4] == a and v.nitro == GetVehiclePropertyValue(veh, "HasNitro") and v.armor == GetVehiclePropertyValue(veh, "VehArmor")) then
vehicletbl = v
DestroyVehicle(veh)
table.remove(PlayerData[ply].garages[garageid].vehicles, i)
break
end
end
end
if vehicletbl then
table.insert(PlayerData[ply].garages[movegarageid2].vehicles, vehicletbl)
CallRemoteEvent(ply, "CreateNotification", "Garage", "Moved vehicle " .. tostring(vehicletbl.model) .. " to garage " .. tostring(movegarageid), 5000)
else
print("Error : Can't find vehicle to move")
end
end
end
end
end
end)
|
-----------------------------------
-- Area: Batallia Downs (105)
-- Mob: Skirling Liger
-----------------------------------
require("scripts/globals/status");
-----------------------------------
function onMobEngaged(mob,target)
mob:setMod(tpz.mod.REGAIN, 50);
end;
function onMobDisengage(mob)
mob:setMod(tpz.mod.REGAIN,0);
end;
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
UpdateNMSpawnPoint(mob:getID());
end;
|
--[[
################################################################################
#
# Copyright (c) 2014-2016 Ultraschall (http://ultraschall.fm)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
################################################################################
]]
current_position = reaper.GetPlayPosition() -- Position of play-cursor
retval, retvals_csv = reaper.GetUserInputs("Insert chapter marker", 1, "Name of this chapter marker:", "") -- User input box
if retval == true then -- User pressed ok
markername = retvals_csv
reaper.AddProjectMarker(0, false, current_position, 0 , markername, -1) -- Place named marker
end -- Else = user pressed cancel, so nothing to do here.
|
local hex={
u8=function(num) return string.format("%02X",num) end,
s8=function(num) return string.format("%02X",num) end,
u16=function(num) return string.format("%04X",num) end,
s16=function(num) return string.format("%04X",num) end,
u32=function(num) return string.format("%08X",num) end,
s32=function(num) return string.format("%08X",num) end
};
return hex;
|
local KEYS = require('constants').KEYS
local resizeMappings = {
h = {x = 0, y = 0, w = 0.5, h = 1},
j = {x = 0.25, y = 0.35, w = 0.5, h = 0.65},
u = {x = 0, y = 0, w = 0.5, h = 0.5},
o = {x = 0.5, y = 0, w = 0.5, h = 0.5},
m = {x = 0.5, y = 0.5, w = 0.5, h = 0.5},
l = {x = 0.5, y = 0, w = 0.5, h = 1},
n = {x = 0, y = 0, w = 1, h = 1},
i = {x = 0.13, y = 0, w = 0.87, h = 1}
}
for key in pairs(resizeMappings) do
hs.hotkey.bind(KEYS.A, key, function()
local win = hs.window.focusedWindow()
if win then win:moveToUnit(resizeMappings[key]) end
end, 0)
end
|
--[[ Hazardous EnVironment Suit Voice Pack ]]
RegisterSuitVoicePack( "Opposing Force", "opfor", "////////////////////////////////////////////////////////////////\n// H.E.V. Suit Voice Pack - Opposing Force\n////////////////////////////////////////////////////////////////\n\n// Initialization\nHEV_OPFOR_AAx player/pcv_vest\nHEV_OPFOR_A0 player/pcv_vest\n\n// Vital Sign Monitoring\nHEV_OPFOR_DMG0 fvox/boop\n\nHEV_OPFOR_SHOCK fvox/boop\nHEV_OPFOR_FIRE fvox/boop\n\n// High Impact Reactive Armor\nHEV_OPFOR_0P fvox/fuzz\nHEV_OPFOR_1P fvox/fuzz\nHEV_OPFOR_2P fvox/fuzz\nHEV_OPFOR_3P fvox/fuzz\nHEV_OPFOR_4P fvox/fuzz\nHEV_OPFOR_5P fvox/fuzz\nHEV_OPFOR_6P fvox/fuzz\nHEV_OPFOR_7P fvox/fuzz\nHEV_OPFOR_8P fvox/fuzz\nHEV_OPFOR_9P fvox/fuzz\nHEV_OPFOR_10P fvox/fuzz\nHEV_OPFOR_11P fvox/fuzz\nHEV_OPFOR_12P fvox/fuzz\nHEV_OPFOR_13P fvox/fuzz\nHEV_OPFOR_14P fvox/fuzz\nHEV_OPFOR_15P fvox/fuzz\nHEV_OPFOR_16P fvox/fuzz\nHEV_OPFOR_17P fvox/fuzz\nHEV_OPFOR_18P fvox/fuzz\nHEV_OPFOR_19P fvox/fuzz\n\n// Munition Level Monitoring\nHEV_OPFOR_AMO0 fvox/blip\n\n// Atmospheric Contaminant Sensors\nHEV_OPFOR_DET0 fvox/blip blip blip\nHEV_OPFOR_DET1 fvox/blip blip blip\nHEV_OPFOR_DET2 fvox/blip blip blip\n" );
-- Opposing Force went for minimalism with these voice lines.
local function SetSuitUpdate( ply, sentence )
if ( ply.suitPlaylistPack == "opfor" ) then
if ( string.StartWith( sentence, "MED" ) ) then
return true;
end
if ( string.StartWith( sentence, "HEAL" ) ) then
return true;
end
if ( sentence != "DMG0" && string.StartWith( sentence, "DMG" ) ) then
return true;
end
if ( string.StartWith( sentence, "HLTH" ) ) then
return true;
end
end
end
hook.Add( "SetSuitUpdate", "SuitVoicePack_OPFOR_SetSuitUpdate", SetSuitUpdate );
|
math.randomseed( os.time() )
-- Fisher-Yates shuffle from http://santos.nfshost.com/shuffling.html
function shuffle(t)
for i = 1, #t - 1 do
local r = math.random(i, #t)
t[i], t[r] = t[r], t[i]
end
end
-- builds a width-by-height grid of trues
function initialize_grid(w, h)
local a = {}
for i = 1, h do
table.insert(a, {})
for j = 1, w do
table.insert(a[i], true)
end
end
return a
end
-- average of a and b
function avg(a, b)
return (a + b) / 2
end
dirs = {
{x = 0, y = -2}, -- north
{x = 2, y = 0}, -- east
{x = -2, y = 0}, -- west
{x = 0, y = 2}, -- south
}
function make_maze(w, h)
w = w or 16
h = h or 8
local map = initialize_grid(w*2+1, h*2+1)
function walk(x, y)
map[y][x] = false
local d = { 1, 2, 3, 4 }
shuffle(d)
for i, dirnum in ipairs(d) do
local xx = x + dirs[dirnum].x
local yy = y + dirs[dirnum].y
if map[yy] and map[yy][xx] then
map[avg(y, yy)][avg(x, xx)] = false
walk(xx, yy)
end
end
end
walk(math.random(1, w)*2, math.random(1, h)*2)
local s = {}
for i = 1, h*2+1 do
for j = 1, w*2+1 do
if map[i][j] then
table.insert(s, '#')
else
table.insert(s, ' ')
end
end
table.insert(s, '\n')
end
return table.concat(s)
end
print(make_maze())
|
BASE.name = "Base Vehicle"
BASE.uniqueID = "base_vehicle"
BASE.weight = 1
BASE.category = "Vehicle"
BASE.functions = {}
BASE.cantdrop = true
BASE.rotate = 90
BASE.seats = {}
BASE.CanTransfer = false
BASE.sellFactor = .5
BASE.numplate = {
}
local function honk_init( vehicle )
vehicle.snd_honk = CreateSound( vehicle, "npc/attack_helicopter/aheli_crash_alert2.wav" )
vehicle.snd_honk:ChangePitch( 150, 0 )
end
BASE.postSpawn = honk_init
local function honk( player, vehicle ) -- pretty example of vehicle think.
if player:KeyDown( IN_ATTACK ) then
if !vehicle.bool_honk then
vehicle.bool_honk = true
vehicle.snd_honk:Play()
player:ChatPrint( "HONK HONK" )
end
else
if vehicle.bool_honk then
vehicle.bool_honk = false
vehicle.snd_honk:Stop()
end
end
end
BASE.vehicleThink = honk
local aprefix = "VR."
local asuffix = ""
function numberAssgin()
local str = aprefix .. math.random( 11111,99999 ) .. asuffix
return str
end
numberAssgin()
BASE.functions.Use = {
alias = "Spawn Vehicle",
tip = "Spawn the vehicle in front of you.",
icon = "icon16/car_add.png",
run = function(itemTable, client, data, entity)
if (SERVER) then
local vehicle = client:SpawnVehicle( itemTable, data, entity )
if !vehicle:IsValid() then
nut.util.Notify(nut.lang.Get( "vehicle_failed" ), client)
return false
else
local idat = table.Copy( data )
idat.onworld = true
if !idat.number then
-- TODO:add manual assign
nut.util.Notify(nut.lang.Get( "vehicle_register_auto" ), client)
idat.number = numberAssgin()
nut.util.Notify( idat.number, client)
vehicle:SetNetVar( "number", idat.number )
end
client:UpdateInv( itemTable.uniqueID, -1, data )
client:UpdateInv( itemTable.uniqueID, 1, idat )
nut.util.Notify(nut.lang.Get( "vehicle_spawned" ), client)
vehicle:EmitSound( "ambient/machines/teleport1.wav" )
return false
end
end
end,
shouldDisplay = function( itemTable, data, entity)
return !LocalPlayer():GetNetVar( "spawned_vehicle" )
end
}
BASE.functions.Store = {
alias = "Store Vehicle",
tip = "Spawn the vehicle in front of you.",
icon = "icon16/car_delete.png",
run = function(itemTable, client, data, entity)
if (SERVER) then
if client:GetNetVar( "spawned_vehicle" ) then
if data.onworld then
local found = false
for k, v in pairs( ents.FindInSphere( client:GetPos(), 200 ) ) do
if v:GetClass() == "prop_vehicle_jeep" then
if client:GetNetVar( "spawned_vehicle" ) == v:EntIndex() then
local idat = table.Copy( data )
idat.onworld = false
client:UpdateInv( itemTable.uniqueID, -1, data )
client:UpdateInv( itemTable.uniqueID, 1, idat )
client:SetNetVar( "spawned_vehicle", nil )
nut.util.Notify( nut.lang.Get( "vehicle_stored" ), client)
v:Remove()
client:EmitSound( "doors/metal_stop1.wav" )
found = true
break
end
end
end
if !found then
nut.util.Notify(nut.lang.Get( "vehicle_cantfind" ), client)
end
else
nut.util.Notify(nut.lang.Get( "vehicle_alreadyspawned" ), client)
end
return false
end
end
end,
shouldDisplay = function( itemTable, data, entity)
if data.onworld then
if LocalPlayer():GetNetVar( "spawned_vehicle" ) then
return true
end
end
return false
end
}
BASE.functions.Sell = {
alias = "Sell Vehicle",
tip = "Spawn the vehicle in front of you.",
icon = "icon16/money.png",
run = function(itemTable, client, data, entity)
if (SERVER) then
if data.onworld then
nut.util.Notify(nut.lang.Get( "vehicle_cantsell_out" ), client)
return false
else
nut.util.Notify(nut.lang.Get( "vehicle_sold", nut.currency.GetName( itemTable.price*itemTable.sellFactor ) ), client)
client:GiveMoney( itemTable.price*itemTable.sellFactor )
return true
end
end
end,
shouldDisplay = function( itemTable, data, entity)
if !data.onworld then
return true
end
return false
end
}
|
SoundManager.deploy = function (slot0)
return
end
SoundManager.unloadGameEffect = function (slot0, slot1)
slot4 = slot0
slot7 = slot1
slot0.unloadEffect(slot3, ResConfig.getSoundPath(slot6))
end
SoundManager.preloadGameEffect = function (slot0, slot1)
slot4 = slot0
slot7 = slot1
slot0.preloadEffect(slot3, ResConfig.getSoundPath(slot6))
end
SoundManager.playDefaultBtnClickSound = function (slot0)
return
end
SoundManager.playGameEffect = function (slot0, slot1, slot2, slot3)
slot6 = slot1
if StringUtil.isStringValid(slot5) then
slot9 = slot1
slot9 = slot3
return slot0.playEffect(slot5, slot0, ResConfig.getSoundPath(slot8), slot2)
end
return nil
end
return
|
local vmf = get_mod("VMF")
-- ####################################################################################################################
-- ##### Locals and Variables #########################################################################################
-- ####################################################################################################################
-- hook_type is an identifier to help distinguish the different api calls.
local HOOK_TYPES = {
hook = 1,
hook_safe = 2,
hook_origin = 3,
}
-- Constants to ease on table lookups when not needed
local HOOK_TYPE_NORMAL = 1
local HOOK_TYPE_SAFE = 2
local HOOK_TYPE_ORIGIN = 3
--[[ Planned registry structure:
_registry[self][orig] = { active = true}
_registry.hooks[hook_type]
_registry.origs
]]
-- dont need to attach this to registry.
local _delayed = {}
local _delaying_enabled = true
-- This metatable will automatically create a table entry if one doesnt exist.
-- This lets us easily do _registry[self] without having to worry about nil-checking it.
local auto_table_meta = {__index = function(t, k) t[k] = {} return t[k] end }
local _registry = setmetatable({}, auto_table_meta)
-- This table will hold all of the hooks, in the format of _registry.hooks[hook_type]
_registry.hooks = {
-- Do the same thing with these tables to allow .hooks[hook_type][orig] without a ton of nil-checks.
setmetatable({}, auto_table_meta), -- normal
setmetatable({}, auto_table_meta), -- safe
-- Since there can only be one origin per function, it doesnt need to generate a table.
{}, -- origin
}
_registry.origs = {}
-- ####################################################################################################################
-- ##### Util functions ###############################################################################################
-- ####################################################################################################################
local function is_orig_hooked(obj, method)
local orig_registry = _registry.origs
if obj and orig_registry[obj] and orig_registry[obj][method] then
return true
elseif orig_registry[method] then
return true
end
return false
end
-- Since we replace the original function, we need to keep its reference around.
-- This will grab the cached reference if we hooked it before, otherwise return the function.
local function get_orig_function(self, obj, method)
if obj then
if is_orig_hooked(obj, method) then
return _registry.origs[obj][method]
else
return obj[method]
end
else
if is_orig_hooked(obj, method) then
return _registry.origs[method]
else
return rawget(_G, method)
end
end
end
-- Return an object from the global table. Second return value is if it was successful.
local function get_object_reference(obj)
if type(obj) == "table" then
return obj, true
elseif type(obj) == "string" then
local obj_table = rawget(_G, obj)
if obj_table then
return obj_table, true
end
end
return obj, false
end
-- VT1 hooked everything using a "Obj.Method" string
-- Add backward compatibility for that format.
local function split_function_string(str)
local find_position = string.find(str, "%.")
local method, obj
if find_position then
method = string.sub(str, find_position + 1)
obj = string.sub(str, 1, find_position - 1)
else
method = str
end
return method, obj
end
-- We need to get the number of return values for accurate unpacking
-- This is based on Lupo/Propjoe table.pack, but without putting the number inside the table
local function get_return_values(...)
local num = select('#', ...)
return num, { ... }
end
-- ####################################################################################################################
-- ##### Hook Creation ################################################################################################
-- ####################################################################################################################
-- For any given original function, return the newest entry of the hook_chain.
-- Since all hooks of the chain contain the call to the previous one, we don't need to do any manual loops.
-- This continues until the end of the chain, where the original function is called.
local function get_hook_chain(orig)
local hook_registry = _registry.hooks
local hooks = hook_registry[HOOK_TYPE_NORMAL][orig]
if hooks and #hooks > 0 then
return hooks[#hooks]
end
-- We can't simply return orig here, or it would cause origins to depend on load order.
return function(...)
if hook_registry[HOOK_TYPE_ORIGIN][orig] then
return hook_registry[HOOK_TYPE_ORIGIN][orig](...)
else
return orig(...)
end
end
end
-- Returns a function closure with all the information needed for a given hook to be handled correctly.
local function create_specialized_hook(self, orig, handler, hook_type)
local func
local hook_data = _registry[self][orig]
-- Determine the previous function in the hook stack
-- Note: If a previous hook is removed from the table, these functions wouldn't be updated
-- This would break the chain, solution is to not remove the hooks, simply make them inactive
-- Make sure inactive hooks that rely on the chain still call the next function seamlessly.
local previous_hook = get_hook_chain(orig)
if hook_type == HOOK_TYPE_NORMAL then
func = function(...)
if hook_data.active then
return handler(previous_hook, ...)
else
return previous_hook(...)
end
end
-- Make sure hook_origin directly calls the original function if inactive.
elseif hook_type == HOOK_TYPE_ORIGIN then
func = function(...)
if hook_data.active then
return handler(...)
else
return orig(...)
end
end
elseif hook_type == HOOK_TYPE_SAFE then
func = function(...)
if hook_data.active then
vmf.xpcall_no_return_values(self, "(safe_hook)", handler, ...)
end
end
end
return func
end
-- The hook system makes internal functions that replace the original function and handles all the hooks.
local function create_internal_hook(orig, obj, method)
local fn = function(...)
-- Execute the hook chain. Note that we need to keep the return values
-- in case another function depends on them.
local hook_chain = get_hook_chain(orig)
-- We need to keep return values in case another function depends on them
local num_values, values = get_return_values( hook_chain(...) )
local safe_hooks = _registry.hooks[HOOK_TYPE_SAFE][orig]
if safe_hooks and #safe_hooks > 0 then
for i = 1, #safe_hooks do safe_hooks[i](...) end
end
return unpack(values, 1, num_values)
end
if obj then
-- object cannot be a string at this point, so we don't need to check for that.
if not _registry.origs[obj] then _registry.origs[obj] = {} end
_registry.origs[obj][method] = orig
obj[method] = fn
else
_registry.origs[method] = orig
_G[method] = fn
end
end
local function create_hook(self, orig, obj, method, handler, func_name, hook_type)
self:info("(%s): Hooking '%s' from [%s] (Origin: %s)", func_name, method, obj or "_G", orig)
if not is_orig_hooked(obj, method) then
create_internal_hook(orig, obj, method)
end
-- Check to make sure it wasn't hooked before
if not _registry[self][orig] then
_registry[self][orig] = { active = self:is_enabled() }
local hook_registry = _registry.hooks[hook_type]
-- Add to the hook to registry. Origin hooks are unique, so we check for that too.
if hook_type == HOOK_TYPE_ORIGIN then
if hook_registry[orig] then
self:error("(%s): Attempting to hook origin of already hooked function %s", func_name, method)
else
hook_registry[orig] = create_specialized_hook(self, orig, handler, hook_type)
end
else
table.insert(hook_registry[orig], create_specialized_hook(self, orig, handler, hook_type) )
end
else
-- This should be a warning log, but currently there are no differences between warning and error.
-- Wouldn't want to scare users that mods are broken because this used to be acceptable.
if vmf:get("developer_mode") then
self:warning("(%s): Attempting to rehook already active hook %s.", func_name, method)
else
self:info("(%s): Attempting to rehook already active hook %s.", func_name, method)
end
end
end
-- ####################################################################################################################
-- ##### GENERIC API ##################################################################################################
-- ####################################################################################################################
-- Singular functions that works on a generic basis so the VMFMod API can be tailored for user simplicity.
-- Valid styles:
-- Giving a string pointing to a global object table and method string and hook function
-- self, string (obj), string (method), function (handler), string (func_name)
-- Giving an object table and a method string and hook function
-- self, table (obj), string (method), function (handler), string (func_name)
-- Giving a method string or a Obj.Method string (VT1 Style) and a hook function
-- self, string (method), function (handler), nil, string (func_name)
local function generic_hook(self, obj, method, handler, func_name)
if vmf.check_wrong_argument_type(self, func_name, "obj", obj, "string", "table", "nil") or
vmf.check_wrong_argument_type(self, func_name, "method", method, "string", "function") or
vmf.check_wrong_argument_type(self, func_name, "handler", handler, "function", "nil")
then
return
end
-- Adjust the arguments.
if type(method) == "function" then
handler = method
method, obj = split_function_string(obj)
if not method then
self:error("(%s): trying to create hook without giving a method name. %s", func_name)
return
end
end
-- Get hook_type based on name
local hook_type = HOOK_TYPES[func_name]
-- Grab the object's reference, if this fails, obj will remain a string and the hook will be delayed.
local obj, success = get_object_reference(obj) --luacheck: ignore
if obj and not success then
if _delaying_enabled and type(obj) == "string" then
-- Call this func at a later time, using upvalues.
self:info("(%s): [%s.%s] needs to be delayed.", func_name, obj, method)
table.insert(_delayed, function()
generic_hook(self, obj, method, handler, func_name)
end)
return
else
self:error("(%s): trying to hook object that doesn't exist: %s", func_name, obj)
return
end
end
-- Quick check to make sure the target exists
if obj and not obj[method] then
self:error("(%s): trying to hook method that doesn't exist: [%s.%s]", func_name, obj, method)
return
elseif not obj and not rawget(_G, method) then
self:error("(%s): trying to hook function that doesn't exist: [%s]", func_name, method)
return
end
-- obj can't be a string for these now.
local orig = get_orig_function(self, obj, method)
if type(orig) ~= "function" then
self:error("(%s): trying to hook %s (a %s), not a function.", func_name, method, type(orig))
return
end
return create_hook(self, orig, obj, method, handler, func_name, hook_type)
end
local function generic_hook_toggle(self, obj, method, enabled_state)
local func_name = (enabled_state) and "hook_enable" or "hook_disable"
if vmf.check_wrong_argument_type(self, func_name, "obj", obj, "string", "table") or
vmf.check_wrong_argument_type(self, func_name, "method", method, "string", "nil") then
return
end
-- Adjust the arguments.
if not method then
if type(obj) == "string" then
method, obj = split_function_string(obj)
else
self:error("(%s): trying to toggle hook without giving a method name. %s", func_name)
end
end
local obj, success = get_object_reference(obj) --luacheck: ignore
if obj and not success then
if _delaying_enabled and type(obj) == "string" then
-- Call this func at a later time, using upvalues.
self:info("(%s): [%s.%s] needs to be delayed.", func_name, obj, method)
table.insert(_delayed, function()
generic_hook_toggle(self, obj, method, enabled_state)
end)
return
else
self:error("(%s): trying to toggle hook on object that doesn't exist: %s", func_name, obj)
return
end
end
local orig = get_orig_function(self, obj, method)
if _registry[self][orig] then
_registry[self][orig].active = enabled_state
else
-- This has the potential for mod-breaking behavior, but not guaranteed
self:warning("(%s): trying to toggle hook that doesn't exist: %s", func_name, method)
end
end
-- ####################################################################################################################
-- ##### VMFMod #######################################################################################################
-- ####################################################################################################################
-- :hook_safe() provides callback after a function is called. You have no control over the execution of the
-- original function, nor can you change its return values, making it much safer to use.
-- The handler is never given the a "func" parameter.
-- These will always be executed the original function and the hook chain.
function VMFMod:hook_safe(obj, method, handler)
return generic_hook(self, obj, method, handler, "hook_safe")
end
-- :hook() will allow you to hook a function, allowing your handler to replace the function in the stack,
-- and control its execution. All hooks on the same function will be part of a chain, with the
-- original function at the end. Your handler has to call the next function in the chain manually.
-- The chain of event is determined by mod load order.
function VMFMod:hook(obj, method, handler)
return generic_hook(self, obj, method, handler, "hook")
end
-- :hook_origin() allows you to directly hook a function, replacing it. The original function will bever be called.
-- This hook will not be part of the hook chain proper, instead taking the place of the original function.
-- This is similar to :back functionality that was sparsely used in old V1 mods.
-- The handler is never given the a "func" parameter.
-- This there is a limit of a single origin hook for any given function.
-- This should only be used as a last resort due to its limitation and its potential to break the game if not careful.
function VMFMod:hook_origin(obj, method, handler)
return generic_hook(self, obj, method, handler, "hook_origin")
end
-- Enable/disable functions for all hook types:
function VMFMod:hook_enable(obj, method) generic_hook_toggle(self, obj, method, true) end
function VMFMod:hook_disable(obj, method) generic_hook_toggle(self, obj, method, false) end
function VMFMod:enable_all_hooks()
self:info("(hooks): Enabling all hooks for mod: %s", self:get_name())
for _, hook_data in pairs(_registry[self]) do
hook_data.active = true
end
end
function VMFMod:disable_all_hooks()
self:info("(hooks): Disabling all hooks for mod: %s", self:get_name())
for _, hook_data in pairs(_registry[self]) do
hook_data.active = false
end
end
-- ####################################################################################################################
-- ##### VMF internal functions and variables #########################################################################
-- ####################################################################################################################
-- Remove all hooks when VMF is about to be reloaded
vmf.hooks_unload = function()
for key, value in pairs(_registry.origs) do
-- origs[method] = orig
if type(value) == "function" then
_G[key] = value
-- origs[obj][method] = orig
elseif type(value) == "table" then
for method, orig in pairs(value) do
key[method] = orig
end
end
end
end
vmf.apply_delayed_hooks = function(status, state)
if status == "enter" and state == "StateIngame" then
_delaying_enabled = false
end
if #_delayed > 0 then
vmf:info("Attempt to hook %s delayed hooks", #_delayed)
-- Go through the table in reverse so we don't get any issues removing entries inside the loop
for i = #_delayed, 1, -1 do
_delayed[i]()
table.remove(_delayed, i)
end
end
end
|
wrk.method = "POST"
wrk.body = '{ "token": "tuturu" }'
wrk.headers["Content-Type"] = "application/json"
--[[
wrk -c 32 -t 16 -s ./benchmark/Route.lua -d 10s http://localhost:3000/
--]]
|
package.loaded.utils = nil
local utils = require "utils"
local classInstantiate = utils.classInstantiate
local function createWindow(options)
-- Create Cheat Engine window
local window = createForm(true)
-- Window position {xpixels, ypixels}; if nil, put at center of screen
if options.windowPosition ~= nil then
window:setPosition(options.windowPosition[1], options.windowPosition[2])
else
window:centerScreen()
end
-- Window title
window:setCaption("RAM Display")
return window
end
local function start(options)
local gameModuleName =
options.gameModuleName or error("Must provide a gameModuleName.")
local layoutName =
options.layoutName or error("Must provide a layoutName.")
package.loaded[gameModuleName] = nil
local GameClass = require(gameModuleName)
local game = classInstantiate(GameClass, options)
local window = createWindow(options)
-- Modules where we'll look for layout definitions.
local layoutModuleNames = {
-- Layouts that aren't game specific
'generic_layouts',
-- User-defined layouts (not under version control)
'custom_layouts',
}
-- Game-specific layout modules
for _, name in pairs(game.layoutModuleNames) do
table.insert(layoutModuleNames, name)
end
-- Get the requested layout.
local layout = nil
for _, layoutModuleName in pairs(layoutModuleNames) do
-- Due to the way we're checking the existence of layout modules, we must
-- first ensure the module is not considered loaded OR preloaded.
package.preload[layoutModuleName] = nil
package.loaded[layoutModuleName] = nil
-- Check that the layout module exists. In particular we want to tolerate
-- non-existence of the custom module.
if utils.isModuleAvailable(layoutModuleName) then
local layoutModule = require(layoutModuleName)
for name, layoutCandidate in pairs(layoutModule.layouts) do
if name == layoutName then
layout = layoutCandidate
break
end
end
end
end
if layout == nil then
error("Couldn't find layout named: " .. layoutName)
end
local layoutOptions = options.layoutOptions or {}
layout.window = window
layout.game = game
layout:init(unpack(layoutOptions))
game:startUpdating(layout)
end
return {
start = start,
}
|
return {'zwitser','zwitserland','zwitsers','zwitserse','zwichten','zwichtstelling','zwiep','zwiepen','zwieper','zwieping','zwiepplank','zwier','zwierbol','zwierbollen','zwieren','zwierf','zwierig','zwierigheid','zwierven','zwijgen','zwijger','zwijggeld','zwijgplicht','zwijgrecht','zwijgzaam','zwijgzaamheid','zwijmel','zwijmelbeker','zwijmeldronken','zwijmelen','zwijmeling','zwijmelroes','zwijmen','zwijn','zwijnachtig','zwijnen','zwijnenaard','zwijnenboel','zwijnenhoeder','zwijnenjacht','zwijnenkeet','zwijnenkost','zwijnenkot','zwijnenpan','zwijnenstal','zwijnenvlees','zwijnerij','zwijnjak','zwijnshoofd','zwijnskop','zwijntje','zwijntjesjager','zwik','zwikboor','zwikhout','zwikken','zwilk','zwilwrat','zwin','zwing','zwingelaar','zwingelen','zwingelmolen','zwingelspaan','zwirrelen','zwijgverbod','zwingliaan','zwijnenpopulatie','zwijnaarde','zwijndrecht','zwijndrechtenaar','zwijndrechts','zwinkels','zwier','zwirs','zwiggelaar','zwijsen','zwikker','zwijger','zwicht','zwichtlijnen','zwichtte','zwichtten','zwiepingen','zwiept','zwiepte','zwiepten','zwierde','zwierden','zwierige','zwieriger','zwierigere','zwierigst','zwierigste','zwiert','zwijg','zwijgend','zwijgende','zwijgers','zwijgt','zwijgzaamst','zwijgzame','zwijgzamer','zwijm','zwijmde','zwijmden','zwijmelde','zwijmelden','zwijmelingen','zwijmelt','zwijmt','zwijnachtige','zwijnde','zwijnden','zwijnenhoeders','zwijnenstallen','zwijnerijen','zwijnskoppen','zwijnt','zwijntjes','zwijntjesjagers','zwikje','zwikt','zwikte','zwikten','zwilwratten','zwingel','zwingelaars','zwingelde','zwingelmolens','zwingelt','zwingen','zwinnen','zwirrelde','zwirrelden','zwiepend','zwiepende','zwiepers','zwierend','zwijmelende','zwijnjakken','zwijnshoofden','zwikboren','zwikhouten','zwinglianen','zwirrelt','zwirrel','zwiers','zwijndrechtse'}
|
--[[
KeyPool provides a pool of objects suitable for use as map keys.
Create a new KeyPool, then call pool:get() to get a new key. Once you're done with it, call key:release().
Example:
local pool = KeyPool.new("foo")
...
local key1 = pool:get()
local key2 = pool:get()
map[key1] = thing1
map[key2] = thing2
...
map[key1] = nil
key1:release()
key1 = nil
]]
local Root = script:FindFirstAncestor("infinite-scroller").Parent
local t = require(Root.t)
-- Forward declarations
local KeyPool = {}
KeyPool.__index = KeyPool
local Key = {}
Key.__index = Key
-- This is Key.new, but we don't want to expose that publicly.
local function newkey(pool, index)
local key = {
pool = pool,
index = index,
}
setmetatable(key, Key)
return key
end
-- KeyPool functions
function KeyPool.new(class)
assert(t.string(class))
local pool = {
class = class,
available = {},
limit = 0,
count = 0,
}
setmetatable(pool, KeyPool)
return pool
end
-- Get a currently unused key, or create a new one if everything is in use.
function KeyPool:get()
if self.count == 0 then
self.limit = self.limit + 1
return newkey(self, self.limit)
end
local key = self.available[self.count]
self.count = self.count - 1
return key
end
-- Key functions
function Key:__tostring()
return self.pool.class .. "_" .. tostring(self.index)
end
-- Return this key to the pool it came from. Whatever previously held this key should not keep the reference after
-- calling this.
function Key:release()
self.pool.count = self.pool.count + 1
self.pool.available[self.pool.count] = self
end
return KeyPool
|
--X・HERO ワンダー・ドライバー
--Xtra HERO Wonder Driver
--Scripted by Eerie Code
function c1948618.initial_effect(c)
--c:EnableReviveLimit()
--aux.AddLinkProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x8),2,2)
--set
--local e1=Effect.CreateEffect(c)
--e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
--e1:SetDescription(aux.Stringid(1948619,0))
--e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
--e1:SetCode(EVENT_SUMMON_SUCCESS)
--e1:SetCountLimit(1,1948619)
--e1:SetRange(LOCATION_MZONE)
--e1:SetCondition(c1948618.setcon)
--e1:SetTarget(c1948618.settg)
--e1:SetOperation(c1948618.setop)
--c:RegisterEffect(e1)
--active fusion
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetRange(LOCATION_GRAVE)
e1:SetCountLimit(1,1948619)
e1:SetCost(c1948618.spcost)
e1:SetCondition(c1948618.setcon)
e1:SetTarget(c1948618.tg)
e1:SetOperation(c1948618.op)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCountLimit(1,1948618)
c:RegisterEffect(e2)
local e02=e1:Clone()
e02:SetCountLimit(1,1948618)
e02:SetCode(EVENT_BECOME_TARGET)
c:RegisterEffect(e02)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e3:SetCountLimit(1)
e3:SetCondition(c1948618.spcon)
e3:SetTarget(c1948618.sptg)
e3:SetOperation(c1948618.spop)
c:RegisterEffect(e3)
end
function c1948618.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToDeckAsCost() end
Duel.SendtoDeck(e:GetHandler(),nil,2,REASON_COST)
end
function c1948618.setcfilter(c,tp,lg)
return c:IsFaceup() and c:IsControler(tp) and c:IsSetCard(0x8)
end
function c1948618.setcon(e,tp,eg,ep,ev,re,r,rp)
local lg=e:GetHandler()
return eg:IsExists(c1948618.setcfilter,1,nil,tp,lg)
end
function c1948618.setfilter(c)
return ((c:IsType(TYPE_SPELL) and c:IsSetCard(0x46)) or (c:IsType(TYPE_QUICKPLAY) and c:IsSetCard(0xa5))) and c:IsSSetable()
end
function c1948618.settg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c1948618.setfilter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectTarget(tp,c1948618.setfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,g,1,0,0)
end
function c1948618.setop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsSSetable() then
Duel.SSet(tp,tc)
Duel.ConfirmCards(1-tp,tc)
end
end
function c1948618.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_BATTLE)
or (rp==1-tp and c:IsReason(REASON_DESTROY) and c:GetPreviousControler()==tp)
end
function c1948618.spfilter(c,e,tp)
return c:IsSetCard(0x8) and c:IsCanBeSpecialSummoned(e,0,tp,true,true) and not c:IsCode(1948618)
end
function c1948618.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c1948618.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c1948618.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c1948618.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,true,true,POS_FACEUP)
end
end
function c1948618.filter1(c,e,tp,eg,ep,ev,re,r,rp)
return c:CheckActivateEffect(false,true,false)~=nil and (((c:IsType(TYPE_SPELL) and c:IsSetCard(0x46))) or (c:IsCode(24094653) or c:IsCode(45906428) or c:IsCode(12071500)or c:IsCode(94820406) or c:IsCode(35255456) or c:IsCode(54283059)) and (c:IsCode(24094653) or c:IsCode(45906428) or c:IsCode(12071500) or c:IsCode(94820406) or c:IsCode(35255456) or c:IsCode(54283059)) or (c:IsSetCard(0xa5) and c:IsType(TYPE_QUICKPLAY)) and (c:IsCode(48130397) or c:IsCode(911000814) or c:IsCode(170000117)) and (c:IsCode(100000470) or c:IsCode(100405101))) and not (c:IsCode(77565204))
end
function c1948618.tg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chk==0 then return Duel.IsExistingMatchingCard(c1948618.filter1,tp,LOCATION_DECK,0,1,nil) end
local tc=Duel.SelectMatchingCard(tp,c1948618.filter1,tp,LOCATION_DECK,0,1,1,nil)
e:SetLabel(1)
local te,eg,ep,ev,re,r,rp=tc:GetFirst():CheckActivateEffect(false,true,true)
e:SetLabelObject(tc:GetFirst())
local tc=e:GetLabelObject()
local te,eg,ep,ev,re,r,rp=tc:CheckActivateEffect(false,true,true)
local tg=te:GetTarget()
e:SetLabelObject(te)
e:SetCategory(te:GetCategory())
e:SetProperty(te:GetProperty())
if tg then tg(e,tp,eg,ep,ev,re,r,rp,1) end
--Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
function c1948618.op(e,tp,eg,ep,ev,re,r,rp)
local te=e:GetLabelObject()
if not te then return end
local op=te:GetOperation()
if op then op(e,tp,eg,ep,ev,re,r,rp) end
e:SetLabel(0)
end
--Magical Trick Mirror
--function c1948618.initial_effect(c)
--copy Spell
--local e1=Effect.CreateEffect(c)
--e1:SetType(EFFECT_TYPE_ACTIVATE)
--e1:SetCode(EVENT_ATTACK_ANNOUNCE)
--e1:SetCondition(c1948618.condition)
--e1:SetTarget(c1948618.target)
--e1:SetOperation(c1948618.operation)
--c:RegisterEffect(e1)
--end
function c1948618.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp
end
function c1948618.filter(c,e,tp,eg,ep,ev,re,r,rp)
return c:IsType(TYPE_SPELL) and c:CheckActivateEffect(false,false,false)~=nil and not c:IsType(TYPE_FIELD)
end
function c1948618.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) or chkc:IsLocation(LOCATION_MZONE) and chkc:GetControler()~=tp and c511001112.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c1948618.filter,tp,0,LOCATION_GRAVE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c1948618.filter,tp,0,LOCATION_GRAVE,1,1,nil)
end
function c1948618.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToEffect(e) then return end
if c:IsRelateToEffect(e) and not tc:IsType(TYPE_EQUIP+TYPE_CONTINUOUS) then
local tpe=tc:GetType()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetValue(tpe)
e1:SetReset(RESET_EVENT+0x1fc0000)
c:RegisterEffect(e1)
local te=tc:GetActivateEffect()
local tg=te:GetTarget()
local op=te:GetOperation()
e:SetCategory(te:GetCategory())
e:SetProperty(te:GetProperty())
Duel.ClearTargetCard()
if tg then tg(e,tp,eg,ep,ev,re,r,rp,1) end
Duel.BreakEffect()
if op then op(e,tp,eg,ep,ev,re,r,rp) end
end
if c:IsRelateToEffect(e) and tc:IsType(TYPE_EQUIP+TYPE_CONTINUOUS) then
local tpe=tc:GetType()
local code=tc:GetOriginalCode()
c:CopyEffect(code,nil,1)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetValue(tpe)
e1:SetReset(RESET_EVENT+0x1fc0000)
c:RegisterEffect(e1)
local te=tc:GetActivateEffect()
local tg=te:GetTarget()
local op=te:GetOperation()
e:SetCategory(te:GetCategory())
e:SetProperty(te:GetProperty())
Duel.ClearTargetCard()
if tg then tg(e,tp,eg,ep,ev,re,r,rp,1) end
Duel.BreakEffect()
if op then op(e,tp,eg,ep,ev,re,r,rp) end
c:CancelToGrave()
end
end
|
object_tangible_dungeon_mustafar_valley_battlefield_turret_concussion_weapon = object_tangible_dungeon_mustafar_valley_battlefield_shared_turret_concussion_weapon:new {
}
ObjectTemplates:addTemplate(object_tangible_dungeon_mustafar_valley_battlefield_turret_concussion_weapon, "object/tangible/dungeon/mustafar/valley_battlefield/turret_concussion_weapon.iff")
|
local playsession = {
{"gespenstdermaschine", {310692}},
{"foggyliziouz", {1401137}},
{"EPO666", {202975}},
{"tykak", {50257}},
{"MovingMike", {840626}},
{"Karakut", {252453}},
{"010110", {561}},
{"raskl", {19616}},
{"MegaKillBot", {326639}},
{"Akhrem", {2525}},
{"cawsey21", {1097874}},
{"TiTaN", {390990}},
{"rlidwka", {79069}},
{"MaZeeT", {2377}},
{"beranabus", {117669}},
{"vad7ik", {924944}},
{"skace", {318}},
{"JailsonBR", {932010}},
{"dog80", {1121644}},
{"Mrho", {1697}},
{"mpovas", {404473}},
{"iceskaarj", {1076523}},
{"Wobbleflopper", {88122}},
{"strongfive", {92641}},
{"dazonker", {933724}},
{"nobleoclelot", {1193}},
{"tyce1234", {620194}},
{"Creator_Zhang", {550961}},
{"kat23", {45603}},
{"facere", {546899}},
{"fandoce", {476282}},
{"Charcuteur", {47702}},
{"Fudster", {102592}},
{"Spocks", {344447}},
{"Menander", {571873}},
{"Wiedrock", {303756}},
{"jamie1994", {199993}},
{"0000mick0000", {1984}},
{"MFH", {23474}},
{"dracoix", {2231}},
{"onyxinsanity", {2155}},
{"moocat12", {149679}},
{"Oveerlord92", {220267}},
{"C4pT_H0oK", {163355}},
{"sanilogc21", {260}},
{"DKarma", {249792}},
{"fishguts", {35828}},
{"Jamesterjim", {8696}},
{"BieneMajaR3turns", {11669}},
{"petterah", {15231}}
}
return playsession
|
require("player")
require("background")
require("entities")
function love.load()
-- Var
elapsedTime = 0
playing = false
firstTime = true
bestScore = 0
titleAlpha = 1
scaleParams = { scale = 1, translate = {x=0, y=0} }
pause = false
lifeSprite = love.graphics.newImage("assets/life.png")
logo = love.graphics.newImage("assets/logo.png")
logo:setFilter("nearest", "nearest")
bgm = love.audio.newSource("assets/bgm.mp3", "stream")
bgm:setLooping(true)
bgm:play()
bgm:setVolume(0.4)
-- Win Config
window = love.graphics.newCanvas(1200, 600)
checksize( love.graphics.getWidth(), love.graphics.getHeight() )
love.graphics.setNewFont("assets/PatrickHandSC-Regular.ttf", 40)
-- Load save
if love.filesystem.getInfo("savedata.txt") then
local file = love.filesystem.read("savedata.txt")
local save = tonumber(file)
if type(save)=="number" then
bestScore = save
end
end
-- Core init
background.load()
entities.load()
player.load()
end
function love.draw()
love.graphics.setCanvas(window)
love.graphics.clear()
background.draw()
entities.draw()
player.draw()
if pause then
love.graphics.printf({{0.6,0,0},"Paused\n(Press P to continue)"}, -600, 250, 1200, "center", 0, 2, 2)
end
if playing then
for i=1,player.life do
love.graphics.draw(lifeSprite, -15 + 30 * i, 15)
end
love.graphics.printf({{1,1,1,titleAlpha},"Score : "..math.ceil(background_elems.elaspedDistance * 0.003)}, 0, 0, 1200, "center")
else
love.graphics.setColor(255, 255, 255, titleAlpha)
love.graphics.printf("Best Score : "..bestScore, 0, 0, 1200, "center")
love.graphics.printf("Jump to start !", 0, 40, 1200, "center")
love.graphics.draw(logo, 1200*0.5, 100, 0.2 * math.sin(elapsedTime), 1.5, 1.5, 300*0.5, 0)
love.graphics.setColor(255, 255, 255, 1)
end
love.graphics.setCanvas()
love.graphics.draw(window, scaleParams.translate.x, scaleParams.translate.y, 0, scaleParams.scale, scaleParams.scale)
end
function love.update(dt)
if pause then
return 0
end
elapsedTime = elapsedTime + dt
if love.keyboard.isDown("space") or love.mouse.isDown(1) then
if not playing then
resetGame()
end
player.jump(firstTime)
end
background.update(dt)
entities.update(dt)
player.update(dt)
end
function love.keyreleased(key)
if key == "escape" then
love.event.quit()
elseif key == "p" then
pause = not pause
end
end
function love.resize(w,h)
checksize(w,h)
end
-------------------- No-Love Events
function resetGame()
playing = true
elapsedTime = 0
player.reset()
entities.reset()
background.reset()
end
function onGameOver(dt)
if playing then
if background_elems.elaspedDistance * 0.003 > bestScore then
bestScore = math.ceil(background_elems.elaspedDistance * 0.003)
love.filesystem.write("savedata.txt", bestScore)
end
playing = false
firstTime = false
end
if titleAlpha<1 then
titleAlpha = titleAlpha + dt
if titleAlpha>1 then
titleAlpha = 1
end
end
end
function checksize(w,h)
if w~=1200 and h~=600 then
local s = math.min(w/1200,h/600)
local sw = s * 1200
local sh = s * 600
scaleParams.translate.x = w/2 - sw/2
scaleParams.translate.y = h/2 - sh/2
scaleParams.scale = s
end
end
|
--Resource Extractor/Coin Currency GUI Handler by DevSenju
--[[
HOW TO ADD NEW RESORUCES' GUI ON THE SCREEN AND ON THE PLAYER'S HEAD
1) Add the model of the currency to ReplicatedStorage.Assets. Make sure the model contains a Billboard GUI with an ImageLabel
and is tagged with ONLY 1 CollectionService tag containing the name of the currency type. I recommend using the Instance Tagging plugin
by Sweetheartichoke for this.
2) Copy and Paste a currency counter UI in StarterGui and rename it currencyName.."Counter" (e.g. SteelCounter).
Be sure to replace any object names inside the new UI containing the previous currency's name with the new currency's name.
(e.g. SteelPickupObjects, SteelCoinAmount, SteelCoinLabel)
3) Add an entry UI_HOLDER, PICKUP_OBJECTS_FOLDERS, TWEEN_REFS, FINAL_UI_HEIGHT, and TRACKERS. Here are the entry templates.
UI_HOLDER - [currencyName.."UI"] = Player.PlayerGui.currencyNameCounter.Background;
PICKUP_OBJECTS_FOLDERS - [currencyName.."UI"] = Player.PlayerGui.currencyNameCounter.Background.currencyNamePickupObjects;
TWEEN_REFS -
[currencyName.."UI"] = {
["moneytweenref"] = {UI_HOLDER[currencyName.."UI"].currencyNameAmount.Total.TweenRef,UI_HOLDER[currencyName.."UI"].currencyAmount," anything"};
["moneycolor"] = {UI_HOLDER[currencyName.."UI"].currencyNameAmount.MoneyColor,UI_HOLDER[currencyName.."UI"].currencyAmount};
["refToTween"] = nil;
};
FINAL_UI_HEIGHT - ["currencyName"] = Vector3.new(X,Y,Z);
TRACKERS - ["currencyName"] = {}
Watch out for warnings in the output!
]]
if script:GetAttribute("DebugMode") == true then debugmode = true else debugmode = false end
--Player Variables
local Player = game:GetService("Players").LocalPlayer
--Services
local TweenService = game:GetService("TweenService")
local CollectionService = game:GetService("CollectionService")
--GUI Variables
local UI_HOLDER = {
["CoinUI"] = Player.PlayerGui.CoinCounter.Background;
["GemUI"] = Player.PlayerGui.GemCounter.Background;
-- ["ExampleUI"] = Player.PlayerGui.ExampleCounter.Background;
}
local PICKUP_OBJECTS_FOLDERS = {
["CoinUI"] = Player.PlayerGui.CoinCounter.Background.CoinPickupObjects;
["GemUI"] = Player.PlayerGui.GemCounter.Background.GemPickupObjects;
-- ["ExampleUI"] = Player.PlayerGui.ExampleCounter.Background.ExamplePickupObjects;
}
local TWEEN_REFS = {
["CoinUI"] = {
["moneytweenref"] = {UI_HOLDER["CoinUI"].CoinAmount.Total.TweenRef,UI_HOLDER["CoinUI"].CoinAmount," ??"};
["moneycolor"] = {UI_HOLDER["CoinUI"].CoinAmount.MoneyColor,UI_HOLDER["CoinUI"].CoinAmount};
["refToTween"] = nil;
};
["GemUI"] = {
["moneytweenref"] = {UI_HOLDER["GemUI"].GemAmount.Total.TweenRef,UI_HOLDER["GemUI"].GemAmount," ??"};
["moneycolor"] = {UI_HOLDER["GemUI"].GemAmount.MoneyColor,UI_HOLDER["GemUI"].GemAmount};
["refToTween"] = nil;
};
--[[
["ExampleUI"] = {
["moneytweenref"] = {UI_HOLDER["ExampleUI"].ExampleAmount.Total.TweenRef,UI_HOLDER["ExampleUI"].ExampleAmount," ??"};
["moneycolor"] = {UI_HOLDER["ExampleUI"].ExampleAmount.MoneyColor,UI_HOLDER["ExampleUI"].ExampleAmount};
["refToTween"] = nil;
};
--]]
}
--Other Variables
local GAINED_CURRENCY_COLOR = Color3.fromRGB(44, 255, 86)
local LOST_CURRENCY_COLOR = Color3.fromRGB(255, 65, 68)
local INTIAL_UI_HEIGHT = Vector3.new(0,1.2,0)
local FINAL_UI_HEIGHT = {
["Coin"] = Vector3.new(0,3,0);
["Gem"] = Vector3.new(0,5,0);
-- ["Example"] = Vector3.new(0,6,0);
}
local TRACKERS = {
["Coin"] = {};
["Gem"] = {};
-- ["Example"] = {};
}
--Other variables
local RNG = Random.new()
--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
--Be careful editing beyond this point
--!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
--Update UI functions
--[[
Connects a Changed event to the currency text. When a given TweenRef is changed, the text on currency GUI will update to its value.
Connects a Changed event to currency color. When MoneyColor is changed, the color on currency GUI will update to its value.
For currency text tweening, there is an extra argument included in the TWEEN_REFS dictionary which describes what to concat
to the end of the currency amount.
]]
for x,y in pairs(TWEEN_REFS) do
for i,v in pairs(y) do
if type(v) == "table" then
v[1].Changed:Connect(function(moving)
if typeof(moving) == "number" then --currency value then
v[2].Text = moving..v[3]
elseif typeof(moving) == "Color3" then
v[2].TextColor3 = moving
end
end)
end
end
end
--[[
startTimeout(UI,saved)
Args:
UI: holder GUI (total currency pickup)
saved: int (time of pickup)
Functionality:
startTimeout beings a countdown from the given time. Once time is up, the function will check if the current timeout
on that iteration of the function is still valid. If so, it destroys the current total pickup counter.
]]
function startTimeout(UI,saved,tag)
task.delay(3,function()
if TRACKERS[tag] == saved then
if debugmode == true then print("ShowCurrencyChangePlayer UI timeout") end
UI.Name = "ToBeRemoved"
local transparencyTweenInfo = TweenInfo.new(0.3,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local transparencyTween = TweenService:Create(UI.PickupAmount,transparencyTweenInfo,{TextTransparency = 1,TextStrokeTransparency = 1})
transparencyTween:Play()
transparencyTween.Completed:Wait()
UI:Destroy()
else
if debugmode == true then print("ShowCurrencyChangePlayer UI refresh") end
end
end)
end
--[[
playCurrencyTween(UI,studsoffset,transparencyTweenInfo,positionTweenInfo)
Args:
UI: holder GUI (total currency pickup)
studsoffset: Vector3 (the final location of the UI before timing out)
transparencyTweenInfo: TweenInfo (UI transparency tween's properties)
positionTweenInfo: TweenInfo (UI position tween's properties)
isCheck: bool (is the current UI object new or did it exist already?)
Functionality:
playCurrencyTween creates and plays the tweens on the total currency pickup that change its position and
text trasparency. If the timer was already running (isCheck == true), reset the UI position to singal the
timer resetting. It returns the time the tweens were run at.
]]
function playTotalCurrencyTween(UI,studsoffset,transparencyTweenInfo,positionTweenInfo,isCheck)
local transparencyTween = TweenService:Create(UI.PickupAmount,transparencyTweenInfo,{TextTransparency = 0,TextStrokeTransparency = 0})
local positionTween = TweenService:Create(UI,positionTweenInfo,{StudsOffset = studsoffset})
if isCheck == true then
UI.StudsOffset = INTIAL_UI_HEIGHT
end
transparencyTween:Play()
positionTween:Play()
local saved = tick()
return saved
end
--[[
ShowCurrencyChangePlayer(tag,diff)
Args:
tag: string (name of object type)
diff: int (amount to display)
Functionality:
ShowCurrencyChangePlayer will create a Billboard GUI on the Player's Head that shows the total pickup amount of a currency set on a timer.
Once the timer runs out, the UI will fade away. The timer can be reset by picking up another instance of the same currency type.
The only 2 supported currencies right now are Gems and Coins. The else statement will run for any outside currencies
added.
]]
function ShowCurrencyChangePlayer(tag,diff)
local transparencyTweenInfo = TweenInfo.new(1,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local positionTweenInfo = TweenInfo.new(2,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local check = Player.Character.Head:FindFirstChild("ShowTotal"..tag.."Pickup")
if check == nil then
if debugmode == true then print("Start ShowCurrencyChangePlayer") end
local findtemplate = game.ReplicatedStorage.Assets.UI:FindFirstChild("ShowTotal"..tag.."Pickup")
if findtemplate then
local template = findtemplate:Clone()
if diff > 0 then
template.PickupAmount.Text = "+"..diff
else
template.PickupAmount.TextColor3 = LOST_CURRENCY_COLOR
template.PickupAmount.Text = diff
end
template.Parent = Player.Character.Head
template.Adornee = Player.Character.Head
local saved = playTotalCurrencyTween(template,FINAL_UI_HEIGHT[tag],transparencyTweenInfo,positionTweenInfo,false)
TRACKERS[tag] = saved
startTimeout(template,saved,tag)
else
warn("CurrencyCounterHandler could not find ShowTotal"..tag.."Pickup UI. Is it in the ReplicatedStorage.Assets.UI?")
return
end
else
local spliced = string.gsub(check.PickupAmount.Text, "%D", "")
check.PickupAmount.Text = "+"..(diff + spliced)
local saved = playTotalCurrencyTween(check,FINAL_UI_HEIGHT[tag],transparencyTweenInfo,positionTweenInfo,true)
TRACKERS[tag] = saved
startTimeout(check,saved,tag)
end
end
--[[
ShowCurrencyChangeUI(tag,diff)
Args:
tag: string (name of object type)
diff: int (amount to display)
Functionality:
ShowCurrencyChangeUI will create a TextLabel GUI on the correspoding curreny GUI that shows the pickup amount of single piece of currency.
The only 2 supported currencies right now are Gems and Coins. The else statement will run for any outside currencies
added.
]]
function ShowCurrencyChangeUI(tag, diff)
local template = game.ReplicatedStorage.Assets.UI.CoinNotification:Clone()
if UI_HOLDER[tag] == nil then
warn("ShowCurrencyChangeUI did not find "..tag.."'s UI. Is it in the UI_HOLDER table and StarterGui?")
template:Destroy()
return
end
template.Parent = PICKUP_OBJECTS_FOLDERS[tag]
if diff > 0 then
if debugmode == true then print("Start ShowCurrencyChangeUI +") end
template.Text = "+"..diff
local choices = {Enum.TextXAlignment.Left,Enum.TextXAlignment.Right,Enum.TextXAlignment.Center}
local randomXAlignment = RNG:NextInteger(1,3)
template.TextXAlignment = choices[randomXAlignment]
local transparencyTweenInfo = TweenInfo.new(0.3,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,true)
local positionTweenInfo = TweenInfo.new(0.5,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local transparencyTween = TweenService:Create(template,transparencyTweenInfo,{TextTransparency = 0,TextStrokeTransparency = 0})
local positionTween = TweenService:Create(template,positionTweenInfo,{Position = UDim2.new(0.416,0,-2,0)})
transparencyTween:Play()
positionTween:Play()
task.wait(1)
template:Destroy()
elseif diff < 0 then
if debugmode == true then print("Start ShowCurrencyChangeUI -") end
template.Text = diff
template.TextColor3 = Color3.fromRGB(255, 65, 68)
local choices = {Enum.TextXAlignment.Left,Enum.TextXAlignment.Right,Enum.TextXAlignment.Center}
local randomXAlignment = RNG:NextInteger(1,3)
template.TextXAlignment = choices[randomXAlignment]
local transparencyTweenInfo = TweenInfo.new(0.3,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,true)
local positionTweenInfo = TweenInfo.new(0.5,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local transparencyTween = TweenService:Create(template,transparencyTweenInfo,{TextTransparency = 0,TextStrokeTransparency = 0})
local positionTween = TweenService:Create(template,positionTweenInfo,{Position = UDim2.new(0.416,0,2,0)})
transparencyTween:Play()
positionTween:Play()
task.wait(1)
template:Destroy()
end
end
--[[
For loop that connects Changed events to each UI's Total IntValue. When changed, it will tween the total amount of coins up or down depending on
the new value's relation to the current value.
]]
for i,v in pairs(UI_HOLDER) do
local total = v:FindFirstChild("Total",true)
if total then
total.Changed:Connect(function(val)
if debugmode == true then print("Start Coin Amount Tween") end
local show
local colortween = TweenInfo.new(1,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local moneytween = TweenInfo.new(1,Enum.EasingStyle.Quad,Enum.EasingDirection.Out,0,false)
local ryotween = TweenService:Create(TWEEN_REFS[i]["moneytweenref"][1], moneytween, {Value = val})
local mycolor
local backcolor
local spliced = string.gsub(TWEEN_REFS[i]["moneytweenref"][2].Text, "%D", "")
if val > tonumber(spliced) then
mycolor = TweenService:Create(TWEEN_REFS[i]["moneycolor"][1],colortween,{Value = Color3.fromRGB(44, 255, 86)})
backcolor = TweenService:Create(TWEEN_REFS[i]["moneycolor"][1],colortween,{Value = Color3.fromRGB(255, 255, 255)})
elseif val < tonumber(spliced) then
mycolor = TweenService:Create(TWEEN_REFS[i]["moneycolor"][1],colortween,{Value = Color3.fromRGB(255, 48, 48)})
backcolor = TweenService:Create(TWEEN_REFS[i]["moneycolor"][1],colortween,{Value = Color3.fromRGB(255, 255, 255)})
end
print(TWEEN_REFS[i]["refToTween"])
if TWEEN_REFS[i]["refToTween"] and TWEEN_REFS[i]["refToTween"].PlaybackState == Enum.PlaybackState.Playing then
if debugmode == true then print("Coin Amount Previous Tween detected, pause it") end
TWEEN_REFS[i]["refToTween"]:Pause()
end
TWEEN_REFS[i]["refToTween"] = mycolor
mycolor:Play()
ryotween:Play()
ryotween.Completed:Wait()
--print(refToTween.PlaybackState, mycolor.PlaybackState)
if mycolor and (mycolor.PlaybackState == Enum.PlaybackState.Paused or mycolor.PlaybackState == Enum.PlaybackState.Cancelled ) then
if debugmode == true then print("Coin Amount mycolor pause detected, end event") end
else
TWEEN_REFS[i]["refToTween"] = nil
backcolor:Play()
end
end)
else
warn("Unable to find Total IntValue inside of "..v.Parent.Name".")
return
end
end
--[[
Bindable Event connection that updates the UIs on the Player and Player GUI whenever it is fired (a currency is collected)
]]
game.ReplicatedStorage.Events.IncrementCurrencyAmount.Event:Connect(function(obj,val)
local onlytag = CollectionService:GetTags(obj)[1]
if #CollectionService:GetTags(obj) > 2 then
warn("Currency objects should only be tagged with the name of the currency. If you want more, edit this Connection.")
return
end
TWEEN_REFS[onlytag.."UI"]["moneytweenref"][2].Total.Value += val
ShowCurrencyChangePlayer(onlytag,val)
ShowCurrencyChangeUI(onlytag.."UI",val)
end)
|
local class = require 'middleclass'
local TException = require 'thrift.TException'
local TProtocolExceptionType = require 'thrift.protocol.TProtocolExceptionType'
local TProtocolException = class('TProtocolException', TException)
function TProtocolException:initialize(message, code)
TException.initialize(self, message)
self.errorCode = code or 0
end
function TProtocolException:__errorCodeToString()
if self.errorCode == TProtocolExceptionType.INVALID_DATA then
return 'Invalid data'
elseif self.errorCode == TProtocolExceptionType.NEGATIVE_SIZE then
return 'Negative size'
elseif self.errorCode == TProtocolExceptionType.SIZE_LIMIT then
return 'Size limit'
elseif self.errorCode == TProtocolExceptionType.BAD_VERSION then
return 'Bad version'
elseif self.errorCode == TProtocolExceptionType.INVALID_PROTOCOL then
return 'Invalid protocol'
elseif self.errorCode == TProtocolExceptionType.DEPTH_LIMIT then
return 'Exceeded size limit'
else
return 'Default (unknown)'
end
end
return TProtocolException
|
local help = require("mod.helpers")
local pauseState = {}
function pauseState:enter(from)
self.from = from
love.graphics.clear()
end
function pauseState:draw()
local str = "PAUSE"
local font = love.graphics.getFont()
local text = love.graphics.newText(font, str)
local w, h = love.graphics.getDimensions()
local x = w / 2 - font:getWidth(str) / 2
local y = h / 2 - font:getHeight() / 2
love.graphics.setColor(help.rgba(0, 0, 0))
love.graphics.rectangle("fill", 0, 0, w, h)
love.graphics.setColor(help.rgba(255, 255, 255))
love.graphics.draw(text, x, y)
end
function pauseState:keyreleased(key)
if key == 'return' then
Gamestate.switch(self.from)
end
end
return pauseState
|
--SFX Editor
local sfxobj = require("Libraries.sfx") --The sfx object
local eapi = select(1,...) --The editors api
local sw, sh = screenSize() --The screensize
local volColors = {1,2,13,6,12,14,15,7}
local se = {} --sfx editor
local sfxSlots = 64 --The amount of sfx slots
local sfxNotes = 32 --The number of notes in each sfx
local defaultSpeed = 0.25 --The default speed
local speed = defaultSpeed --The current sfx speed
local selectedSlot = 0
local selectedWave = 0
local playingNote = -1
local pitchGrid = {0,9, sfxNotes*4,12*7, sfxNotes,12*7}
local volumeGrid = {0,sh-8-8*2-1, sfxNotes*4,8*2, sfxNotes,8}
--The SFXes datas.
local sfxdata = {}
for i=0,sfxSlots-1 do
local sfx = sfxobj(sfxNotes, defaultSpeed)
for i=0,sfxNotes-1 do
sfx:setNote(i,1,1,0,0) --Octave 0 is hidden...
end
sfxdata[i] = sfx
end
local patternImage = imagedata("LK12;GPUIMG;2x6;770007700077;")
local pattern2Image = imagedata("LK12;GPUIMG;4x2;00070070;")
local selection = {0,31}
local history_size = 32
local history_index = 1
local history = {}
local touched_graphs = false
local function drawGraph()
local x,y = pitchGrid[1], pitchGrid[2]-1
local x2,y2 = volumeGrid[1], volumeGrid[2]
local sfx = sfxdata[selectedSlot]
--Pitch Rectangle
rect(x,y,pitchGrid[3]+1,pitchGrid[4]+4,false,0)
--Octave Lines
local spacing = 12
for i=1,7 do
line(x-1,y + i*spacing+1,x + pitchGrid[3]+1,y + i*spacing+1, 1)
end
--Volume Rectangle
rect(x2,y2-1,volumeGrid[3]+1,volumeGrid[4]+2,false,0)
--Horizontal Box (Style)
rect(x,y+pitchGrid[4]+4, pitchGrid[3]+1+1, y2-1-y-pitchGrid[4]-4, false, 9)
patternFill(patternImage)
rect(x,y+pitchGrid[4]+4, pitchGrid[3]+1+1, y2-1-y-pitchGrid[4]-4, false, 4)
patternFill()
--Vertical Line (Style)
rect(x+pitchGrid[3]+1,8, 4,sh-16, false, 9)
patternFill(pattern2Image)
rect(x+pitchGrid[3]+1,8, 4,sh-16, false, 4)
patternFill()
local playingNote = math.floor(playingNote)
-- Selection line
if(selection[1] ~= 0 or selection[2] ~= 31)then
rect(x+selection[1]*4+1,93,selection[2]*4 - selection[1]*4 + 2,3,false,2)
end
--Notes lines
for i=0, sfxNotes-1 do
local note,oct,wave,amp = sfx:getNote(i); note = note-1
if wave >= 0 and amp > 0 then
local line_col = 1
if((i >= selection[1] and i <= selection[2]) and not (selection[1] == 0 and selection[2] == 31))then line_col = 2 end
rect(x+1+i*4, y+12*8-(note+oct*12), 2, note+oct*12-9, false, (playingNote == i and 6 or line_col))
rect(x+1+i*4, y+12*8-(note+oct*12), 2, 2, false, 8+wave)
end
local vol = math.floor(amp*7)
if wave < 0 then vol = 0 end
rect(x2+1+i*4, y2+(7-vol)*2, 3,2, false, volColors[vol+1])
end
end
local slotLeft, slotLeftDown = {sw-26,15,4,7}, false
local slotRight, slotRightDown = {sw-9,15,4,7}, false
function se:drawSlot()
color(12)
print("SLOT:",sw-53,16)
if slotLeftDown then pal(9,4) end
_SystemSheet:draw(164,slotLeft[1],slotLeft[2])
pal()
color(13)
rect(sw-21,15,fontWidth()*2+3,fontHeight()+1, false, 6)
print(selectedSlot, sw-20,16, fontWidth()*2+2, "right")
if slotRightDown then pal(9,4) end
_SystemSheet:draw(165,slotRight[1],slotRight[2])
pal()
end
local speedLeft, speedLeftDown = {sw-25,27,4,7}, false
local speedRight, speedRightDown = {sw-8,27,4,7}, false
function se:drawSpeed()
color(7)
print("SPEED:",sw-55,28)
if speedLeftDown then pal(9,4) end
_SystemSheet:draw(164,speedLeft[1],speedLeft[2])
pal()
color(13)
rect(sw-20,27,fontWidth()*2+3,fontHeight()+1, false, 6)
print(speed/0.25, sw-19,28, fontWidth()*2+2, "right")
if speedRightDown then pal(9,4) end
_SystemSheet:draw(165,speedRight[1],speedRight[2])
pal()
end
local playRect, playDown = {sw-8,sh-8,8,8}, false
function se:drawPlay()
if playingNote >= 0 then
_SystemSheet:draw(playDown and 41 or 17,playRect[1],playRect[2])
else
_SystemSheet:draw(playDown and 40 or 16,playRect[1],playRect[2])
end
end
local waveGrid,waveHover,waveDown = {sw-56,40,9*6,7,6,1}, false, false
function se:drawWave()
rect(waveGrid[1],waveGrid[2],waveGrid[3],waveGrid[4], false, 5)
for i=0,5 do
local colorize = (waveHover and waveHover == i+1) or (selectedWave == i)
local down = (waveDown and waveHover and waveHover == i+1) or (selectedWave == i)
if colorize then pal(6,8+i) end
if down then palt(13,true) end
_SystemSheet:draw(173+i,down and waveGrid[1]+i*9+1 or waveGrid[1]+i*9,down and waveGrid[2]+1 or waveGrid[2])
pal() palt()
end
end
local SelectButtons = {
["x_origin"] = sw-55,
["y_origin"] = 52,
["sel_x_orig"] = sw-56,
["sel_y_orig"] = 60,
["sel_R_offset"] = 17,
["selB_offset"] = 33,
["sel_clear_offset"] = 23,
["selA_L_down"] = false,
["selA_R_down"] = false,
["sel_clr_down"] = false,
["selB_L_down"] = false,
["selB_R_down"] = false,
}
function se:drawSelect()
local sb = SelectButtons
local ix,iy = sb.x_origin,sb.y_origin
local sx,sy = sb.sel_x_orig,sb.sel_y_orig
color(7)
print("Selection:",ix + 2,iy)
--Selection Start Controls
if sb.selA_L_down then pal(9,4) end
_SystemSheet:draw(164,sx,sy)
pal()
color(13)
rect(sx + 5,sy,fontWidth()*2+3,fontHeight()+1, false, 6)
print(selection[1] + 1, sx+6, sy+1, fontWidth()*2+2, "right")
if sb.selA_R_down then pal(9,4) end
_SystemSheet:draw(165,sx + sb.sel_R_offset,sy)
pal()
-- Selection Clear Control
local back_col = 9
if(sb.sel_clr_down)then pal(7,13) back_col = 4 end
rect(sx + sb.sel_clear_offset+1, sy+1, 6, 6, false, back_col)
_SystemSheet:draw(120, sx + sb.sel_clear_offset, sy)
pal()
--Selection End Controls
local sx = sx + sb.selB_offset
if sb.selB_L_down then pal(9,4) end
_SystemSheet:draw(164,sx,sy)
pal()
color(13)
rect(sx + 5,sy,fontWidth()*2+3,fontHeight()+1, false, 6)
print(selection[2] + 1, sx+6, sy+1, fontWidth()*2+2, "right")
if sb.selB_R_down then pal(9,4) end
_SystemSheet:draw(165,sx + 17,sy)
pal()
end
local ToolButtons = {
["x_origin"] = sw-56,
["y_origin"] = 71,
["tools_offset"] = 6,
["tools_spacing"] = 11,
["tool_down"] = -1,
["waves_offset"] = 30,
["wave_down"] = -1,
["copy_buffer"] = nil,
}
function se:drawTools()
local tb = ToolButtons
color(7)
print("Tools",tb.x_origin + 14,tb.y_origin)
local box_col = 6
for i=0,4 do
for j=0,1 do
local x_off = tb.x_origin + i * tb.tools_spacing
local y_off = tb.y_origin + tb.tools_offset + j * tb.tools_spacing + 1
if(tb.tool_down == i+j*5)then box_col = 1 end
rect(x_off + 1, y_off + 1,9,9, false, 13)
rect(x_off, y_off,9,9, false, box_col)
box_col = 6
end
end
pal(7,13)
local ix,iy = tb.x_origin + 1, tb.y_origin + tb.tools_offset + 2
_SystemSheet:draw(179, ix, iy)
_SystemSheet:draw(180, ix + tb.tools_spacing, iy)
--spr_clear:image():draw(ix + 22, iy)
_SystemSheet:draw(82, ix + 21, iy -1)
_SystemSheet:draw(83, ix + 32, iy -1)
_SystemSheet:draw(84, ix + 44, iy -1)
--Second Row
for i=1,4 do
_SystemSheet:draw(180 + i, ix + tb.tools_spacing * (i-1), iy + tb.tools_spacing)
end
_SystemSheet:draw(184, ix + tb.tools_spacing*4 + 7, iy + tb.tools_spacing + 8, math.pi)
pal()
for i=0,5 do
if(tb.wave_down == i)then pal(6, 8+i) end
_SystemSheet:draw(173 + i, tb.x_origin + i * 9, tb.y_origin + tb.waves_offset)
pal()
end
end
function se:entered()
speed = sfxdata[selectedSlot]:getSpeed()
-- Default state
if(#history == 0)then
se:clearHistory()
se:addHistory()
end
eapi:drawUI()
drawGraph()
self:drawSlot()
self:drawSpeed()
self:drawPlay()
self:drawWave()
self:drawSelect()
self:drawTools()
end
function se:leaved()
--Stop the current playing SFX
if Audio then Audio.stop() end
playingNote = -1
end
local select_start = -1
function se:pitchMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,pitchGrid)
if cx and isMDown(1) then
local sfx = sfxdata[selectedSlot]
cx, cy = cx-1, 12*8-cy+1
local note = cy%12
local oct = math.floor(cy/12)
local _,_,_,amp = sfx:getNote(cx)
sfx:setNote(cx,note,oct,selectedWave,amp == 0 and 5/7 or amp)
drawGraph()
end
if cx and isMDown(2) then
if(state == "pressed")then
select_start = cx-1
selection[1] = select_start
selection[2] = select_start
elseif(select_start ~= -1)then
if(cx > select_start)then
selection[1] = select_start
selection[2] = math.min(cx-1,31)
else
selection[1] = cx-1
selection[2] = math.min(select_start,31)
end
end
drawGraph()
se:drawSelect()
end
if(state == "released")then select_start = -1 end
if(not touched_graphs and cx and state == "moved" and (isMDown(1) or istouch))then
touched_graphs = true
end
end
function se:volumeMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,volumeGrid)
if cx and isMDown(1) then
local sfx = sfxdata[selectedSlot]
local note, oct, wave = sfx:getNote(cx-1)
if wave < 0 and cy < 8 then wave = selectedWave end
sfx:setNote(cx-1,false,false,wave,(8-cy)/7)
drawGraph()
end
if(not touched_graphs and cx and state == "moved" and (isMDown(1) or istouch))then
touched_graphs = true
end
end
function se:slotMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,slotLeft) then
slotLeftDown = true
self:drawSlot()
end
if isInRect(x,y,slotRight) then
slotRightDown = true
self:drawSlot()
end
elseif state == "moved" then
if not isInRect(x,y,slotLeft) and slotLeftDown then
slotLeftDown = false
self:drawSlot()
end
if not isInRect(x,y,slotRight) and slotRightDown then
slotRightDown = false
self:drawSlot()
end
else
if isInRect(x,y,slotLeft) and slotLeftDown then
selectedSlot = math.max(selectedSlot-1,0)
speed = sfxdata[selectedSlot]:getSpeed()
se:clearHistory()
se:addHistory()
end
slotLeftDown = false
if isInRect(x,y,slotRight) and slotRightDown then
selectedSlot = math.min(selectedSlot+1,sfxSlots-1)
speed = sfxdata[selectedSlot]:getSpeed()
se:clearHistory()
se:addHistory()
end
slotRightDown = false
drawGraph() self:drawSlot() self:drawSpeed()
end
end
function se:speedMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,speedLeft) then
speedLeftDown = true
self:drawSpeed()
end
if isInRect(x,y,speedRight) then
speedRightDown = true
self:drawSpeed()
end
elseif state == "moved" then
if not isInRect(x,y,speedLeft) and speedLeftDown then
speedLeftDown = false
self:drawSpeed()
end
if not isInRect(x,y,speedRight) and speedRightDown then
speedRightDown = false
self:drawSpeed()
end
else
if isInRect(x,y,speedLeft) and speedLeftDown then
speed = math.max(speed-0.25,0.25)
sfxdata[selectedSlot]:setSpeed(speed)
end
speedLeftDown = false
if isInRect(x,y,speedRight) and speedRightDown then
speed = math.min(speed+0.25,99*0.25)
sfxdata[selectedSlot]:setSpeed(speed)
end
speedRightDown = false
self:drawSpeed()
end
end
function se:playMouse(state,x,y,button,istouch)
if state == "pressed" then
if isInRect(x,y,playRect) then
playDown = true
self:drawPlay()
end
elseif state == "moved" then
if not isInRect(x,y,playRect) and playDown then
playDown = false
self:drawPlay()
end
elseif state == "released" then
if isInRect(x,y,playRect) and playDown then
playDown = false
if playingNote >= 0 then
if Audio then Audio.stop() end
playingNote = -1
else
sfxdata[selectedSlot]:play(0)
playingNote = 0
end
drawGraph()
self:drawPlay()
end
end
end
function se:waveMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y,waveGrid)
if state == "pressed" then
if cx then
waveHover = cx
waveDown = true
self:drawWave()
end
elseif state == "moved" then
if (waveHover and cx and waveHover ~= cx) or not waveHover then
waveHover = cx
self:drawWave()
elseif waveHover and not cx then
waveHover = false
waveDown = false
self:drawWave()
end
elseif state == "released" then
if waveDown and cx then
selectedWave = cx-1
self:drawWave()
end
waveDown = false
end
end
function se:selectMouse(state,x,y,button,istouch)
local sb = SelectButtons
if state == "pressed" then
-- Selection A Left
if isInRect(x,y,{sb.sel_x_orig, sb.sel_y_orig, 4,7}) then
if(selection[1] ~= 0)then selection[1] = selection[1] - 1 end
sb.selA_L_down = true
self:drawSelect()
-- Selection A Right
elseif isInRect(x,y,{sb.sel_x_orig + sb.sel_R_offset, sb.sel_y_orig, 4,7}) then
if(selection[1] < 30 and selection[1] < selection[2])then selection[1] = selection[1] + 1 end
sb.selA_R_down = true
self:drawSelect()
-- Selection Clear
elseif isInRect(x,y,{sb.sel_x_orig + sb.sel_clear_offset, sb.sel_y_orig, 8, 8})then
selection[1] = 0 selection[2] = 31
sb.sel_clr_down = true
self:drawSelect()
-- Selection B Left
elseif isInRect(x,y,{sb.sel_x_orig + sb.selB_offset, sb.sel_y_orig, 4,7}) then
if(selection[2] ~= 1 and selection[2] > selection[1])then selection[2] = selection[2] - 1 end
sb.selB_L_down = true
self:drawSelect()
-- Selection B Right
elseif isInRect(x,y,{sb.sel_x_orig + sb.selB_offset + sb.sel_R_offset, sb.sel_y_orig, 4,7}) then
if(selection[2] < 31)then selection[2] = selection[2] + 1 end
sb.selB_R_down = true
self:drawSelect()
end
elseif state == "released" then
sb.selA_L_down = false
sb.selA_R_down = false
sb.selB_L_down = false
sb.selB_R_down = false
sb.sel_clr_down = false
self:drawSelect()
end
end
local tools_grid = {ToolButtons.x_origin, ToolButtons.y_origin + ToolButtons.tools_offset, 5*11,2*11, 5,2}
local waves_grid = {ToolButtons.x_origin, ToolButtons.y_origin + ToolButtons.waves_offset, 9*6,8,6,1}
function se:toolPitchUp()
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
local note,oct,wave,amp = sfx:getNote(i)
-- Make sure we're not at max
if(oct <= 7 or note < 12)then
-- loop
if(note == 12)then
note = 1
oct = oct + 1
else
note = note + 1
end
end
if(amp > 0)then
sfx:setNote(i,note,oct)
end
end
drawGraph()
se:addHistory()
end
function se:toolPitchDown()
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
local note,oct,wave,amp = sfx:getNote(i)
-- Make sure we're not at min
if(oct > 1 or note > 1)then
-- loop
if(note == 1)then
note = 12
oct = oct - 1
else
note = note - 1
end
end
sfx:setNote(i,note,oct)
end
drawGraph()
se:addHistory()
end
function se:toolOctaveUp()
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
local note,oct,wave,amp = sfx:getNote(i)
if(oct <= 6)then
oct = oct + 1
end
if(amp > 0)then
sfx:setNote(i,note,oct)
end
end
se:addHistory()
end
function se:toolOctaveDown()
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
local note,oct = sfx:getNote(i)
if(oct > 1)then
oct = oct - 1
end
sfx:setNote(i,note,oct)
end
se:addHistory()
end
function se:toolCopy()
local sfx = sfxobj(selection[2]+1 - selection[1]+1, sfxdata[selectedSlot]:getSpeed())
local ind = 1
for i=selection[1],math.min(sfxNotes-1,selection[2]) do
local c_note,c_oct,c_wave,c_vol = sfxdata[selectedSlot]:getNote(i)
sfx:setNote(ind,c_note,c_oct,c_wave,c_vol)
ind = ind + 1
end
--Save to clipboard
local copy = sfxdata[selectedSlot]:export():sub(3,-2):sub(selection[1]*6+1,(selection[2]+1)*6)
clipboard(copy)
color(4)
_systemMessage("SFX data ["..(selection[1]+1).."-"..(selection[2]+1).."] copied to buffer")
drawGraph()
end
function se:toolPaste()
local paste = nil
local clip = clipboard()
local ok, err = pcall(function()
if(clip:sub(-1,-1) ~= ",")then clip = clip.."," end
local new_sfx = sfxobj(#clip/6,1)
new_sfx:import("1:"..clip)
paste = new_sfx
local notes_given = paste.notes - 1
local notes_pasted = math.min(selection[2] - selection[1],notes_given)
local target_area = {selection[1], math.min(selection[2],selection[1] + notes_given)}
local sfx = sfxdata[selectedSlot]
local ind = 0
for i = target_area[1],target_area[2] do
local note,oct,wave,vol = paste:getNote(ind)
sfx:setNote(i,note,oct,wave,vol)
ind = ind + 1
end
selection[2] = math.min(target_area[2], selection[1] + notes_pasted)
se:addHistory()
_systemMessage("Pasted "..notes_pasted.." of "..notes_given.." notes to ["..(target_area[1]+1).."-"..(target_area[2]+1).."]")
end)
if not ok then
_systemMessage("No SFX data in buffer to paste!",5)
cprint("PASTE ERR: "..(err or "nil"))
end
drawGraph()
end
function se:toolDelete()
-- Clear all notes in selection
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
sfx:setNote(i,1,1,0,0)
end
drawGraph()
se:addHistory()
end
function se:toolFlatten()
local notes = {}
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
local note, oct, _, amp = sfx:getNote(i)
if(amp > 0)then
table.insert(notes, oct * 12 + note)
end
end
local sum = 0
for i=1,#notes do
sum = sum + notes[i]
end
local result = sum/#notes
local average_note = {result % 12, math.floor(result/12)}
for i=selection[1],selection[2] do
local _,_,_,amp = sfx:getNote(i)
if(amp > 0)then
sfx:setNote(i, average_note[1], average_note[2])
end
end
drawGraph()
se:addHistory()
end
function se:toolUndo()
if(history_index < history_size and history[history_index + 1] ~= nil)then
sfxdata[selectedSlot]:import(history[history_index + 1])
history_index = history_index + 1
else
_systemMessage("No more steps to undo available.")
end
drawGraph()
end
function se:toolRedo()
if(history_index - 1 > 0)then
sfxdata[selectedSlot]:import(history[history_index - 1])
history_index = history_index - 1
else
_systemMessage("No more steps to redo available.")
end
drawGraph()
end
function se:toolsMouse(state,x,y,button,istouch)
local cx,cy = whereInGrid(x,y, tools_grid)
local tb = ToolButtons
if(cx and state == "pressed")then
local tools = {
{se.toolPitchUp, se.toolPitchDown, se.toolCopy, se.toolPaste, se.toolDelete},
{se.toolOctaveUp, se.toolOctaveDown, se.toolFlatten,se.toolUndo,se.toolRedo},
}
tb.tool_down = cx-1 + (cy-1)*5
if(tools[cy][cx] ~= nil)then
tools[cy][cx]()
end
self:drawTools()
end
if(state == "pressed")then
cx,cy = whereInGrid(x,y,waves_grid)
if(cx)then
tb.wave_down = cx -1
local sfx = sfxdata[selectedSlot]
for i=selection[1],selection[2] do
local note,oct,wave,amp = sfx:getNote(i)
sfx:setNote(i,note,oct,cx-1,amp)
end
self:drawTools()
end
end
if state == "released" then
tb.tool_down = -1
tb.wave_down = -1
self:drawTools()
end
end
function se:addHistory()
if(history_index > 1)then
for i = 1, history_index-1 do
table.remove(history,1)
end
history_index = 1
end
table.insert(history, 1, sfxdata[selectedSlot]:export())
if(#history > history_size)then table.remove(history, history_size+1) end
end
function se:clearHistory()
history_index = 1
history = {}
end
se.keymap = {
--Play SFX
["space"] = function(self)
if playingNote >= 0 then
if Audio then Audio.stop() end
playingNote = -1
else
sfxdata[selectedSlot]:play(0)
playingNote = 0
end
drawGraph()
self:drawPlay()
end,
--Select Waveform
["1"] = function(self)
selectedWave = 0
self:drawWave()
end,
["2"] = function(self)
selectedWave = 1
self:drawWave()
end,
["3"] = function(self)
selectedWave = 2
self:drawWave()
end,
["4"] = function(self)
selectedWave = 3
self:drawWave()
end,
["5"] = function(self)
selectedWave = 4
self:drawWave()
end,
["6"] = function(self)
selectedWave = 5
self:drawWave()
end,
--Decrease speed
["z"] = function(self)
speed = math.max(speed-0.25,0.25)
sfxdata[selectedSlot]:setSpeed(speed)
self:drawSpeed()
end,
--Increase speed
["x"] = function(self)
speed = math.min(speed+0.25,99*0.25)
sfxdata[selectedSlot]:setSpeed(speed)
self:drawSpeed()
end,
--Decrease slot
["a"] = function(self)
selectedSlot = math.max(selectedSlot-1,0)
speed = sfxdata[selectedSlot]:getSpeed()
drawGraph() self:drawSlot() self:drawSpeed()
end,
--Increase slot
["s"] = function(self)
selectedSlot = math.min(selectedSlot+1,sfxSlots-1)
speed = sfxdata[selectedSlot]:getSpeed()
drawGraph() self:drawSlot() self:drawSpeed()
end,
["f"] = se.toolFlatten,
["m"] = se.addHistory,
["n"] = se.clearHistory,
["up"] = se.toolPitchUp,
["down"] = se.toolPitchDown,
["left"] = function(self)
if(selection[1] > 0)then
selection[1] = selection[1] - 1
selection[2] = selection[2] - 1
end
self:drawSelect()
drawGraph()
end,
["right"] = function(self)
if(selection[2] < 31)then
selection[1] = selection[1] + 1
selection[2] = selection[2] + 1
end
self:drawSelect()
drawGraph()
end,
["ctrl-c"] = se.toolCopy,
["ctrl-v"] = se.toolPaste,
["delete"] = se.toolDelete,
["ctrl-z"] = se.toolUndo,
["ctrl-y"] = se.toolRedo,
}
function se:checkGraphs()
if(touched_graphs)then
se:addHistory()
touched_graphs = false
end
end
function se:update(dt)
if playingNote >= 0 then
playingNote = playingNote + (dt*sfxNotes)/speed
if playingNote >= sfxNotes then
playingNote = -1
self:drawPlay()
end
drawGraph()
end
end
function se:mousepressed(x,y,button,istouch)
self:pitchMouse("pressed",x,y,button,istouch)
self:volumeMouse("pressed",x,y,button,istouch)
self:slotMouse("pressed",x,y,button,istouch)
self:speedMouse("pressed",x,y,button,istouch)
self:playMouse("pressed",x,y,button,istouch)
self:waveMouse("pressed",x,y,button,istouch)
self:selectMouse("pressed",x,y,button,istouch)
self:toolsMouse("pressed",x,y,button,istouch)
end
function se:mousemoved(x,y,button,istouch)
self:pitchMouse("moved",x,y,dx,dy,istouch)
self:volumeMouse("moved",x,y,dx,dy,istouch)
self:slotMouse("moved",x,y,dx,dy,istouch)
self:speedMouse("moved",x,y,dx,dy,istouch)
self:playMouse("moved",x,y,dx,dy,istouch)
self:waveMouse("moved",x,y,dx,dy,istouch)
self:toolsMouse("moved",x,y,dx,dy,istouch)
end
function se:mousereleased(x,y,button,istouch)
self:pitchMouse("released",x,y,button,istouch)
self:volumeMouse("released",x,y,button,istouch)
self:slotMouse("released",x,y,button,istouch)
self:speedMouse("released",x,y,button,istouch)
self:playMouse("released",x,y,button,istouch)
self:waveMouse("released",x,y,button,istouch)
self:selectMouse("released",x,y,button,istouch)
self:toolsMouse("released",x,y,button,istouch)
self:checkGraphs()
end
function se:export()
local data, dpos = {}, 1
for i=0,sfxSlots-1 do
data[dpos] = sfxdata[i]:export():sub(1,-2)
data[dpos+1] = ";\n"
dpos = dpos +2
end
return table.concat(data)
end
function se:import(data)
data = data:gsub("\n","")
local id = 0
for sfxd in data:gmatch("(.-);") do
sfxdata[id]:import(sfxd..",")
id = id + 1
end
end
function se:encode()
local data, dpos = {}, 1
for i=0,sfxSlots-1 do
data[dpos] = sfxdata[i]:encode()
dpos = dpos +1
end
return table.concat(data)
end
function se:decode(data)
for i=0,sfxSlots-1 do
local bin = data:sub(i*53+1,i*53+53+1)
sfxdata[i]:decode(bin)
end
end
return se
|
local helper = require("thetto.lib.testlib.helper")
local thetto = helper.require("thetto")
describe("thetto", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can open ui in list buffer", function()
thetto.start("line", {opts = {insert = false}})
assert.filetype("thetto")
end)
it("can open ui in input buffer", function()
thetto.start("line")
assert.filetype("thetto-input")
end)
it("can scroll ui by offset", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {insert = false, offset = 10}})
assert.current_line("test3")
end)
it("can close ui by :quit", function()
helper.set_lines([[
test]])
thetto.start("line", {opts = {insert = false}})
vim.cmd("quit")
assert.window_count(1)
end)
it("should exist only one in a tab", function()
thetto.start("line")
thetto.start("vim/runtimepath")
assert.window_count(4)
end)
it("should exist same source only one", function()
thetto.start("line")
vim.cmd("tabedit")
thetto.start("line")
assert.window_count(4)
end)
it("can filter by substring", function()
thetto.setup({sorters = {"length"}})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
helper.sync_input({"2"})
thetto.execute("move_to_list")
assert.current_line("test2")
assert.no.exists_pattern("test1")
end)
it("can filter with ignorecase", function()
helper.set_lines([[
test1
TEST2
test2
test3]])
thetto.start("line", {opts = {ignorecase = true}})
helper.sync_input({"test2"})
thetto.execute("move_to_list")
assert.current_line("TEST2")
end)
it("can filter with smartcase", function()
helper.set_lines([[
TEST1
test1
hoge]])
thetto.start("line", {opts = {smartcase = true}})
helper.sync_input({"t"})
thetto.execute("move_to_list")
assert.exists_pattern("TEST1")
assert.exists_pattern("test1")
assert.no.exists_pattern("hoge")
thetto.execute("move_to_input")
vim.cmd("normal! dd")
helper.sync_input({"TE"})
thetto.execute("move_to_list")
assert.exists_pattern("TEST1")
assert.no.exists_pattern("test1")
assert.no.exists_pattern("hoge")
end)
it("should show an error message if not found source", function()
thetto.start("invalid")
assert.exists_message("not found source: invalid")
assert.window_count(1)
end)
it("can input lua escape character", function()
helper.set_lines([[
test1
test%
test3]])
thetto.start("line")
helper.sync_input({"%"})
thetto.execute("move_to_list")
assert.current_line("test%")
end)
it("stops the unfinished job on closed", function()
local job = require("thetto.lib.job").new({"sleep", "9"}, {})
require("thetto.handler.source.line").collect = function(_)
return {}, job
end
thetto.start("line", {opts = {insert = false}})
thetto.execute("quit")
assert.is_false(job:is_running())
end)
it("can open with action opts", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {insert = false}, action_opts = {register = 1}})
helper.search("test3")
thetto.execute("yank")
assert.register_value("1", "test3")
end)
it("can use sorters", function()
helper.set_lines([[
te
t
test
tes]])
thetto.start("line", {opts = {insert = false, sorters = {"length"}}})
assert.current_line("t")
vim.cmd("normal! j")
assert.current_line("te")
vim.cmd("normal! j")
assert.current_line("tes")
end)
it("can set input lines", function()
helper.set_lines([[
hoge
test]])
thetto.start("line", {opts = {insert = false, input_lines = {"test"}}})
assert.current_line("test")
end)
it("does not open windows if no items", function()
thetto.start("cmd/ctags")
assert.exists_message("cmd/ctags: empty")
assert.window_count(1)
thetto.start("cmd/ctags")
-- should be the same error
assert.exists_message("cmd/ctags: empty")
end)
it("cannot delete input lines", function()
thetto.setup({filters = {"substring", "-substring"}})
thetto.start("line")
helper.wait_ui(function()
vim.cmd("normal! dd")
end)
assert.line_count(2)
end)
it("can move to input with behavior as `i`", function()
thetto.setup({filters = {"substring", "-substring"}})
thetto.start("line")
helper.sync_input({"hoge"})
thetto.execute("move_to_list")
thetto.execute("move_to_input")
assert.current_column(#("hoge"))
end)
it("can move to input with behavior as `a`", function()
thetto.setup({filters = {"substring", "-substring"}})
thetto.start("line")
helper.sync_input({"hoge"})
thetto.execute("move_to_list")
thetto.execute("move_to_input", {action_opts = {behavior = "a"}})
assert.current_column(#("hoge") + 1)
end)
it("can filter by regex", function()
thetto.setup({filters = {"regex"}})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
helper.sync_input({"2$"})
thetto.execute("move_to_list")
assert.exists_pattern("test2")
end)
it("closes ui completely", function()
thetto.start("line")
vim.cmd("buffer #")
vim.cmd("close")
assert.window_count(1)
end)
it("can focus only input or list", function()
helper.set_lines([[
test1
test2]])
thetto.start("line")
for _, window in ipairs(helper.sub_windows()) do
vim.fn.win_gotoid(window)
assert.no.filetype("")
end
end)
it("can execute action automatically", function()
local value = nil
thetto.setup({
source_actions = {
line = {
action_hoge = function(_, items)
value = items[1].value
end,
behaviors = {hoge = {quit = false}},
},
},
})
helper.set_lines([[
test_auto_1
test_auto_2]])
thetto.start("line", {opts = {auto = "hoge", insert = false}})
assert.equals("test_auto_1", value)
thetto.execute("move_to_input")
helper.sync_input({"test_auto_2"})
assert.equals("test_auto_2", value)
end)
it("can use visual mode even if enabled auto action", function()
thetto.setup({
source_actions = {
line = {
action_hoge = function(_, _)
vim.cmd("normal! " .. vim.api.nvim_eval("\"\\<ESC>\""))
end,
behaviors = {hoge = {quit = false}},
},
},
})
helper.set_lines([[
test_auto_1
test_auto_2]])
thetto.start("line", {opts = {auto = "hoge", insert = false}})
vim.cmd("normal! Vj")
vim.cmd("doautocmd CursorMoved")
thetto.execute("toggle_selection")
thetto.execute("tab_open")
assert.tab_count(3)
end)
end)
describe("thetto.reload()", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("collects results again", function()
local origin_window = vim.api.nvim_get_current_win()
helper.set_lines([[
test1
test2
]])
thetto.start("line", {opts = {insert = false, input_lines = {"test2"}}})
vim.api.nvim_set_current_win(origin_window)
vim.cmd("wincmd p")
helper.sync_reload()
thetto.execute("move_to_input")
vim.cmd("delete _")
thetto.execute("move_to_list")
assert.current_line("test2")
end)
end)
describe("thetto.execute()", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("should show an error message if not found action", function()
thetto.start("line")
thetto.execute("invalid")
assert.exists_message("not found action: invalid")
end)
it("shows error if items is empty because filtered", function()
thetto.start("line")
helper.sync_input({"hoge"})
thetto.execute("open")
assert.exists_message("not found action: open")
end)
it("cannot execute open if there is no items", function()
thetto.start("line")
helper.sync_input({"hoge"})
thetto.execute("open")
assert.exists_message("not found action: open")
end)
it("can use custom action as default", function()
local called = false
thetto.setup({
kind_actions = {
["vim/variable"] = {
action_hoge = function(_)
called = true
end,
},
},
source = {["vim/variable"] = {global_opts = {action = "hoge"}}},
})
thetto.start("vim/variable", {opts = {insert = false}})
thetto.execute()
assert.is_true(called)
end)
end)
describe("thetto.setup()", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can custom default opts", function()
thetto.setup({global_opts = {display_limit = 1}})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {insert = false}})
assert.line_count(1)
end)
it("can custom source global options", function()
thetto.setup({source = {line = {global_opts = {insert = false}}}})
helper.set_lines([[
test1
test2]])
thetto.start("line")
assert.current_line("test1")
end)
it("can custom source action", function()
local called = false
thetto.setup({
source_actions = {
line = {
action_hoge = function(_)
called = true
end,
},
},
})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {action = "hoge"}})
thetto.execute()
assert.is_true(called)
end)
it("can custom kind action", function()
local called = false
thetto.setup({
kind_actions = {
["file/directory"] = {
action_hoge = function(_)
called = true
end,
},
},
})
helper.set_lines([[
test1
test2
test3]])
thetto.start("vim/runtimepath", {opts = {action = "hoge"}})
thetto.execute()
assert.is_true(called)
end)
end)
describe("thetto.resume()", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can resume even if opened", function()
thetto.start("line")
vim.cmd("tabedit")
thetto.resume()
assert.window_count(4)
end)
it("goes back to original window when quit resumed thetto", function()
thetto.start("line")
vim.cmd("tabedit")
local current = vim.api.nvim_get_current_win()
thetto.resume()
thetto.start("line")
thetto.execute("quit")
assert.window(current)
end)
it("can resume latest", function()
helper.set_lines([[
test11
test21
test22]])
thetto.start("line")
helper.sync_input({"test2"})
thetto.execute("move_to_list")
vim.cmd("normal! G")
thetto.execute("quit")
thetto.resume()
thetto.execute("move_to_input")
assert.filetype("thetto-input")
assert.current_line("test2")
thetto.execute("move_to_list")
assert.current_line("test22")
vim.cmd("normal! gg")
assert.current_line("test21")
end)
it("can resume by source", function()
helper.set_lines([[
test11
test21
test22]])
thetto.start("line")
helper.sync_input({"test2"})
thetto.execute("quit")
thetto.start("vim/runtimepath")
thetto.execute("quit")
thetto.resume("line")
assert.filetype("thetto-input")
assert.current_line("test2")
thetto.execute("move_to_list")
assert.current_line("test21")
end)
it("can resume current window", function()
helper.set_lines([[
test1
test2]])
thetto.start("line")
thetto.execute("move_to_list")
thetto.execute("quit")
thetto.resume()
assert.exists_pattern("test1")
end)
it("can resume empty result", function()
thetto.start("cmd/ctags", {opts = {insert = false}})
thetto.resume()
assert.current_line("")
end)
end)
describe("thetto.resume_execute()", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can resume with offset", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
thetto.execute("quit")
thetto.resume_execute({opts = {offset = -1}})
assert.current_line("test1")
thetto.resume_execute({opts = {offset = 1}})
assert.window_count(1)
assert.current_line("test2")
thetto.resume_execute({opts = {offset = 1}})
assert.window_count(1)
assert.current_line("test3")
thetto.resume_execute({opts = {offset = 1}})
assert.current_line("test3")
end)
end)
describe("resume_previous action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can resume previous source", function()
helper.set_lines([[
test1
test2]])
thetto.start("line", {opts = {insert = false}})
helper.search("test2")
thetto.start("thetto/source")
thetto.execute("resume_previous")
thetto.execute("open")
assert.current_line("test2")
end)
it("can resume wrapped previous source", function()
helper.set_lines([[
test1
test2]])
thetto.start("thetto/source", {opts = {insert = false}})
thetto.execute("quit")
thetto.start("line", {opts = {insert = false}})
helper.search("test2")
thetto.execute("resume_previous")
assert.exists_pattern("^line$")
thetto.execute("resume_previous")
thetto.execute("open")
assert.current_line("test2")
end)
end)
describe("resume_next action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can resume next source", function()
helper.set_lines([[
test1
test2]])
thetto.start("thetto/source")
thetto.execute("quit")
thetto.start("line", {opts = {insert = false}})
helper.search("test2")
thetto.execute("resume_previous")
thetto.execute("resume_next")
thetto.execute("open")
assert.current_line("test2")
end)
it("can resume wrapped next source", function()
helper.set_lines([[
test1
test2]])
thetto.start("line", {opts = {insert = false}})
helper.search("test2")
thetto.start("thetto/source")
thetto.execute("resume_next")
thetto.execute("open")
assert.current_line("test2")
end)
end)
describe("remove_filter action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can remove filter", function()
thetto.setup({source = {line = {filters = {"substring", "-substring"}}}})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
vim.cmd("normal! G")
helper.sync_input({"test2"})
helper.wait_ui(function()
thetto.execute("remove_filter", {action_opts = {name = "-substring"}})
end)
thetto.execute("move_to_list")
assert.exists_pattern("test2")
end)
it("cannot remove the last filter", function()
thetto.start("line")
thetto.execute("remove_filter")
assert.exists_message("the last filter cannot be removed")
end)
end)
describe("reverse_sorter action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can reverse sorter", function()
thetto.setup({sorters = {"length"}})
helper.set_lines([[
te
t
tes]])
thetto.start("line", {opts = {insert = false}})
assert.current_line("t")
helper.wait_ui(function()
thetto.execute("reverse_sorter")
end)
assert.current_line("tes")
end)
it("can reverse specified sorter", function()
thetto.setup({sorters = {"length", "row"}})
helper.set_lines([[
te
t
tes]])
thetto.start("line", {opts = {insert = false}})
assert.current_line("t")
helper.wait_ui(function()
thetto.execute("reverse_sorter", {action_opts = {name = "length"}})
end)
assert.current_line("tes")
end)
end)
describe("add_filter action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can add filter", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
thetto.execute("add_filter", {action_opts = {name = "-substring"}})
vim.cmd("normal! G")
helper.sync_input({"test2"})
thetto.execute("move_to_list")
assert.exists_pattern("test1")
assert.exists_pattern("test3")
end)
end)
describe("inverse_filter action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can inverse filter", function()
thetto.setup({filters = {"-substring"}})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
helper.sync_input({"test2"})
thetto.execute("inverse_filter")
assert.exists_pattern("test2")
end)
end)
describe("change_filter action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can change filter", function()
thetto.setup({filters = {"substring"}})
helper.set_lines([[
test1
test2
test3]])
thetto.start("line")
helper.sync_input({"test2"})
helper.wait_ui(function()
thetto.execute("change_filter", {action_opts = {name = "-substring"}})
end)
thetto.execute("move_to_list")
assert.no.exists_pattern("test2")
end)
end)
describe("toggle_sorter action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can add sorter by toggle_sorter", function()
helper.set_lines([[
te
t
tes]])
thetto.start("line", {opts = {insert = false}})
helper.wait_ui(function()
thetto.execute("toggle_sorter", {action_opts = {name = "length"}})
end)
assert.current_line("t")
end)
it("can remove sorter by toggle_sorter", function()
thetto.setup({sorters = {"length"}})
helper.set_lines([[
te
t
tes]])
thetto.start("line", {opts = {insert = false}})
helper.wait_ui(function()
thetto.execute("toggle_sorter", {action_opts = {name = "length"}})
end)
assert.current_line("te")
end)
end)
describe("debug_print action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can execute debug_print", function()
helper.set_lines([[
test1
test2]])
thetto.start("line")
thetto.execute("debug_print")
assert.exists_message("row = 1")
assert.exists_message("value = \"test1\"")
end)
end)
describe("toggle_selection action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can select items and execute action", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {insert = false}})
thetto.execute("toggle_selection")
vim.cmd("normal! j")
thetto.execute("toggle_selection")
vim.cmd("normal! j")
thetto.execute("toggle_selection")
thetto.execute("toggle_selection")
thetto.execute("tab_open")
assert.tab_count(3)
assert.current_line("test2")
end)
it("can execute with range", function()
helper.set_lines([[
test1
test2
test3
test4
test5]])
thetto.start("line", {opts = {insert = false}})
vim.cmd("2")
vim.cmd("normal! v2j")
thetto.execute("toggle_selection")
thetto.execute("tab_open")
assert.tab_count(4)
end)
end)
describe("toggle_all_selection action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can execute toggle_all_selection", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {insert = false}})
helper.search("test2")
thetto.execute("toggle_selection")
thetto.execute("toggle_all_selection")
thetto.execute("tab_open")
assert.tab_count(3)
assert.current_line("test3")
vim.cmd("tabclose")
assert.current_line("test1")
end)
end)
describe("append action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can execute append", function()
helper.set_lines([[
test1
test2
test3]])
vim.cmd("normal! $")
thetto.start("line", {opts = {insert = false}})
helper.search("test2")
thetto.execute("append")
assert.current_line("test1test2")
end)
end)
describe("yank action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can yank item value", function()
helper.set_lines([[
test1
test2
test3]])
thetto.start("line", {opts = {insert = false}})
vim.cmd("normal! vj")
thetto.execute("yank")
assert.register_value("+", "test1\ntest2")
end)
end)
describe("toggle_preview action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can toggle preview", function()
helper.set_lines([[
test1
test2]])
thetto.start("line", {opts = {insert = false}})
local count = helper.window_count()
thetto.execute("toggle_preview")
assert.window_count(count + 1)
thetto.execute("toggle_preview")
assert.window_count(count)
end)
it("can execute continuously", function()
helper.set_lines([[
test1
test2]])
thetto.start("line", {opts = {insert = false}})
local count = helper.window_count()
thetto.execute("toggle_preview")
assert.window_count(count + 1)
vim.cmd("normal! j")
thetto.execute("toggle_preview")
assert.window_count(count + 1)
end)
end)
describe("preview action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can open preview", function()
helper.set_lines([[
test1
test2]])
thetto.start("line", {opts = {insert = false}})
local count = helper.window_count()
thetto.execute("preview")
assert.window_count(count + 1)
end)
end)
describe("close_preview action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can close preview", function()
helper.set_lines([[
test1
test2]])
thetto.start("line", {opts = {insert = false}})
local count = helper.window_count()
thetto.execute("preview")
thetto.execute("close_preview")
assert.window_count(count)
end)
end)
describe("move_to_input action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can move to filter", function()
thetto.start("line", {opts = {insert = false}})
assert.filetype("thetto")
thetto.execute("move_to_input")
assert.filetype("thetto-input")
end)
end)
describe("move_to_list action", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("can move to list", function()
thetto.start("line")
assert.filetype("thetto-input")
thetto.execute("move_to_list")
assert.filetype("thetto")
end)
it("can move to list even if empty", function()
thetto.start("line")
helper.sync_input({"test"})
assert.filetype("thetto-input")
thetto.execute("move_to_list")
assert.filetype("thetto")
end)
end)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.