content
stringlengths 5
1.05M
|
---|
return Def.ActorFrame{
Def.Sprite {
Texture=NOTESKIN:GetPath( '_down', 'tap mine' );
Frame0000=0;
Delay0000=1;
InitCommand=function(self)
self:spin():effectclock('beat'):effectmagnitude(0,0,32)
end;
};
};
|
local screenX, screenY = guiGetScreenSize()
local panelState = false
local bgWidth = 900
local bgHeight = 570
local bgPosX = (screenX / 2) - (bgWidth / 2)
local bgPosY = (screenY / 2) - (bgHeight / 2)
local bgMargin = 3
local titleFont = false
local itemFont = false
local mainColumnWidth = 300
local mainColumnHeight = bgHeight - 90
local mainColumnPosX = bgPosX + 10
local mainColumnPosY = bgPosY + 40
local mainColumnTitle = "Categorias:"
local selectedColumnTitle = "Descrição:"
local notificationText = ""
local notificationTick = 0
local selectWidth = 400
local selectHeight = 120
local selectPosX = (screenX / 2) - (selectWidth / 2)
local selectPosY = (screenY / 2) - (selectHeight / 2)
local infoWidth = 600
local infoHeight = 400
local infoPosX = (screenX / 2) - (infoWidth / 2)
local infoPosY = (screenY / 2) - (infoHeight / 2)
local infoText = ""
local availableCategories = {
[1] = {
["name"] = "Primeiros Passos",
["imagePath"] = "arquivos/imagens/18.png",
["subCategories"] = {
[1] = {
["name"] = "Regras Gerais",
["imagePath"] = false,
["description"] = "#d9534fLínguagem principal do servidor é o Português#ffffff, o que significa\
que é a única língua que você pode usar na caixa de mensagens.\
No entanto, você pode usar qualquer língua ao enviar mensagens\
privadas\
\
#d9534fOfenças e xingamentos é proíbido#ffffff\
\
Falta de conhecimento sobre as regras não significa que você\
não vá cumprilas.\
\
#2F7CCCVocê pode encontrar todas as regras em: www.vdbg.org"
},
[2] = {
["name"] = "Controles",
["imagePath"] = false,
["description"] = "Os #2F7CCCcomandos#ffffff do servidor você pode encontrar\
em nosso #2F7CCCfórum#ffffff, até porque temos um monte de comandos\
e binds vínculadas e personalizadas.\
\
#d9534fAlém dos comandos você encontra muitos outros recursos.#ffffff\
\
@ #2F7CCCwww.vdbg.org"
},
[3] = {
["name"] = "Estilos de Chat",
["imagePath"] = false,
["description"] = "VDBGaming tem diferentes tipos de #2F7CCCbate-papos#ffffff com várias finalidades.\
\
Pressione 'T' para usar o #2F7CCCchat principal#ffffff.\
O #2F7CCCbate-papo mais monitorado#ffffff onde é forçado a ser falado #2F7CCCportuguês.#ffffff\
#d9534fSpams, inundações e publicidade #ffffffsão totalmente proíbidos,\
Pressione 'o' para usar o #FFBF00Chat local#ffffff. Este chat foi criado para que \
os jogadores seria capaz de conversar com #2F7CCCoutros jogadores nas\
proximidades.#ffffff\
Pressione Y para usar o #FFBF00bate papo de equipe#ffffff\
Equipe de bate-papo foi criado para que você e os outros #2F7CCCjogadores\
da mesma equipe#ffffff '#d9534fCriminoso, #428bcaCidadão, #4aabd0Policial#ffffff' e etc.\
O #FFBF00Bate-papo do veículo#ffffff fica disponível com: /cc [texto] para usá-lo.\
Se você estiver em um veículo, você pode usar este \
bate-papo para falar com os ocupantes do veículo.\
"
},
[4] = {
["name"] = "Selecionar uma Equipe",
["imagePath"] = false,
["description"] = "Temos #FFBF00Três grupos principais#ffffff em nosso servidor\
\
#d9534fCriminoso\
#428bcaCidadão\
#4aabd0Policial\
\
#ffffffCada grupo tem um papel diferente, \
a maioria pode ser adivinhado pelo nome dele \
Você pode #428bcadescobrir mais sobre os grupos#ffffff \
se você ler sobre, ou visitar o nosso site \
\
VDBGaming #428bca @ www.vdbg.org"
},
[5] = {
["name"] = "HUD",
["imagePath"] = false,
["description"] = "#d9534fO artigo a seguir ainda não fui adicionado ao banco de dados."
--["price"] = 1000,
--["amount"] = 1
},
[6] = {
["name"] = "Player Stats",
["imagePath"] = false,
["description"] = "Este sistema está incluído no #d9534fpainel do usuário."
},
[7] = {
["name"] = "O painel do usuário",
["imagePath"] = false,
["description"] = "Estamos projetando um #428bca painel do usuário#ffffff\
baseada em' dxDraw ' Este painel inclui as informações \
do usuário informações como: #428bca Equipe, Dinheiro, ID da conta, \
Configurações de Interface, Escolher Avatar#ffffff e outros \
\
Lembrando que este painel está estruturado, porém está sendo\
feito aos poucos, pois não temos todo o tempo do mundo, \
e além disso temos outras #d9534fpendências#ffffff do servidor.\
"
},
[8] = {
["name"] = "Inventário",
["imagePath"] = false,
["description"] = "O #428bcainventário#ffffff é uma das partes mais #d9534fimportantes#ffffff da jogabilidade.\
Você pode ver o painel pressionando a #428bcatecla 'i'.\
\
Você pode ver todos os seus #428bcaitens no painel#ffffff, você pode vender\
na #428bcafeira do rolo#ffffff e #d9534fjogar fora#ffffff, qualquer item.\
"
},
[9] = {
["name"] = "Criação de Armas",
["imagePath"] = false,
["description"] = "text\ntext"
},
[10] = {
["name"] = "Painél do veículo",
["imagePath"] = false,
["description"] = "O paínel do veículo é uma das principais\
atividades do servidor. Você pode ver o painel precionando\
'F2'. Você pode ver todos os veículos nesse painél\
\
Caso você perca seu veículo, use o botão asseguradora\
e automaticamente seu veículo será recuperado\
Note que após assegurar o seu veículo, ele irá para o seguro\
que fica no centro do mapa.\
"
},
},
},
[2] = {
["name"] = "Cidadão",
["imagePath"] = "arquivos/imagens/18.png",
["subCategories"] = {
[1] = {
["name"] = "Recursos Básicos",
["imagePath"] = false,
["description"] = "A equipe #428bcaVDBGaming #FFFFFFse empenhou muito, criando diversos trabalhos.\
Entre eles estão os trabalhos civis, que são os\
trabalho que geralmente não envolvem armas.\
*Taxista, Mecânico, caminhoneiro e muito mais!\
* Para uma descrição mais detalhada leia a sessão: Cidadãos\
Há também trabalhos que podem envolver armas, como os\
criminosos ou agentes da lei.\
Criminosos: Fazem ações criminosas, como o nome já diz.\
\
Ações criminosas:\
- Hacker, Ladrão de Carros, traficante de drogas entre outros\
* Para uma descrição mais detalhada leia a sessão: 'criminosos'.\
Policiais: Combatem as ações dos criminosos.\
* Para uma descrição mais detalhada leia a sessão: 'Policiais'."
},
[2] = {
["name"] = "Trabalhos",
["imagePath"] = false,
["description"] = "Como policial, seu trabalho sempre será prender criminosos\
- Encontrando criminosos:\
Uma algema acima da cabeça do jogador\
Você pode acessar o computador policial precionando'F5',\
Pegue uma algema e bata no criminoso que está com algema na\
cabeça, assim você irá algema-lo. Logo depois leve-o até a prisão,\
irá ter um check-point azul te esperando"
},
[3] = {
["name"] = "Mecânico",
["imagePath"] = false,
["description"] = "Um mecânico realiza reparos em veículos.\
Para reparar um veículo apenas fique parado ao lado do veículo e pressione\
'M' do seu teclado, em seguida, clique no carro que você deseja reparar\
Reboque os carros para a asseguradora que fica na oficina de SF\
com isso você ganhe R$ 1000,00 por veículo.\
\
Perk trabalho: N/A\
"
},
[4] = {
["name"] = "Motorista",
["imagePath"] = false,
["description"] = "Um motorista faz viagens de ônibus pela cidade.\
As cidades disponíveis para rotas são:\
- SF\
- LS\
\
Ambas as cidades tem dois tipos de ônibus para realizar esta tarefa.\
O dinheiro é pago em cada parada, além disso você ganha pontos em #428bcaXP#ffffff.\
\
Esses pontos de #428bcaXP#FFFFFF aumenta seu nível de jogo.\
\
Perk trabalho: N/A\
"
--["price"] = 1000,
--["amount"] = 1
},
[5] = {
["name"] = "Stunter",
["imagePath"] = false,
["description"] = "Um Stunter realiza manobras com motos.\
Em qualquer lugar do mapa, realize uma manobra com uma:\
\
- MOTO\
-BICICLETA\
\
Cidades disponíveis:\
- SF\
- LS\
- LV\
\
Ambas as cidades tem mais que dois tipos de motocicletas para realizar esta tarefa.\
O dinheiro é pago a cada manobra, além disso você ganha pontos em #428bcaXP#ffffff.\
Esses pontos de #428bcaXP#FFFFFF aumenta seu nível de jogo.\
\
Perk trabalho: N/A\
"
--["price"] = 1000,
--["amount"] = 1
},
[6] = {
["name"] = "Moto-BOY",
["imagePath"] = false,
["description"] = "Um Moto-BOY realiza entregas de pizzas.\
Veículos disponíveis para realizar esta tarefa:\
\
- PIZZABOY\
\
Cidades disponíveis:\
- SF\
- LS\
\
Ambas as cidades tem mais que vinte lugares para realizar esta tarefa.\
O dinheiro é pago a cada entrega, além disso você ganha pontos em #428bcaXP#ffffff.\
Esses pontos de #428bcaXP#FFFFFF aumenta seu nível de jogo.\
\
Perk trabalho: N/A\
"
--["price"] = 1000,
--["amount"] = 1
},
[7] = {
["name"] = "Criminoso",
["imagePath"] = false,
["description"] = "Como um criminoso, você é o verdadeiro protagonista do VDBG!\
Mas cuidado, o trabalho de policial, é somente para irritar você,\
principalmente em sua ascensão ao poder. \
Algumas ações criminosas:\
\
-Você Pode vender drogas.\
-Você Pode entregar drogas com uma van\
-Você Pode criar armas.\
-Você Pode controlar um território e ganhar dinheiro.\
-Você Pode hackear um caixa eletrônico.\
-Você Pode roubar um banco, um casino,\
-Você Pode roubar um carro escondido no mapa.\
-Você pode assaltar todas as lojas do mapa.\
\
Perk trabalho: Usar drogas.\
"
--["price"] = 1000,
--["amount"] = 1
},
[8] = {
["name"] = "Vagabundo",
["imagePath"] = false,
["description"] = "O vagabundo não tem um emprego\
por isso ganha dinheiro vagando pelo mapa a busca de\
dinheiro e comida.\
\
Você vai encontrar aleatoriamente:\
\
- Dinheiro\
- Alimentos\
- Armas.\
Alguns alimentos pode aumentar a sua saúde\
* outrospouco de comida pode abaixá-lo.\
\
Perk trabalho: Recuperar a saúde com / sono.\
"
--["price"] = 1000,
--["amount"] = 1
},
[9] = {
["name"] = "Lixeiro",
["imagePath"] = false,
["description"] = "Um Lixeiro realiza limpeza de rua.\
Veículos disponíveis para realizar esta tarefa:\
\
- Caminhão de lixo\
- Carro de limpeza de rua\
\
Cidades disponíveis:\
- LS\
\
A cidade tem mais que vinte lugares para realizar esta tarefa.\
O dinheiro é pago a cada entrega, além disso você ganha pontos em #428bcaXP#ffffff.\
Esses pontos de #428bcaXP#FFFFFF aumenta seu nível de jogo.\
\
Perk trabalho: N/A\
"
--["price"] = 1000,
--["amount"] = 1
},
[10] = {
["name"] = "Entregador",
["imagePath"] = false,
["description"] = "Um Entregador realiza entregas de encomendas.\
Veículos disponíveis para realizar esta tarefa:\
\
- VAN'S\
\
Cidades disponíveis:\
- SF\
- LS\
\
Ambas as cidades tem mais que vinte lugares para realizar esta tarefa.\
O dinheiro é pago a cada entrega, além disso você ganha pontos em #428bcaXP#ffffff.\
Esses pontos de #428bcaXP#FFFFFF aumenta seu nível de jogo.\
\
Perk trabalho: N/A\
"
--["price"] = 1000,
--["amount"] = 1
},
[11] = {
["name"] = "Piloto",
["imagePath"] = false,
["description"] = "O piloto pode voar levando jogadores em torno\
do mapa com uma taxa, você também pode ganhar dinheiro entregando os\
passageiros pré definidos pelo servidor nos aeroportos.\
\
* Veículos disponíveis para realizar esta tarefa:\
- Aeronaves\
* Cidades disponíveis:\
- Todas\
\
Ambas as cidades automaticamente coordena a cidade mais longe\
para realizar esta tarefa.\
O dinheiro é pago a cada entrega, além disso você ganha pontos em #428bcaXP#ffffff.\
Esses pontos de #428bcaXP#FFFFFF aumenta seu nível de jogo.\
\
Perk trabalho: N/A\
"
--["price"] = 1000,
--["amount"] = 1
},
},
},
[3] = {
["name"] = "Agente da Lei",
["imagePath"] = "arquivos/imagens/17.png",
["subCategories"] = {
[1] = {
["name"] = "Introdução",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[2] = {
["name"] = "Informações Básicas",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[3] = {
["name"] = "A prisão",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[4] = {
["name"] = "Ações especiais",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
},
},
[4] = {
["name"] = "Criminoso",
["imagePath"] = "arquivos/imagens/21.png",
["subCategories"] = {
[1] = {
["name"] = "Informações Básicas",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[2] = {
["name"] = "Roubo de Lojas",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[3] = {
["name"] = "Roubo de Lojas",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[4] = {
["name"] = "Roubo de Banco",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[5] = {
["name"] = "Roubo de Carros",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[5] = {
["name"] = "Transporte de Drogas",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
},
},
[5] = {
["name"] = "Locais",
["imagePath"] = "arquivos/imagens/22.png",
["subCategories"] = {
[1] = {
["name"] = "",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[2] = {
["name"] = "Staff",
["imagePath"] = false,
["description"] = "Dono/Administrador: Galego\nConsole: Strikergfx\nConsole: N/A\nAdministrador: N/A\nAdministrador: N/A\nAdministrador: N/A\nAdministrador: N/A\nAdministrador: N/A"
--["price"] = 1000,
--["amount"] = 1
},
},
},
[6] = {
["name"] = "Doações",
["imagePath"] = "arquivos/imagens/23.png",
["subCategories"] = {
[1] = {
["name"] = "Site Interativo",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[2] = {
["name"] = "Forum",
["imagePath"] = false,
["description"] = "N/A\nN/A"
--["price"] = 1000,
--["amount"] = 1
},
},
},
[7] = {
["name"] = "Perguntas e Respostas",
["imagePath"] = "arquivos/imagens/23.png",
["subCategories"] = {
[1] = {
["name"] = "Site Interativo",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[2] = {
["name"] = "Forum",
["imagePath"] = false,
["description"] = "N/A\nN/A"
--["price"] = 1000,
--["amount"] = 1
},
},
},
[8] = {
["name"] = "Site",
["imagePath"] = "arquivos/imagens/23.png",
["subCategories"] = {
[1] = {
["name"] = "Site Interativo",
["imagePath"] = false,
["description"] = "text\ntext"
--["price"] = 1000,
--["amount"] = 1
},
[2] = {
["name"] = "Forum",
["imagePath"] = false,
["description"] = "N/A\nN/A"
--["price"] = 1000,
--["amount"] = 1
},
},
},
}
local visibleItem = 1
local columnHeight = 30
local selectedCategory = false
local selectedItem = 1
local setaWidth, setaHeight = 16, 28
local upsetaPosX = mainColumnPosX + mainColumnWidth + 9
local upsetaPosY = mainColumnPosY + 5
local downsetaPosX = upsetaPosX
local downsetaPosY = mainColumnPosY + mainColumnHeight - setaHeight - 5
local exitButtonPosX = mainColumnPosX + mainColumnWidth + 50
local exitButtonPosY = mainColumnPosY + mainColumnHeight + 10
local exitButtonWidth = bgWidth - 70 - mainColumnWidth
local exitButtonHeight = 30
local amountEditBox = false
local premiumPoints = 0
local premiumTick = 0
local premiumChange = 0
function createFonts()
destroyFonts()
titleFont = dxCreateFont("arquivos/opensans.ttf", 14.5 * 2, true)
itemFont = dxCreateFont("arquivos/opensans.ttf", 9 * 3, false)
end
function destroyFonts()
if isElement(titleFont) then
destroyElement(titleFont)
end
if isElement(itemFont) then
destroyElement(itemFont)
end
end
addEventHandler("onClientResourceStop", getResourceRootElement(),
function ()
if panelState then
end
end
)
addEventHandler("onClientKey", root, function(k,v)
if (getElementData(localPlayer,"logado") == false) then return end;
if (exports.VDBGaming:isServerVDBG("adminverif","02102015") == false) then return end
if k == "F1" and v then
if not panelState then
if getElementData(localPlayer, "opendashboard") == true then return end
setElementData(localPlayer, "opendashboard", true)
playSound(":VDBGPanelSound/abre.mp3")
createFonts()
panelState = "shop"
else
panelState = false
setElementData(localPlayer, "opendashboard", false)
playSound(":VDBGPanelSound/fecha.mp3")
end
--panelState = not panelState
destroyGUI()
selectedItem = 1
selectedCategory = false
if panelState then
premiumPoints = getElementData(localPlayer, "char.artpoint")
showCursor(true)
showChat(false)
else
showCursor(false)
showChat(true)
playSound(":VDBGPanelSound/fecha.mp3", false)
destroyFonts()
setElementData(localPlayer, "opendashboard", false)
end
end
end)
addEventHandler("onClientElementDataChange", getRootElement(),
function (dataName, oldValue)
if panelState then
if source == localPlayer then
if dataName == "char.artpoint" then
local newValue = getElementData(source, "char.artpoint")
if newValue then
premiumTick = getTickCount() + 5000
premiumChange = newValue - oldValue
premiumPoints = newValue
end
end
end
end
end
)
function destroyGUI()
-- destroyElement(amountEditBox)
showChat(true)
end
function createGUI()
--destroyGUI()
--amountEditBox = guiCreateEdit(exitButtonPosX, mainColumnPosY + 410, exitButtonWidth, exitButtonHeight, "", false)
end
addEventHandler("onClientClick", getRootElement(),
function (button, state, absoluteX, absoluteY)
if button == "left" then
if state == "up" then
if panelState == "menu" then
if absoluteX >= selectPosX + 10 and absoluteX <= selectPosX + 10 + selectWidth - 20 and absoluteY >= selectPosY + 10 and absoluteY <= selectPosY + 40 then -- shop
panelState = "shop"
elseif absoluteX >= selectPosX + 10 and absoluteX <= selectPosX + 10 + selectWidth - 20 and absoluteY >= selectPosY + 45 and absoluteY <= selectPosY + 75 then -- informations
panelState = "informations"
elseif absoluteX >= selectPosX + 10 and absoluteX <= selectPosX + 10 + selectWidth - 20 and absoluteY >= selectPosY + 80 and absoluteY <= selectPosY + 110 then -- exit
--executeCommandHandler("diamondshop")
end
elseif panelState == "informations" then
if absoluteX >= infoPosX + 10 and absoluteX <= infoPosX + 10 + infoWidth - 20 and absoluteY >= infoPosY + infoHeight - 40 and absoluteY <= infoPosY + infoHeight - 10 then -- enter to shop
panelState = "shop"
end
elseif panelState == "shop" then
if absoluteX >= upsetaPosX and absoluteX <= upsetaPosX + setaWidth and absoluteY >= upsetaPosY and absoluteY <= upsetaPosY + setaHeight then
if visibleItem - 1 >= 1 then
visibleItem = visibleItem - 1
end
elseif absoluteX >= downsetaPosX and absoluteX <= downsetaPosX + setaWidth and absoluteY >= downsetaPosY and absoluteY <= downsetaPosY + setaHeight then
if selectedCategory then
if availableCategories[selectedCategory]["subCategories"][visibleItem + 16] then
visibleItem = visibleItem + 1
end
else
if availableCategories[visibleItem + 16] then
visibleItem = visibleItem + 1
end
end
elseif absoluteX >= exitButtonPosX and absoluteX <= exitButtonPosX + exitButtonWidth and absoluteY >= exitButtonPosY - exitButtonHeight - 10 and absoluteY <= exitButtonPosY - 10 then -- buy
if selectedCategory then
if availableCategories[selectedCategory] then
if availableCategories[selectedCategory]["subCategories"] then
if selectedItem then
if availableCategories[selectedCategory]["subCategories"][selectedItem] then
if selectedCategory == 1 then -- bankpénz
elseif selectedCategory == 2 then -- money
local premiumPoints = getElementData(localPlayer, "char.artpoint")
end
end
end
end
end
end
end
end
end
end
end
)
bindKey("mouse_wheel_up", "down",
function ()
if panelState then
if absX >= mainColumnPosX and absX <= mainColumnPosX + mainColumnWidth and absY >= mainColumnPosY and absY <= mainColumnPosY + mainColumnHeight then
if visibleItem - 1 >= 1 then
visibleItem = visibleItem - 1
end
end
end
end
)
bindKey("mouse_wheel_down", "down",
function ()
if panelState then
if absX >= mainColumnPosX and absX <= mainColumnPosX + mainColumnWidth and absY >= mainColumnPosY and absY <= mainColumnPosY + mainColumnHeight then
if selectedCategory then
if availableCategories[selectedCategory]["subCategories"][visibleItem + 16] then
visibleItem = visibleItem + 1
end
else
if availableCategories[visibleItem + 16] then
visibleItem = visibleItem + 1
end
end
end
end
end
)
addEventHandler("onClientRender", getRootElement(),
function ()
if panelState == "menu" then
absX, absY = 0, 0
if isCursorShowing() then
local relX, relY = getCursorPosition()
absX = relX * screenX
absY = relY * screenY
end
--[[ elseif panelState == "informations" then
absX, absY = 0, 0
if isCursorShowing() then
local relX, relY = getCursorPosition()
absX = relX * screenX
absY = relY * screenY
end
-- ** Háttér
dxDrawRectangle(infoPosX, infoPosY, infoWidth, infoHeight, tocolor(0, 0, 0, 140))
-- ** Keret
dxDrawRectangle(infoPosX - bgMargin, infoPosY - bgMargin, infoWidth + (bgMargin * 2), bgMargin, tocolor(0, 0, 0, 200)) -- felső
dxDrawRectangle(infoPosX - bgMargin, infoPosY + infoHeight, infoWidth + (bgMargin * 2), bgMargin, tocolor(0, 0, 0, 200)) -- alsó
dxDrawRectangle(infoPosX - bgMargin, infoPosY, bgMargin, infoHeight, tocolor(0, 0, 0, 200)) -- bal
dxDrawRectangle(infoPosX + infoWidth, infoPosY, bgMargin, infoHeight, tocolor(0, 0, 0, 200)) -- jobb
local entrarcor = tocolor(0, 0, 0, 140)
if absX >= infoPosX + 10 and absX <= infoPosX + 10 + infoWidth - 20 and absY >= infoPosY + infoHeight - 40 and absY <= infoPosY + infoHeight - 10 then
entrarcor = tocolor(171, 211, 115, 140)
end
dxDrawRectangle(infoPosX + 280, infoPosY + infoHeight - 300, infoWidth - 300, 40, entrarcor)
local vendercomprarcor = tocolor(0, 0, 0, 140)
if absX >= infoPosX + 10 and absX <= infoPosX + 10 + infoWidth - 20 and absY >= infoPosY + infoHeight - 40 and absY <= infoPosY + infoHeight - 10 then
vendercomprarcor = tocolor(171, 211, 115, 140)
end
dxDrawRectangle(infoPosX + 280, infoPosY + infoHeight - 250, infoWidth - 300, 40, vendercomprarcor)
local empresacor = tocolor(0, 0, 0, 140)
if absX >= infoPosX + 10 and absX <= infoPosX + 10 + infoWidth - 20 and absY >= infoPosY + infoHeight - 40 and absY <= infoPosY + infoHeight - 10 then
empresacor = tocolor(171, 211, 115, 140)
end
dxDrawRectangle(infoPosX + 280, infoPosY + infoHeight - 200, infoWidth - 300, 40, empresacor)
local fecharcor = tocolor(0, 0, 0, 140)
if absX >= infoPosX + 280 and absX <= infoPosX + 10 + infoWidth - 300 and absY >= infoPosY + infoHeight - 40 and absY <= infoPosY + infoHeight - 10 then
fecharcor = tocolor(171, 211, 115, 140)
end
dxDrawRectangle(infoPosX + 280, infoPosY + infoHeight - 150, infoWidth - 300, 40, fecharcor)
local fecharcor = tocolor(0, 0, 0, 140)
if absX >= infoPosX + 10 and absX <= infoPosX + 10 + infoWidth - 20 and absY >= infoPosY + infoHeight - 40 and absY <= infoPosY + infoHeight - 10 then
fecharcor = tocolor(171, 211, 115, 140)
end
dxDrawRectangle(infoPosX + 10, infoPosY + infoHeight - 40, infoWidth - 20, 30, fecharcor)
dxDrawText("Fechar", infoPosX + 10, infoPosY + infoHeight - 40, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Fechar", infoPosX + 10, infoPosY + infoHeight - 40, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
-- ** Estrutura
dxDrawText("#2F7CCCVDB #ffffffGaming - Minhas propriedades.", infoPosX - 300, infoPosY - 425, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("PROPRIEDADES DISPONÍVEIS (1/2)", infoPosX + 300, infoPosY - 360, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawRectangle(infoPosX + 10, infoPosY + 30, infoWidth - 350, (infoPosY + infoHeight - 50) - (infoPosY + 40), tocolor(0, 0, 0, 140))
dxDrawText("ID da propriedade 01", infoPosX - 330, infoPosY - 300, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Localização: Galton", infoPosX - 330, infoPosY - 250, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Dono: tiaguinhods", infoPosX - 330, infoPosY - 200, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Preço: 1.000,000", infoPosX - 330, infoPosY - 150, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Empresa: Não", infoPosX - 330, infoPosY - 100, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Lucro da Empresa: R$ 0,00", infoPosX - 330, infoPosY - 50, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Garagem: Sim", infoPosX - 330, infoPosY, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
dxDrawText("Carros na Garagem: (1/2)", infoPosX - 330, infoPosY + 50, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 10, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
-- ** Content
--dxDrawRectangle(infoPosX + 10, infoPosY + 140, infoWidth - 20, (infoPosY + infoHeight - 50) - (infoPosY + 140), tocolor(255, 255, 255, 40))
dxDrawText(infoText, infoPosX + 10, infoPosY + 140, infoPosX + 10 + infoWidth - 20, infoPosY + infoHeight - 50, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "center", false, false, true, true, true)
]]
elseif panelState == "shop" then
absX, absY = 0, 0
if isCursorShowing() then
local relX, relY = getCursorPosition()
absX = relX * screenX
absY = relY * screenY
end
-- ** Háttér
dxDrawRectangle(bgPosX, bgPosY, bgWidth, bgHeight, tocolor(0, 0, 0, 140))
-- ** Keret
dxDrawRectangle(bgPosX - bgMargin, bgPosY - bgMargin, bgWidth + (bgMargin * 2), bgMargin, tocolor(0, 0, 0, 200)) -- felső
dxDrawRectangle(bgPosX - bgMargin, bgPosY + bgHeight, bgWidth + (bgMargin * 2), bgMargin, tocolor(0, 0, 0, 200)) -- alsó
dxDrawRectangle(bgPosX - bgMargin, bgPosY, bgMargin, bgHeight, tocolor(0, 0, 0, 200)) -- bal
dxDrawRectangle(bgPosX + bgWidth, bgPosY, bgMargin, bgHeight, tocolor(0, 0, 0, 200)) -- jobb
-- ** Content
dxDrawText("#4aabd0" .. mainColumnTitle, mainColumnPosX + 5, mainColumnPosY - 28, 0, 0, tocolor(255, 255, 255, 255), 0.5, titleFont, "left", "top", false, false, true, true, true)
dxDrawRectangle(mainColumnPosX, mainColumnPosY, mainColumnWidth, mainColumnHeight, tocolor(0, 0, 0, 140))
dxDrawRectangle(mainColumnPosX + mainColumnWidth, mainColumnPosY, 30, mainColumnHeight, tocolor(0, 0, 0, 140))
dxDrawRectangle(mainColumnPosX + mainColumnWidth, mainColumnPosY, bgMargin, mainColumnHeight, tocolor(0, 0, 0, 200))
dxDrawRectangle(mainColumnPosX - bgMargin, mainColumnPosY - bgMargin, mainColumnWidth + 30 + (bgMargin * 2), bgMargin, tocolor(0, 0, 0, 200)) -- felső
dxDrawRectangle(mainColumnPosX - bgMargin, mainColumnPosY + mainColumnHeight, mainColumnWidth + 30 + (bgMargin * 2), bgMargin, tocolor(0, 0, 0, 200)) -- alsó
dxDrawRectangle(mainColumnPosX - bgMargin, mainColumnPosY, bgMargin, mainColumnHeight, tocolor(0, 0, 0, 200)) -- bal
dxDrawRectangle(mainColumnPosX + mainColumnWidth + 30, mainColumnPosY, bgMargin, mainColumnHeight, tocolor(0, 0, 0, 200)) -- jobb
if notificationTick >= getTickCount() then
dxDrawText(notificationText, exitButtonPosX, bgPosY + 10, exitButtonPosX + exitButtonWidth, 0, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "top", false, false, true, true, true)
end
if absX >= upsetaPosX and absX <= upsetaPosX + setaWidth and absY >= upsetaPosY and absY <= upsetaPosY + setaHeight then
dxDrawImage(upsetaPosX, upsetaPosY, setaWidth, setaHeight, "arquivos/setas/upsetaon.png")
else
dxDrawImage(upsetaPosX, upsetaPosY, setaWidth, setaHeight, "arquivos/setas/upsetaoff.png")
end
if absX >= downsetaPosX and absX <= downsetaPosX + setaWidth and absY >= downsetaPosY and absY <= downsetaPosY + setaHeight then
dxDrawImage(downsetaPosX, downsetaPosY, setaWidth, setaHeight, "arquivos/setas/downsetaon.png")
else
dxDrawImage(downsetaPosX, downsetaPosY, setaWidth, setaHeight, "arquivos/setas/downsetaoff.png")
end
-- ** Back
local backTextColor = tocolor(255, 255, 255, 255)
local backBoxColor = tocolor(0, 0, 0, 140)
if not selectedCategory then
backTextColor = tocolor(100, 100, 100, 100)
else
if absX >= mainColumnPosX - bgMargin and absX <= mainColumnPosX - bgMargin + mainColumnWidth + 30 + (bgMargin * 2) and absY >= mainColumnPosY + mainColumnHeight + 10 and absY <= mainColumnPosY + mainColumnHeight + 10 + columnHeight then
backBoxColor = tocolor(74, 171, 208, 140)
if getKeyState("mouse1") then
selectedItem = false
selectedCategory = false
visibleItem = 1
-- destroyGUI()
playSound(":VDBGPanelSound/fecha.mp3", false)
end
end
end
dxDrawRectangle(mainColumnPosX - bgMargin, mainColumnPosY + mainColumnHeight + 10, mainColumnWidth + 30 + (bgMargin * 2), columnHeight, backBoxColor)
dxDrawText("Voltar", mainColumnPosX - bgMargin, mainColumnPosY + mainColumnHeight + 10, mainColumnPosX - bgMargin + mainColumnWidth + 30 + (bgMargin * 2), mainColumnPosY + mainColumnHeight + 10 + columnHeight, backTextColor, 0.5, titleFont, "center", "center", false, false, true, true, true)
-- ** Buy
local buyTextColor = tocolor(255, 255, 255, 255)
local buyBoxColor = tocolor(0, 0, 0, 140)
if not selectedCategory then
buyTextColor = tocolor(100, 100, 100, 100)
else
if absX >= exitButtonPosX and absX <= exitButtonPosX + exitButtonWidth and absY >= exitButtonPosY - exitButtonHeight - 10 and absY <= exitButtonPosY - 10 then
buyBoxColor = tocolor(172, 211, 115, 140)
end
end
--dxDrawRectangle(exitButtonPosX, exitButtonPosY - exitButtonHeight - 10, exitButtonWidth, exitButtonHeight, buyBoxColor)
--dxDrawText("Vásárlás!", exitButtonPosX, exitButtonPosY - exitButtonHeight - 10, exitButtonPosX + exitButtonWidth, exitButtonPosY - exitButtonHeight - 10 + exitButtonHeight, buyTextColor, 0.5, titleFont, "center", "center", false, false, true, true, true)
-- ** Exit
local exitTextColor = tocolor(255, 255, 255, 255)
local exitBoxColor = tocolor(0, 0, 0, 140)
if absX >= exitButtonPosX and absX <= exitButtonPosX + exitButtonWidth and absY >= exitButtonPosY and absY <= exitButtonPosY + exitButtonHeight then
exitBoxColor = tocolor(220, 20, 60, 140)
if getKeyState("mouse1") then
--executeCommandHandler("diamondshop")
panelState = false
showCursor(false)
showChat(true)
setElementData(localPlayer, "opendashboard", false)
playSound(":VDBGPDU/arquivos/fechar.mp3")
end
end
dxDrawRectangle(exitButtonPosX, exitButtonPosY, exitButtonWidth, exitButtonHeight, exitBoxColor)
dxDrawText("Sair", exitButtonPosX, exitButtonPosY, exitButtonPosX + exitButtonWidth, exitButtonPosY + exitButtonHeight, exitTextColor, 0.5, titleFont, "center", "center", false, false, true, true, true)
local loopTable = {}
if not selectedCategory then
loopTable = availableCategories
else
if availableCategories[selectedCategory] then
loopTable = availableCategories[selectedCategory]["subCategories"]
end
end
local categoryCount = 0
for k,v in ipairs(loopTable) do
if k >= visibleItem and k <= visibleItem + 15 then
if categoryCount % 2 ~= 0 then
dxDrawRectangle(mainColumnPosX, mainColumnPosY + (categoryCount * columnHeight), mainColumnWidth, columnHeight, tocolor(255, 255, 255, 40))
end
if absX >= mainColumnPosX and absX <= mainColumnPosX + mainColumnWidth and absY >= mainColumnPosY + (categoryCount * columnHeight) and absY <= mainColumnPosY + (categoryCount * columnHeight) + columnHeight then
dxDrawRectangle(mainColumnPosX, mainColumnPosY + (categoryCount * columnHeight), mainColumnWidth, columnHeight, tocolor(35, 158, 240, 140))
if not selectedCategory then
if getKeyState("mouse1") then
selectedCategory = k
visibleItem = 1
playSound(":VDBGPanelSound/navegacao.mp3", false)
if selectedCategory == 1 or selectedCategory == 2 or selectedCategory == 4 or selectedCategory == 5 then
createGUI()
end
end
else
if selectedItem ~= k then
if getKeyState("mouse1") then
selectedItem = k
playSound(":VDBGPanelSound/navegacao.mp3", false)
end
end
end
end
dxDrawText(v["name"], mainColumnPosX, mainColumnPosY + (categoryCount * columnHeight), mainColumnPosX + mainColumnWidth, mainColumnPosY + (categoryCount * columnHeight) + columnHeight, tocolor(255, 255, 255, 255), 0.5, itemFont, "center", "center", false, false, true, true, true)
categoryCount = categoryCount + 1
end
end
if selectedCategory then
if availableCategories[selectedCategory] then
if selectedItem then
if availableCategories[selectedCategory]["subCategories"][selectedItem] then
if availableCategories[selectedCategory]["subCategories"][selectedItem]["imagePath"] then
dxDrawImage(exitButtonPosX, mainColumnPosY, exitButtonWidth, 160, availableCategories[selectedCategory]["subCategories"][selectedItem]["imagePath"] )
elseif availableCategories[selectedCategory]["imagePath"] then
dxDrawImage(exitButtonPosX, mainColumnPosY, exitButtonWidth, 160, availableCategories[selectedCategory]["imagePath"])
end
dxDrawText("#3B95DA" .. availableCategories[selectedCategory]["subCategories"][selectedItem]["name"], exitButtonPosX, mainColumnPosY + 170, exitButtonPosX + 10 + exitButtonWidth, 0, tocolor(255, 255, 255, 255), 0.5, titleFont, "center", "top", false, false, true, true, true)
if selectedCategory == 6 then
-- dxDrawText("Ár: #acd373" .. availableCategories[selectedCategory]["subCategories"][selectedItem]["amount"] .. " ArtPont #FFFFFF| #4aabd0(1 ArtPont = $" .. math.floor(availableCategories[selectedCategory]["subCategories"][selectedItem]["amount"] / availableCategories[selectedCategory]["subCategories"][selectedItem]["amount"]) .. ")", exitButtonPosX, mainColumnPosY + 190, exitButtonPosX + 10 + exitButtonWidth, 0, tocolor(255, 255, 255, 255), 0.5, titleFont, "left", "top", false, false, true, true, true)
else
--dxDrawText("Ár: #acd373" .. availableCategories[selectedCategory]["subCategories"][selectedItem]["amount"] .. " ArtPont", exitButtonPosX, mainColumnPosY + 190, exitButtonPosX + 10 + exitButtonWidth, 0, tocolor(255, 255, 255, 255), 0.5, titleFont, "left", "top", false, false, true, true, true)
end
if availableCategories[selectedCategory]["subCategories"][selectedItem]["description"] then -- járművek
dxDrawText(availableCategories[selectedCategory]["subCategories"][selectedItem]["description"], exitButtonPosX, mainColumnPosY + 210, exitButtonPosX + 10 + exitButtonWidth, 0, tocolor(255, 255, 255, 255), 0.45, titleFont, "center", "top", false, false, true, true, true)
end
end
end
end
end
end
end
)
function createNotification(text)
notificationText = text
notificationTick = getTickCount() + 5000
end
|
util.AddNetworkString( "player_in_spawn" )
local meta = FindMetaTable("Entity")
--Initilization of box areas
local sBoxes = {
[1] = {
Vector(-5743.565430, -8658.199219, 1153.013184), --Start of box 1, type getpos to get these vectors to start the box. (Recommended you set this first below the map)
Vector(-8241.015625, -10732.653320, -156.267517), --End of box 1, type getpos to get the closing area of the box. To work the vector must be set higher (in the map)
}
}
--Check to see if player is in spawn
function meta:IsInSpawn()
for _,boxes in pairs(sBoxes) do
for _,ent in pairs(ents.FindInBox(boxes[1], boxes[2])) do
if IsValid(ent) and ent == self then
return true
end
end
end
return false
end
--Sets players weapon to the one specified specified
function meta:SetWeapon(wep_name)
for _,v in pairs(self:GetWeapons()) do
if v:GetClass() == wep_name then
self:SetActiveWeapon(v)
end
end
end
--main timer loop to perform checks on players
timer.Create("SpawnCheck", 0, 0, function()
for _,v in pairs(player.GetAll()) do
if IsValid(v) then
net.Start("player_in_spawn")
net.WriteEntity(v)
if v:IsInSpawn() then
net.WriteBool(true)
net.Send(v)
v:SetWeapon("weapon_physgun")
else
net.WriteBool(false)
net.Send(v)
end
end
end
for _,v in pairs(ents.FindByClass("prop_physics")) do
if IsValid(v) and v:IsInSpawn() then
v:Remove()
end
end
end)
-- This grants god mode while in spawn.
hook.Add("EntityTakeDamage", "SpawnProt", function(target, dmginfo)
if target:IsPlayer() and target:IsInSpawn() then
dmginfo:ScaleDamage(0)
end
return dmginfo
end)
|
return {'ton','tonaal','tonaliteit','tonbrug','tondel','tondeldoos','tonder','tondeuse','toneel','toneelaanwijzing','toneelacademie','toneelachtig','toneelauteur','toneelavond','toneelbeeld','toneelbenodigdheden','toneelbestel','toneelbewerking','toneelcarriere','toneelclub','toneelcriticus','toneeldebuut','toneeldecor','toneeldichter','toneeleffect','toneelervaring','toneelgezelschap','toneelgroep','toneelheld','toneelhuis','toneelkapper','toneelkennis','toneelkijker','toneelknecht','toneelkostuum','toneelkring','toneelkritiek','toneelkunst','toneelkunstenaar','toneellaars','toneelleider','toneellicht','toneelliefhebber','toneelliefhebster','toneelliteratuur','toneelloopbaan','toneelmaker','toneelmatig','toneelmeester','toneelmonoloog','toneelmuziek','toneelopleiding','toneelopvoering','toneelpraktijk','toneelprijs','toneelproductie','toneelrecensent','toneelregie','toneelregisseur','toneelrepetitie','toneelrol','toneelruimte','toneelscherm','toneelschikking','toneelschool','toneelschrijfster','toneelschrijver','toneelscript','toneelscene','toneelseizoen','toneelspeelster','toneelspel','toneelspelen','toneelspeler','toneelstuk','toneeltaal','toneeltekst','toneeltje','toneeltoren','toneeluitvoering','toneelverbond','toneelvereniging','toneelversie','toneelvertoning','toneelvoorstelling','toneelwereld','toneelwerk','toneelwerkgroep','toneelzaal','tonelist','tonen','toner','tong','tongbeen','tongbeslag','tongblaar','tongbreker','tongen','tongenworst','tongetje','tongewelf','tongfilet','tongkijker','tongkus','tongpiercing','tongpunt','tongriem','tongschar','tongschraper','tongstrelend','tongval','tongvormig','tongwerk','tongwortel','tongzoen','tongzoenen','tonic','tonica','tonicum','tonijn','tonijnsalade','tonijnvangst','tonijnvisser','tonijnvisserij','tonisch','tonkaboom','tonkaboon','tonkilometer','tonkinstok','tonmolen','tonnage','tonnagegrondslag','tonneau','tonnen','tonnenmaat','tonnenstelsel','tonner','tonnetje','tonrond','tonrondte','tonsil','tonsillectomie','tonsillitis','tonster','tonsuur','tontine','tonus','toneeltraditie','toneelschrijfkunst','toneelgeschiedenis','toneelschoolleerling','toneeloeuvre','toneelfiguur','toneelmuseum','toneelspelersgezelschap','toneelduivel','toneelles','toneelleven','toneelopening','toneelpodium','toneelvloer','toneelvorm','tongbasis','tongbeet','toneelactrice','ton','tonga','tongaan','tongaans','tongenaar','tongeraar','tongeren','tongerlo','tongers','tonia','tonkin','tonnie','tony','tonningen','toni','tonnis','tonny','tonnaer','tonino','tonkens','tonkes','tonies','tonnard','tonk','tonale','tonde','tondeldozen','tonden','tondeuses','toneelaanwijzingen','toneelachtige','toneelacteurs','toneelcritici','toneeldichters','toneeleffecten','toneelgezelschappen','toneelhelden','toneelkijkers','toneelkringen','toneelkunstenaars','toneellaarzen','toneellessen','toneelmatige','toneelmatiger','toneelmeesters','toneelopvoeringen','toneelproducties','toneelrollen','toneelschermen','toneelscholen','toneelschrijvers','toneelspeelsters','toneelspelers','toneelstukje','toneelstukjes','toneelstukken','toneeltjes','toneelverbonden','toneelverenigingen','toneelvertoningen','toneelvoorstellingen','toneelwerken','toneelzalen','tonelen','tonelisten','tonend','tongetjes','tongewelven','tongpunten','tongpuntje','tongriemen','tongscharren','tongschrapers','tongvallen','tongvormige','tongwerken','tongzoende','tongzoenden','tongzoenend','tongzoenende','tongzoent','tonicums','tonijnen','tonijntje','tonijntjes','tonische','tonkabonen','tonkilometers','tonkinstokken','tonmolens','tonnages','tonneaus','tonners','tonnetjes','tonronde','tonsillen','tonsters','tonsuren','tont','tontines','toneelavonden','toneelbewerkingen','toneelclubs','toneeldecors','toneelgespeeld','toneelgroepen','toneelknechten','toneelknechts','toneelkostuums','toneelkritieken','toneelliefhebbers','toneelmakers','toneelprijzen','toneelrecensenten','toneelregisseurs','toneelrepetities','toneeluitvoeringen','tonende','tongbeenderen','tongbenen','tongbrekers','tongde','tongfilets','tongkijkers','tongkussen','tongwortels','tonijnvissers','toneelscenes','tongstrelende','tongaanse','tonics','toneelschoolleerlingen','toneelseizoenen','tongerse','tons','tonis','tonias','tonnies','tonnis','tonnys','tonys','toneelteksten','tongriempje','toneelvormen','toneelauteurs','toneelopleidingen','toneelbeelden','toneelzaaltje','toneelspelertjes','toneelspelletje','toneelleiders','toneelgebeuren','tongpiercings','toneelclubje','toneelervaringen','toneelgroepje','toneelgroepjes','toneelkijkertjes','toneelversies','tongerense'}
|
local typedefs = require "kong.db.schema.typedefs"
return {
name = "mtls_certs_manager",
fields = {
{ consumer = typedefs.no_consumer },
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{ plugin_endpoint_usage = { type = "string", default = "register_instance", one_of = { "register_instance", "renew_instance" } } },
{ ca_private_key_path = { type = "string", default = "/usr/local/custom/kong/plugins/mtls_certs_manager/example_certs/CA-key.pem" }, },
{ ca_private_key_passphrase = { type = "string", default = "1234" }, },
{ ca_certificate_path = { type = "string", default = "/usr/local/custom/kong/plugins/mtls_certs_manager/example_certs/CA-cert.pem" }, },
{ common_name_regex = { type = "string", default = "CN=(.*)/O=" }, },
{ days_of_validity = { type = "integer", default = 60 }, }
},
},
},
}
}
|
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/GameObject/UM02_Droids_Spawn.lua#2 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/GameObject/UM02_Droids_Spawn.lua $
--
-- Original Author: Jeff_Stewart
--
-- $Author: Jeff_Stewart $
--
-- $Change: 46698 $
--
-- $DateTime: 2006/06/21 14:21:37 $
--
-- $Revision: #2 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("PGStateMachine")
require("PGSpawnUnits")
require("JGS_FunctionLib") -- added library of commonly used functions
function Definitions()
-- Object isn't valid at this point so don't do any operations that
-- would require it. State_Init is the first chance you have to do
-- operations on Object
DebugMessage("%s -- In Definitions", tostring(Script))
Define_State("State_Init", State_Init);
end
function State_Init(message)
if message == OnEnter then
-- Register a prox event that looks for any nearby units
empire_player = Find_Player("Empire")
underworld_player = Find_Player("Underworld")
random_var = GameRandom(2,10)
Register_Timer(Respawn, random_var)
last_droid = nil
elseif message == OnUpdate then
--Do Nothing
elseif message == OnExit then
--Do Nothing
end
end
function Respawn()
-- respawns destroyer droids from the production lines until deleted by script
if not TestValid(last_droid) then
unit_list = Find_All_Objects_Of_Type("Destroyer_Droid")
if table.getn(unit_list) < 20 then
Object.Play_SFX_Event("Unit_AT_AT_Rope_Drop")
last_droid = Create_Generic_Object("Destroyer_Droid",Object.Get_Position(),underworld_player)
Register_Timer(Respawn, 60)
else
Register_Timer(Respawn, 10)
end
else
Register_Timer(Respawn, 10)
end
end
|
local ut = require "lluv.utils"
local log = require "spylog.log"
local EventLog = require "spylog.eventlog"
local trap = require "spylog.monitor.trap"
local function trap_monitor(endpoint, opt, cb, log_header)
local proto, address, port = ut.split_first(endpoint, "://", true)
assert(proto == 'udp')
address, port = ut.split_first(address,":", true)
port = tonumber(port) or 162
endpoint = string.format('%s://%s:%d', proto, address, port)
local log_header = log_header or string.format('[eventlog/%s] [%s:%d]', proto, address, port)
return trap.monitor(endpoint, opt, cb, log_header)
end
local function trap_filter(filter, t)
local msg = filter.events(t) and EventLog.trap2text(t)
if type(msg) == 'string' then
return filter.match(msg)
end
end
return {
monitor = trap_monitor;
filter = trap_filter;
}
|
--[[ =================================================================
Description:
Event detail info. Data available in English only.
Data within this file has been collected from wowwiki.com
================================================================= --]]
ET_Static = {
["ACHIEVEMENT_EARNED"] = {"Achievement ID"},
["ACTIONBAR_HIDEGRID"] = {"Mouse button","True or False"},
["ACTIONBAR_PAGE_CHANGED"] = {"Mouse button","True or False"},
["ACTIONBAR_SLOT_CHANGED"] = {"Slot number","True or False"},
["ACTIONBAR_UPDATE_COOLDOWN"] = {"Mouse button"},
["ACTIONBAR_UPDATE_STATE"] = {"Mouse button"},
["ADDON_ACTION_FORBIDDEN"] = {"AddOn (or function) name","Function name"},
["ADDON_LOADED"] = {"AddOn name"},
["ARENA_OPPONENT_UPDATE"] = {"Arena unit ID","State"},
["AUTOFOLLOW_BEGIN"] = {"Unit following"},
["BAG_CLOSED"] = {"Container ID"},
["BAG_OPEN"] = {"Container ID"},
["BAG_UPDATE"] = {"Container ID"},
["BAG_UPDATE_COOLDOWN"] = {"Container ID"},
["CALENDAR_ACTION_PENDING"] = {"Busy flag"},
["CALENDAR_EVENT_ALARM"] = {"Title","Hour","Minute"},
["CALENDAR_NEW_EVENT"] = {"Is copy"},
["CALENDAR_OPEN_EVENT"] = {"Calender type"},
["CALENDAR_UPDATE_ERROR"] = {"Message"},
["CANCEL_LOOT_ROLL"] = {"Roll ID"},
["CHANNEL_COUNT_UPDATE"] = {"Channel ID","Number of players"},
["CHANNEL_FLAGS_UPDATED"] = {"Channel ID"},
["CHANNEL_PASSWORD_REQUEST"] = {"Channel name"},
["CHANNEL_ROSTER_UPDATE"] = {"Channel ID","Number of players"},
["CHANNEL_VOICE_UPDATE"] = {"Unknown","Unknown","Unknown"},
["CHARACTER_POINTS_CHANGED"] = {"Talent points changed"},
["CHAT_MSG_ACHIEVEMENT"] = {"Message","Player",3,4,"Player",6,"Unknown","Unknown"},
["CHAT_MSG_ADDON"] = {"Prefix","Message","Distribution type","Sender"},
["CHAT_MSG_AFK"] = {"AFK message","Sender"},
["CHAT_MSG_BATTLEGROUND"] = {"Message","Sender","Language"},
["CHAT_MSG_BATTLEGROUND_LEADER"] = {"Message","Sender","Language"},
["CHAT_MSG_BG_SYSTEM_ALLIANCE"] = {"Message"},
["CHAT_MSG_BG_SYSTEM_HORDE"] = {"Message"},
["CHAT_MSG_BG_SYSTEM_NEUTRAL"] = {"Message"},
["CHAT_MSG_CHANNEL"] = {"Message","Sender","Language","Channel name (with number)","Target","AFK/DND/GM","Zone ID","Channel number","Channel name"},
["CHAT_MSG_CHANNEL_JOIN"] = {1,"Player",3,"Channel name (with number)",5,6,7,"Channel number","Channel name"},
["CHAT_MSG_CHANNEL_LEAVE"] = {1,"Player",3,"Channel name (with number)",5,6,7,"Channel number","Channel name"},
["CHAT_MSG_CHANNEL_LIST"] = {"Channels",2,3,"Channel name (with number)"},
["CHAT_MSG_CHANNEL_NOTICE"] = {"Type",2,3,"Channel name (with number)",5,6,"Channel type","Channel number","Channel name"},
["CHAT_MSG_CHANNEL_NOTICE_USER"] = {"Type","Target",3,"Channel name (with number)","Player"},
["CHAT_MSG_COMBAT_CREATURE_VS_CREATURE_HITS"] = {"Message"},
["CHAT_MSG_COMBAT_CREATURE_VS_CREATURE_MISSES"] = {"Message"},
["CHAT_MSG_COMBAT_CREATURE_VS_PARTY_HITS"] = {"Message"},
["CHAT_MSG_COMBAT_CREATURE_VS_PARTY_MISSES"] = {"Message"},
["CHAT_MSG_COMBAT_CREATURE_VS_SELF_HITS"] = {"Message"},
["CHAT_MSG_COMBAT_CREATURE_VS_SELF_MISSES"] = {"Message"},
["CHAT_MSG_COMBAT_FACTION_CHANGE"] = {"Message"},
["CHAT_MSG_COMBAT_FRIENDLY_DEATH"] = {"Message"},
["CHAT_MSG_COMBAT_HONOR_GAIN"] = {"Message"},
["CHAT_MSG_COMBAT_HOSTILE_DEATH"] = {"Message"},
["CHAT_MSG_COMBAT_SELF_HITS"] = {"Message"},
["CHAT_MSG_COMBAT_SELF_MISSES"] = {"Message"},
["CHAT_MSG_COMBAT_XP_GAIN"] = {"Message"},
["CHAT_MSG_DND"] = {"DND message","Sender"},
["CHAT_MSG_EMOTE"] = {"Message","Sender"},
["CHAT_MSG_GUILD"] = {"Message","Sender","Language"},
["CHAT_MSG_GUILD_ACHIEVEMENT"] = {"Message","Player name",3,4,"Player name",6,7,8,9,10,11},
["CHAT_MSG_IGNORED"] = {"Target","Target"},
["CHAT_MSG_LOOT"] = {"Message"},
["CHAT_MSG_MONEY"] = {"Message"},
["CHAT_MSG_MONSTER_EMOTE"] = {"Message","Monster name"},
["CHAT_MSG_MONSTER_SAY"] = {"Message","Sender","Language"},
["CHAT_MSG_MONSTER_YELL"] = {"Message","Sender"},
["CHAT_MSG_OFFICER"] = {"Message","Sender","Language"},
["CHAT_MSG_PARTY"] = {"Message","Sender","Language"},
["CHAT_MSG_PET_INFO"] = {"Message"},
["CHAT_MSG_RAID"] = {"Message","Sender","Language"},
["CHAT_MSG_RAID_BOSS_EMOTE"] = {"Message","Boss name"},
["CHAT_MSG_RAID_LEADER"] = {"Message","Sender","Language"},
["CHAT_MSG_RAID_WARNING"] = {"Message","Sender","Language"},
["CHAT_MSG_SAY"] = {"Message","Sender","Language"},
["CHAT_MSG_SKILL"] = {"Message"},
["CHAT_MSG_SPELL_CREATURE_VS_SELF_DAMAGE"] = {"Full combat text"},
["CHAT_MSG_SPELL_FRIENDLYPLAYER_BUFF"] = {"Full combat text"},
["CHAT_MSG_SPELL_HOSTILEPLAYER_BUFF"] = {"Full combat text"},
["CHAT_MSG_SPELL_PERIODIC_FRIENDLYPLAYER_BUFFS"] = {"Full combat text"},
["CHAT_MSG_SPELL_PERIODIC_HOSTILEPLAYER_DAMAGE"] = {"Full combat text"},
["CHAT_MSG_SPELL_PERIODIC_SELF_BUFFS"] = {"Full combat text"},
["CHAT_MSG_SPELL_PERIODIC_SELF_DAMAGE"] = {"Debuff message"},
["CHAT_MSG_SYSTEM"] = {"Message",2,3,4,5,6,7,8,9,10,11},
["CHAT_MSG_TEXT_EMOTE"] = {"Message","Sender"},
["CHAT_MSG_TRADESKILLS"] = {"Message"},
["CHAT_MSG_WHISPER"] = {"Message","Sender","Language",4,5,"Status","Message ID",8},
["CHAT_MSG_WHISPER_INFORM"] = {"Message","Sender","Language"},
["CHAT_MSG_YELL"] = {"Message","Sender","Language"},
["CLOSE_INBOX_ITEM"] = {"Mailbox slot"},
["COMBAT_LOG_EVENT"] = {"Timestamp","Event","Source GUID","Source name","Source flags","Destination GUID","Destination name","Destination flags","Arg 9","Arg 10","Arg 11","Arg 12","Arg 13","Arg 14","Arg 15","Arg 16","Arg 17"},
["COMBAT_LOG_EVENT_UNFILTERED"] = {"Timestamp","Event","Source GUID","Source name","Source flags","Destination GUID","Destination name","Destination flags","Arg 9","Arg 10","Arg 11","Arg 12","Arg 13","Arg 14","Arg 15","Arg 16","Arg 17"},
["COMBAT_TEXT_UPDATE"] = {"Type","Arg 2 (depends on Type)","Arg 3 (depends on Type)"},
["COMPANION_UPDATE"] = {"Companion type"},
["COMSAT_START"] = {"Unit ID"},
["CRAFT_CLOSE"] = {"Mouse button"},
["CRAFT_SHOW"] = {"Mouse button"},
["CVAR_UPDATE"] = {"CVAR name","Value"},
["DELETE_ITEM_CONFIRM"] = {"Item name"},
["DUEL_REQUESTED"] = {"Opponent name"},
["EXECUTE_CHAT_LINE"] = {"Chat line"},
["GOSSIP_CLOSED"] = {"Mouse button"},
["GUILD_INVITE_REQUEST"] = {"Guild inviter","Guild name"},
["GUILD_MOTD"] = {"Message of the day"},
["GUILD_ROSTER_UPDATE"] = {"Updated by"},
["ITEM_LOCKED"] = {"Bag/Equipment slot","Slot"},
["ITEM_LOCK_CHANGED"] = {"Bag/Equipment slot","Slot"},
["ITEM_PUSH"] = {"Bag","Icon path"},
["ITEM_UNLOCKED"] = {"Bag/Equipment slot","Slot"},
["LEARNED_SPELL_IN_TAB"] = {"Tab number"},
["LOOT_OPENED"] = {"Auto looting"},
["LOOT_SLOT_CLEARED"] = {"Slot number"},
["MACRO_ACTION_FORBIDDEN"] = {"???"},
["MAIL_INBOX_UPDATE"] = {"Mouse button","???"},
["MAIL_SHOW"] = {"???"},
["MEMORY_EXHAUSTED"] = {"Memory limit (MB)"},
["MERCHANT_CLOSED"] = {"Mouse button"},
["MINIMAP_PING"] = {"Unit ID","X-coord","Y-coord"},
["MINIMAP_UPDATE_TRACKING"] = {"Mouse button"},
["MIRROR_TIMER_PAUSE"] = {"Duration"},
["MIRROR_TIMER_START"] = {"Timer","Value","Max value","Scale","Paused","Label"},
["MIRROR_TIMER_STOP"] = {"Timer"},
["MODIFIER_STATE_CHANGED"] = {"Modifier","State"},
["PARTY_INVITE_REQUEST"] = {"Team leader name"},
["PARTY_MEMBER_DISABLE"] = {"Player name"},
["PARTY_MEMBER_ENABLE"] = {"Player name"},
["PET_BAR_SHOWGRID"] = {"Mouse button"},
["PLAYERBANKSLOTS_CHANGED"] = {"Slot/Bag index"},
["PLAYER_COMBO_POINTS"] = {"Unit ID"},
["PLAYER_DAMAGE_DONE_MODS"] = {"Unit ID"},
["PLAYER_EQUIPMENT_CHANGED"] = {"Bag/Equipment slot","Slot"},
["PLAYER_FLAGS_CHANGED"] = {"Unit ID"},
["PLAYER_GAINS_VEHICLE_DATA"] = {"Unit ID"},
["PLAYER_GUILD_UPDATE"] = {"Unit ID"},
["PLAYER_LEVEL_UP"] = {"New level","Hit points","Mana points","Talent points","Strength","Agility","Stamina","Intellect","Spirit"},
["PLAYER_TARGET_CHANGED"] = {"Targetted by"},
["PLAYER_XP_UPDATE"] = {"Unit ID"},
["QUEST_ACCEPT_CONFIRM"] = {"Player name","Quest title"},
["QUEST_FINISHED"] = {"Mouse button"},
["QUEST_WATCH_UPDATE"] = {"Quest index"},
["RAID_INSTANCE_WELCOME"] = {"Instance name","Seconds till reset"},
["READY_CHECK"] = {"Player name","Time till autocomplete (sec)"},
["READY_CHECK_CONFIRM"] = {"Unit ID","Status"},
["REPLACE_ENCHANT"] = {"New enchantment","Current enchantment"},
["RESURRECT_REQUEST"] = {"Player name"},
["RUNE_POWER_UPDATE"] = {"Rune","Usable"},
["RUNE_TYPE_UPDATE"] = {"Rune"},
["SKILL_LINES_CHANGED"] = {"???"},
["SPELLCAST_CHANNEL_START"] = {"Duration (ms)","Spell name"},
["SPELLCAST_CHANNEL_UPDATE"] = {"Duration (ms)"},
["SPELLCAST_DELAYED"] = {"Disruption time"},
["SPELLCAST_START"] = {"Spell name","Duration (ms)"},
["SPELL_UPDATE_COOLDOWN"] = {"Triggered by"},
["START_LOOT_ROLL"] = {"Roll ID","Roll time"},
["SYSMSG"] = {"Message","Red","Green","Blue"},
["TIME_PLAYED_MSG"] = {"Total time played","Time at this level"},
["TOOLTIP_ADD_MONEY"] = {"Tooltip name","Amount"},
["TRACKED_ACHIEVEMENT_UPDATE"] = {"Achievement ID"},
["TRADE_ACCEPT_UPDATE"] = {"Player agreed","Target agreed"},
["TRADE_PLAYER_ITEM_CHANGED"] = {"Trade slot"},
["TRADE_REPLACE_ENCHANT"] = {"New enchantment","Current enchantment"},
["TRADE_REQUEST"] = {"Player name"},
["TRADE_TARGET_ITEM_CHANGED"] = {"Trade slot"},
["UI_ERROR_MESSAGE"] = {"Message"},
["UI_INFO_MESSAGE"] = {"Message"},
["UNIT_ATTACK"] = {"Unit ID"},
["UNIT_ATTACK_POWER"] = {"Unit ID"},
["UNIT_ATTACK_SPEED"] = {"Unit ID"},
["UNIT_AURA"] = {"Unit ID"},
["UNIT_CLASSIFICATION_CHANGED"] = {"Unit ID"},
["UNIT_COMBAT"] = {"Unit ID","Action","Indicator","Damage done","Damage type"},
["UNIT_COMBO_POINTS"] = {"Unit ID"},
["UNIT_DAMAGE"] = {"Unit ID"},
["UNIT_DEFENSE"] = {"Unit ID"},
["UNIT_DISPLAYPOWER"] = {"Unit ID"},
["UNIT_DYNAMIC_FLAGS"] = {"Unit ID"},
["UNIT_ENERGY"] = {"Unit name"},
["UNIT_FACTION"] = {"Unit name"},
["UNIT_FLAGS"] = {"Unit ID"},
["UNIT_HEALTH"] = {"Unit ID"},
["UNIT_INVENTORY_CHANGED"] = {"Unit ID"},
["UNIT_LEVEL"] = {"Unit ID"},
["UNIT_MANA"] = {"Unit ID"},
["UNIT_MAXENERGY"] = {"Unit ID (??)"},
["UNIT_MAXHEALTH"] = {"Unit ID"},
["UNIT_MAXMANA"] = {"Unit ID (??)"},
["UNIT_MAXRAGE"] = {"Unit ID (??)"},
["UNIT_MAXRUNIC_POWER"] = {"Unit ID (??)"},
["UNIT_MODEL_CHANGED"] = {"Unit ID"},
["UNIT_NAME_UPDATE"] = {"Unit ID"},
["UNIT_PET"] = {"Unit ID"},
["UNIT_PET_EXPERIENCE"] = {"Unit ID"},
["UNIT_PORTRAIT_UPDATE"] = {"Unit name"},
["UNIT_PVP_UPDATE"] = {"Unit"},
["UNIT_QUEST_LOG_CHANGED"] = {"Unit name"},
["UNIT_RAGE"] = {"Unit name"},
["UNIT_RANGED_ATTACK_POWER"] = {"Unit ID"},
["UNIT_RESISTANCES"] = {"Unit ID"},
["UNIT_RUNIC_POWER"] = {"unit ID"},
["UNIT_SPELLCAST_CHANNEL_START"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_CHANNEL_STOP"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_CHANNEL_UPDATE"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_DELAYED"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_FAILED"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_FAILED_QUIET"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_INTERRUPTED"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_SENT"] = {"Unit ID","Spell name","Spell rank","Target"},
["UNIT_SPELLCAST_START"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_STOP"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLCAST_SUCCEEDED"] = {"Unit ID","Spell name","Spell rank"},
["UNIT_SPELLMISS"] = {"Unit name","Action"},
["UNIT_STATS"] = {"Unit name"},
["UNIT_TARGET"] = {"Unit ID"},
["UNIT_THREAT_LIST_UPDATE"] = {"Unit ID"},
["UNIT_THREAT_SITUATION_UPDATE"] = {"Unit ID"},
["UPDATE_CHAT_COLOR"] = {"Chat type","Red","Green","Blue"},
["UPDATE_EXHAUSTION"] = {"Unit ID"},
["UPDATE_FACTION"] = {"Unit ID"},
["VEHICLE_ANGLE_UPDATE"] = {"Pitch"},
["VOICE_START"] = {"Unit ID"},
["QUEST_AUTOCOMPLETE"] = {"Quest ID"},
["GARRISON_MISSION_FINISHED"] = {"Mission ID"},
["GARRISON_MISSION_BONUS_ROLL_COMPLETE"] = {"Mission ID","State"},
["GARRISON_MISSION_BONUS_ROLL_LOOT"] = {"Item ID"},
["GARRISON_MISSION_COMPLETE_RESPONSE"] = {"Mission ID","???","???"},
["GARRISON_MISSION_STARTED"] = {"Mission ID"},
};
|
local label_demo = {}
function label_demo.demo()
local label1 = lvgl.label_create(lvgl.scr_act(), nil);
lvgl.label_set_long_mode(label1, lvgl.LABEL_LONG_BREAK); --Break the long lines
lvgl.label_set_recolor(label1, true); --Enable re-coloring by commands in the text
lvgl.label_set_align(label1, lvgl.LABEL_ALIGN_CENTER); --Center aligned lines
lvgl.label_set_text(label1, "#0000ff Re-color# #ff00ff words# #ff0000 of a# label and wrap long text automatically.");
lvgl.obj_set_width(label1, 150);
lvgl.obj_align(label1, nil, lvgl.ALIGN_CENTER, 0, -30);
local label2 = lvgl.label_create(lvgl.scr_act(), nil);
lvgl.label_set_long_mode(label2, lvgl.LABEL_LONG_SROLL_CIRC); --Circular scroll
lvgl.obj_set_width(label2, 150);
lvgl.label_set_text(label2, "It is a circularly scrolling text. ");
lvgl.obj_align(label2, nil, lvgl.ALIGN_CENTER, 0, 30);
end
return label_demo
|
--
-- Test cases
local runtime = {
'continue',
'observing',
'binding',
'set-get',
'visits',
'tags',
'jumping',
'save-load'
}
local units = {
'inclusions',
'comments',
'knots',
'stitches',
'text-line',
'text-lines',
'text-tags',
'text-glue',
'choices-basic',
'choices-tags',
'choices-conditional',
'choices-sticky',
'choices-fallback',
'labels-choices',
'labels-nested',
'branching',
'nesting',
'loop',
'vars',
'constants',
'expressions',
'queries',
'conditions-inline',
'alts-inline',
'conditions-switch',
'alts-blocks',
'lists-basic',
'lists-operators',
'lists-queries',
}
local stories = {
-- No complex stories at the moment
}
local cases = {
runtime = runtime,
units = units,
stories = stories
}
local folderSeparator = package.config:sub(1, 1)
for folderName, folderCases in pairs(cases) do
local itemsWithFoldes = { }
for _, case in ipairs(folderCases) do
table.insert(itemsWithFoldes, folderName .. folderSeparator .. case)
end
cases[folderName] = itemsWithFoldes
end
return cases
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_underlord_atrophy_aura_lua_stack = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_underlord_atrophy_aura_lua_stack:IsHidden()
return true
end
function modifier_underlord_atrophy_aura_lua_stack:IsDebuff()
return false
end
function modifier_underlord_atrophy_aura_lua_stack:IsPurgable()
return false
end
function modifier_underlord_atrophy_aura_lua_stack:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE
end
function modifier_underlord_atrophy_aura_lua_stack:RemoveOnDeath()
return false
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_underlord_atrophy_aura_lua_stack:OnCreated( kv )
end
function modifier_underlord_atrophy_aura_lua_stack:OnRefresh( kv )
end
function modifier_underlord_atrophy_aura_lua_stack:OnRemoved()
end
function modifier_underlord_atrophy_aura_lua_stack:OnDestroy()
if not IsServer() then return end
self.parent:RemoveStack( self.bonus )
end
|
local ok, telescope = pcall(require, 'telescope')
if not ok then
return
end
local M = {}
M.setup = function()
local actions = require('telescope.actions')
telescope.setup({
defaults = {
mappings = {
i = {
['<esc>'] = actions.close,
},
},
},
extensions = {
fzf = {
fuzzy = true,
override_generic_sorter = true,
override_file_sorter = true,
case_mode = 'smart_case',
},
},
})
telescope.load_extension('fzf')
end
return M
|
--------------------------------
-- @module ProtectedNode
-- @extend Node
-- @parent_module cc
---@class cc.ProtectedNode:cc.Node
local ProtectedNode = {}
cc.ProtectedNode = ProtectedNode
--------------------------------
--- Adds a child to the container with a local z-order.<br>
-- If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.<br>
-- param child A child node<br>
-- param localZOrder Z order for drawing priority. Please refer to `setLocalZOrder(int)`
---@param child cc.Node
---@param localZOrder number
---@param tag number
---@return cc.ProtectedNode
---@overload fun(self:cc.ProtectedNode, child:cc.Node, localZOrder:number):cc.ProtectedNode
---@overload fun(self:cc.ProtectedNode, child:cc.Node):cc.ProtectedNode
function ProtectedNode:addProtectedChild(child, localZOrder, tag)
end
--------------------------------
---
---@return cc.ProtectedNode
function ProtectedNode:disableCascadeColor()
end
--------------------------------
--- Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter.
--- param tag An integer number that identifies a child node.
--- param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
---@param tag number
---@param cleanup boolean
---@return cc.ProtectedNode
function ProtectedNode:removeProtectedChildByTag(tag, cleanup)
end
--------------------------------
--- Reorders a child according to a new z value.
--- param child An already added child node. It MUST be already added.
--- param localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
---@param child cc.Node
---@param localZOrder number
---@return cc.ProtectedNode
function ProtectedNode:reorderProtectedChild(child, localZOrder)
end
--------------------------------
--- Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter.
--- param cleanup true if all running actions on all children nodes should be cleanup, false otherwise.
--- js removeAllChildren
--- lua removeAllChildren
---@param cleanup boolean
---@return cc.ProtectedNode
function ProtectedNode:removeAllProtectedChildrenWithCleanup(cleanup)
end
--------------------------------
---
---@return cc.ProtectedNode
function ProtectedNode:disableCascadeOpacity()
end
--------------------------------
--- Sorts the children array once before drawing, instead of every time when a child is added or reordered.
--- This approach can improves the performance massively.
--- note Don't call this manually unless a child added needs to be removed in the same frame
---@return cc.ProtectedNode
function ProtectedNode:sortAllProtectedChildren()
end
--------------------------------
--- Gets a child from the container with its tag.
--- param tag An identifier to find the child node.
--- return a Node object whose tag equals to the input parameter.
---@param tag number
---@return cc.Node
function ProtectedNode:getProtectedChildByTag(tag)
end
--------------------------------
--- Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.
--- param child The child node which will be removed.
--- param cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
---@param child cc.Node
---@param cleanup boolean
---@return cc.ProtectedNode
function ProtectedNode:removeProtectedChild(child, cleanup)
end
--------------------------------
--- Removes all children from the container with a cleanup.
--- see `removeAllChildrenWithCleanup(bool)`.
---@return cc.ProtectedNode
function ProtectedNode:removeAllProtectedChildren()
end
--------------------------------
--- Creates a ProtectedNode with no argument.
--- return A instance of ProtectedNode.
---@return cc.ProtectedNode
function ProtectedNode:create()
end
--------------------------------
---
---@param mask number
---@param applyChildren boolean
---@return cc.ProtectedNode
function ProtectedNode:setCameraMask(mask, applyChildren)
end
--------------------------------
---
---@param globalZOrder number
---@return cc.ProtectedNode
function ProtectedNode:setGlobalZOrder(globalZOrder)
end
--------------------------------
--- js NA
---@param renderer cc.Renderer
---@param parentTransform mat4_table
---@param parentFlags number
---@return cc.ProtectedNode
function ProtectedNode:visit(renderer, parentTransform, parentFlags)
end
--------------------------------
---
---@param parentOpacity number
---@return cc.ProtectedNode
function ProtectedNode:updateDisplayedOpacity(parentOpacity)
end
--------------------------------
---
---@param parentColor color3b_table
---@return cc.ProtectedNode
function ProtectedNode:updateDisplayedColor(parentColor)
end
--------------------------------
---
---@return cc.ProtectedNode
function ProtectedNode:cleanup()
end
--------------------------------
---
---@return cc.ProtectedNode
function ProtectedNode:ProtectedNode()
end
return nil
|
-- Copyright 2021 SkyTheCodeMaster - All Rights Reserved.
local redrun = require("redrun")
local modem = peripheral.find("modem")
local sha256 = require("sha256")
modem.open(30000)
local myid = os.getComputerID()
-- Sha256 digest but pre hexed
local function hash(data)
local dataHash = sha256.digest(data)
return dataHash:toHex()
end
local function transmit(id,packet,type)
local data = {
id=id,
sendid=myid,
packet=packet,
hash=hash(packet),
type=type
}
modem.transmit(30000,30000,data)
end
local function tcpServer()
while true do
local event = {os.pullEvent()}
if event[1] == "tcp_send" then
local message = event[2]
if type(message) == "table" then
if message.type == "data" then
local sender = message.sendid
repeat
modem.transmit(30000,30000,{
id = sender,
sendid = myid,
packet = message.hash,
type = "confirm"
})
local _,_,_,_,ok = os.pullEvent("modem_message")
until ok == true
os.queueEvent("tcp_message",sender,message.packet)
elseif message.type == "confirm" then
end
end
end
end
end
local id = redrun.start(tcpServer,"TCP Server")
if fs.exists("startup.bak") then
shell.run("startup.bak")
end
|
NOTIFICATIONS_VERSION = "1.00"
--[[
Sample Panorama Notifications Library by BMD
Installation
-"require" this file inside your code in order to gain access to the Notifications class for sending notifications to players, teams, or all clients.
-Ensure that you have the barebones_notifications.xml, barebones_notifications.js, and barebones_notifications.css files in your panorama content folder.
-Ensure that barebones_notifications.xml is included in your custom_ui_manifest.xml with
<CustomUIElement type="Hud" layoutfile="file://{resources}/layout/custom_game/barebones_notifications.xml" />
Usage
-Notifications can be sent to the Top or Bottom notification panel of an individual player, a whole team, or all clients at once.
-Notifications can be sent in pieces consisting of Labels, Images, HeroImages, and AbilityImages.
-Notifications are specified by a table which has 4 potential parameters:
-duration: The duration to display the notification for on screen. Ignored for a notification which "continues" a previous notification line.
-class: An optional (leave as nil for default) string which will be used as the class to add to the notification piece.
-style: An optional (leave as nil for default) table of css properties to add to this notification, such as {["font-size"]="60px", color="green"}.
-continue: An optional (leave as nil for false) boolean which tells the notification system to add this notification to the current notification line if 'true'.
This lets you place multiple individual notification pieces on the same overall notification.
-For Labels, there is one additional mandatory parameter:
-text: The text to display in the notification. Can provide localization tokens ("#addonname") or non-localized text.
-For HeroImages, there is two additional parameters:
-hero: (Mandatory) The hero name, e.g. "npc_dota_hero_axe".
-imagestyle: (Optional) The image style to display for this hero image. Default when 'nil' is 'icon'. 'portrait' and 'landscape' are two other options.
-For AboilityImages, there is one additional mandatory parameter:
-ability: The ability name, e.g. "lina_fiery_soul".
-For Images, there is one additional mandatory parameter:
-image: The image src string, e.g. "file://{images}/status_icons/dota_generic.psd".
-For ItemImages, there is one additional mandatory parameter:
-item: The item name, e.g. "item_force_staff".
-Notifications can be removed from the Top/Bottom or cleared
-Call the Notifications:Top, Notifications:TopToAll, or Notifications:TopToTeam to send a top-area notification to the appropriate players
-Call the Notifications:Bottom, Notifications:BottomToAll, or Notifications:BottomToTeam to send a bottom-area notifications to the appropriate players
-Call the Notifications:ClearTop, Notifications:ClearTopFromAll, or Notifications:ClearTopFromTeam to clear all existing top-area notifications from appropriate players
-Call the Notifications:ClearBottom, Notifications:ClearBottomFromAll, or Notifications:ClearBottomFromTeam to clear all existing bottom-area notifications from appropriate players
-Call the Notifications:RemoveTop, Notifications:RemoveTopFromAll, or Notifications:RemoveTopFromTeam to remove all existing top-area notifications from appropriate players up to the provided count of notifications
-Call the Notifications:RemoveBottom, Notifications:RemoveBottomFromAll, or Notifications:RemoveBottomFromTeam to remove all existing bottom-area notifications from appropriate players up to the provided count of notifications
Examples:
-- Send a notification to all players that displays up top for 5 seconds
Notifications:TopToAll({text="Top Notification for 5 seconds ", duration=5.0})
-- Send a notification to playerID 0 which will display up top for 9 seconds and be green, on the same line as the previous notification
Notifications:Top(0, {text="GREEEENNNN", duration=9, style={color="green"}, continue=true})
-- Display 3 styles of hero icons on the same line for 5 seconds.
Notifications:TopToAll({hero="npc_dota_hero_axe", duration=5.0})
Notifications:TopToAll({hero="npc_dota_hero_axe", imagestyle="landscape", continue=true})
Notifications:TopToAll({hero="npc_dota_hero_axe", imagestyle="portrait", continue=true})
-- Display a generic image and then 2 ability icons and an item on the same line for 5 seconds
Notifications:TopToAll({image="file://{images}/status_icons/dota_generic.psd", duration=5.0})
Notifications:TopToAll({ability="nyx_assassin_mana_burn", continue=true})
Notifications:TopToAll({ability="lina_fiery_soul", continue=true})
Notifications:TopToAll({item="item_force_staff", continue=true})
-- Send a notification to all players on radiant (GOODGUYS) that displays near the bottom of the screen for 10 seconds to be displayed with the NotificationMessage class added
Notifications:BottomToTeam(DOTA_TEAM_GOODGUYS, {text="AAAAAAAAAAAAAA", duration=10, class="NotificationMessage"})
-- Send a notification to player 0 which will display near the bottom a large red notification with a solid blue border for 5 seconds
Notifications:Bottom(PlayerResource:GetPlayer(0), {text="Super Size Red", duration=5, style={color="red", ["font-size"]="110px", border="10px solid blue"}})
-- Remove 1 bottom and 2 top notifications 2 seconds later
Timers:CreateTimer(2,function()
Notifications:RemoveTop(0, 2)
Notifications:RemoveBottomFromTeam(DOTA_TEAM_GOODGUYS, 1)
-- Add 1 more notification to the bottom
Notifications:BottomToAll({text="GREEEENNNN again", duration=9, style={color="green"}})
end)
-- Clear all notifications from the bottom
Timers:CreateTimer(7, function()
Notifications:ClearBottomFromAll()
end)
]]
if Notifications == nil then
Notifications = class({})
end
function Notifications:ClearTop(player)
Notifications:RemoveTop(player, 50)
end
function Notifications:ClearBottom(player)
Notifications:RemoveBottom(player, 50)
end
function Notifications:ClearTopFromAll()
Notifications:RemoveTopFromAll(50)
end
function Notifications:ClearBottomFromAll()
Notifications:RemoveBottomFromAll(50)
end
function Notifications:ClearTopFromTeam(team)
Notifications:RemoveTopFromTeam(team, 50)
end
function Notifications:ClearBottomFromTeam(team)
Notifications:RemoveBottomFromTeam(team, 50)
end
function Notifications:RemoveTop(player, count)
if type(player) == "number" then
player = PlayerResource:GetPlayer(player)
end
CustomGameEventManager:Send_ServerToPlayer(player, "top_remove_notification", {count=count} )
end
function Notifications:RemoveBottom(player, count)
if type(player) == "number" then
player = PlayerResource:GetPlayer(player)
end
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_remove_notification", {count=count})
end
function Notifications:RemoveTopFromAll(count)
CustomGameEventManager:Send_ServerToAllClients("top_remove_notification", {count=count} )
end
function Notifications:RemoveBottomFromAll(count)
CustomGameEventManager:Send_ServerToAllClients("bottom_remove_notification", {count=count})
end
function Notifications:RemoveTopFromTeam(team, count)
CustomGameEventManager:Send_ServerToTeam(team, "top_remove_notification", {count=count} )
end
function Notifications:RemoveBottomFromTeam(team, count)
CustomGameEventManager:Send_ServerToTeam(team, "bottom_remove_notification", {count=count})
end
function Notifications:Top(player, table)
if type(player) == "number" then
player = PlayerResource:GetPlayer(player)
end
if table.text ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "top_notification", {text=table.text, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.hero ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "top_notification", {hero=table.hero, imagestyle=table.imagestyle, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.image ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "top_notification", {image=table.image, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.ability ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "top_notification", {ability=table.ability, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.item ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "top_notification", {item=table.item, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
else
CustomGameEventManager:Send_ServerToPlayer(player, "top_notification", {text="No TEXT provided.", duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
end
end
function Notifications:TopToAll(table)
if table.text ~= nil then
CustomGameEventManager:Send_ServerToAllClients("top_notification", {text=table.text, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.hero ~= nil then
CustomGameEventManager:Send_ServerToAllClients("top_notification", {hero=table.hero, imagestyle=table.imagestyle, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.image ~= nil then
CustomGameEventManager:Send_ServerToAllClients("top_notification", {image=table.image, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.ability ~= nil then
CustomGameEventManager:Send_ServerToAllClients("top_notification", {ability=table.ability, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.item ~= nil then
CustomGameEventManager:Send_ServerToAllClients("top_notification", {item=table.item, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
else
CustomGameEventManager:Send_ServerToAllClients("top_notification", {text="No TEXT provided.", duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
end
end
function Notifications:TopToTeam(team, table)
if table.text ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "top_notification", {text=table.text, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.hero ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "top_notification", {hero=table.hero, imagestyle=table.imagestyle, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.image ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "top_notification", {image=table.image, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.ability ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "top_notification", {ability=table.ability, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.item ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "top_notification", {item=table.item, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
else
CustomGameEventManager:Send_ServerToTeam(team, "top_notification", {text="No TEXT provided.", duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
end
end
function Notifications:Bottom(player, table)
if type(player) == "number" then
player = PlayerResource:GetPlayer(player)
end
if table.text ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_notification", {text=table.text, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.hero ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_notification", {hero=table.hero, imagestyle=table.imagestyle, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.image ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_notification", {image=table.image, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.ability ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_notification", {ability=table.ability, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.item ~= nil then
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_notification", {item=table.item, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
else
CustomGameEventManager:Send_ServerToPlayer(player, "bottom_notification", {text="No TEXT provided.", duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
end
end
function Notifications:BottomToAll(table)
if table.text ~= nil then
CustomGameEventManager:Send_ServerToAllClients("bottom_notification", {text=table.text, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.hero ~= nil then
CustomGameEventManager:Send_ServerToAllClients("bottom_notification", {hero=table.hero, imagestyle=table.imagestyle, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.image ~= nil then
CustomGameEventManager:Send_ServerToAllClients("bottom_notification", {image=table.image, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.ability ~= nil then
CustomGameEventManager:Send_ServerToAllClients("bottom_notification", {ability=table.ability, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.item ~= nil then
CustomGameEventManager:Send_ServerToAllClients("bottom_notification", {item=table.item, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
else
CustomGameEventManager:Send_ServerToAllClients("bottom_notification", {text="No TEXT provided.", duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
end
end
function Notifications:BottomToTeam(team, table)
if table.text ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "bottom_notification", {text=table.text, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.hero ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "bottom_notification", {hero=table.hero, imagestyle=table.imagestyle, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.image ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "bottom_notification", {image=table.image, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.ability ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "bottom_notification", {ability=table.ability, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
elseif table.item ~= nil then
CustomGameEventManager:Send_ServerToTeam(team, "bottom_notification", {item=table.item, duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
else
CustomGameEventManager:Send_ServerToTeam(team, "bottom_notification", {text="No TEXT provided.", duration=table.duration, class=table.class, style=table.style, continue=table.continue} )
end
end
|
-----------------------------------
-- Area: Castle Zvahl Keep (162)
-- Mob: Demon Warlock
-- Note: PH for Viscount Morax
-----------------------------------
local ID = require("scripts/zones/Castle_Zvahl_Keep/IDs");
require("scripts/globals/mobs");
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
tpz.mob.phOnDespawn(mob,ID.mob.VISCOUNT_MORAX_PH,10,math.random(3600,28800)); -- 1 to 8 hours
end;
|
local Camera = {
magnitude = 0,
dx = 0,
dy = 0,
currentDuration = 0,
shakeActive = false
}
Camera.__index = Camera
function Camera:new()
local camera = {}
setmetatable(camera, Camera)
camera.magnitude = 0
camera.dx = 0
camera.dy = 0
camera.currentDuration = 0
camera.shakeActive = false
return camera
end
function Camera:update(dt)
if not self.shakeActive then
return
end
self.currentDuration = self.currentDuration - dt
self.dx = love.math.random(-self.magnitude, self.magnitude)
self.dy = love.math.random(-self.magnitude, self.magnitude)
if self.currentDuration <= 0 then
self:stopCameraShake()
end
end
function Camera:startCameraShake(magnitue, duration)
self.magnitude = magnitue
self.currentDuration = duration
self.shakeActive = true
end
function Camera:stopCameraShake()
self.shakeActive = false
self.dx = 0
self.dy = 0
end
function Camera:getShakeDelta()
return self.dx, self.dy
end
local mod = {}
mod.Camera = Camera
return mod
|
require "busted.runner"()
local assert = assert
describe("[Iterator]", function()
local ptable = require "ptable"
describe("Empty table", function()
local empty_table = ptable({})
local i = empty_table:iterator()
it("should not be nil", function() assert.is_not.Nil(i) end)
it("should return nil", function() assert.Nil(i:key()) end)
it("should return nil", function() assert.Nil(i:value()) end)
it("should return false", function() assert.False(i:hasNext()) end)
end)
describe("Not empty table", function()
local tbl = ptable({a = 1, b = 2})
local i = tbl:iterator()
it("should not be nil", function() assert.is_not.Nil(i) end)
it("should not return nil", function() assert.Nil(i:key()) end)
it("should not return nil", function() assert.Nil(i:value()) end)
it("should not return true", function() assert.True(i:hasNext()) end)
end)
describe("key value table", function()
local tbl = ptable({a = 1, b = 2})
local i = tbl:iterator()
i:next()
local key = i:key()
local value = i:value()
it("should return 'a' or 'b'",
function() assert.True("a" == key or "b" == key) end)
it("should return '1' or '2'",
function() assert.True(1 == value or 2 == value) end)
it("should return '1' or '2'", function()
assert.True(
(key == "a" and value == 1) or (key == "b" and value == 2))
end)
it("should return true", function() assert.True(i:hasNext()) end)
end)
describe("key value table", function()
local tbl = ptable({a = 1, b = 2})
local i = tbl:iterator()
local function some_test()
i:next()
i:next()
i:next()
end
it("should return error", function()
local _, err = pcall(some_test)
assert.is_not.Nil(err)
end)
end)
describe("Numerical table", function()
local tbl = ptable({1, 2})
local i = tbl:iterator()
i:next()
local key = i:key()
local value = i:value()
it("should return '1' or '2'",
function() assert.True(1 == key or 2 == key) end)
it("should return '1' or '2'",
function() assert.True(1 == value or 2 == value) end)
it("should return true", function() assert.True(i:hasNext()) end)
end)
describe("key value table", function()
local tbl = ptable({1, 2})
local i = tbl:iterator()
local function some_test()
i:next()
i:next()
i:next()
end
it("should return error", function()
local _, err = pcall(some_test)
assert.is_not.Nil(err)
end)
end)
end)
|
#!/usr/bin/env lua
local ui = require "tek.ui"
local RadioImage1 = ui.getStockImage("radiobutton")
local RadioImage2 = ui.getStockImage("radiobutton", 2)
local BitMapImage1 = ui.loadImage(ui.ProgDir .. "/graphics/world.ppm")
local BitMapImage2 = ui.loadImage(ui.ProgDir .. "/graphics/locale.ppm")
-------------------------------------------------------------------------------
-- Main:
-------------------------------------------------------------------------------
ui.Application:new
{
Children =
{
ui.Window:new
{
HideOnEscape = true,
Children =
{
ui.ImageWidget:new
{
Image = RadioImage1,
MinWidth = 20,
MinHeight = 20,
Mode = "button",
Style = "padding: 10",
ImageAspectX = 2,
ImageAspectY = 3,
onPress = function(self)
ui.ImageWidget.onPress(self)
self:setValue("Image", self.Pressed and RadioImage2 or RadioImage1)
end
},
ui.ImageWidget:new
{
Mode = "button",
Image = BitMapImage1,
Style = "padding: 10",
onPress = function(self)
ui.ImageWidget.onPress(self)
self:setValue("Image", self.Pressed and BitMapImage2 or BitMapImage1)
end
}
}
}
}
}:run()
|
--[[
OEML - REST API
This section will provide necessary information about the `CoinAPI OEML REST API` protocol. This API is also available in the Postman application: <a href=\"https://postman.coinapi.io/\" target=\"_blank\">https://postman.coinapi.io/</a>
The version of the OpenAPI document: v1
Contact: [email protected]
Generated by: https://openapi-generator.tech
]]
-- ord_side class
local ord_side = {}
local ord_side_mt = {
__name = "ord_side";
__index = ord_side;
}
local function cast_ord_side(t)
return setmetatable(t, ord_side_mt)
end
local function new_ord_side()
return cast_ord_side({
})
end
return {
cast = cast_ord_side;
new = new_ord_side;
}
|
---
-- Utility functions for sending MLD requests and parsing reports.
--
-- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html
local nmap = require "nmap"
local ipOps = require "ipOps"
local packet = require "packet"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
_ENV = stdnse.module("multicast", stdnse.seeall)
---
-- Performs an MLD general query on the selected interface and caches the results such that
-- subsequent calls to this function do not generate additional traffic.
--
-- @param if_nfo A table containing information about the interface to send the request on.
-- Can be one of those returned by nmap.list_interfaces().
-- @param arg_timeout The amount of time to wait for reports.
--
-- @return A list of tables, each table containing three items, namely device, layer 2 reply and layer 3 reply.
--
mld_query = function( if_nfo, arg_timeout )
-- check if the interface name is valid or if nmap can find one
if if_nfo == nil then
return nil
end
-- we need some ID for this interface & address combination to use as the
-- registry key and the object to lock the mutex on
local reg_entry = "mld_reports_" .. if_nfo.device .. "_" .. if_nfo.address
local mutex = nmap.mutex( reg_entry )
mutex('lock')
-- first check if nmap.registry contains reports for this interface from a previous call of this function
if nmap.registry[reg_entry] ~= nil then
mutex('done')
return nmap.registry[reg_entry]
end
if not ipOps.ip_in_range(if_nfo.address, "fe80::/10") -- link local address
or if_nfo.link ~= "ethernet" then -- not the loopback interface
mutex('done')
return nil
end
-- create the query packet
local src_mac = if_nfo.mac
local src_ip6 = ipOps.ip_to_str(if_nfo.address)
local dst_mac = packet.mactobin("33:33:00:00:00:01")
local dst_ip6 = ipOps.ip_to_str("ff02::1")
local general_qry = ipOps.ip_to_str("::")
local dnet = nmap.new_dnet()
local pcap = nmap.new_socket()
dnet:ethernet_open(if_nfo.device)
pcap:pcap_open(if_nfo.device, 1500, false, "ip6[40:1] == 58")
local probe = packet.Frame:new()
probe.mac_src = src_mac
probe.mac_dst = dst_mac
probe.ip_bin_src = src_ip6
probe.ip_bin_dst = dst_ip6
probe.ip6_tc = 0
probe.ip6_fl = 0
probe.ip6_hlimit = 1
probe.icmpv6_type = packet.MLD_LISTENER_QUERY
probe.icmpv6_code = 0
-- Add a non-empty payload too.
probe.icmpv6_payload = (
"\x00\x01" .. -- maximum response delay 1 millisecond (if 0, virtualbox TCP/IP stack crashes)
"\x00\x00" .. -- reserved
ipOps.ip_to_str("::") -- empty address - general MLD query
)
probe:build_icmpv6_header()
probe.exheader = string.pack(">BBBB I2 BB",
packet.IPPROTO_ICMPV6, -- next header
0x00, -- length not including first 8 octets
0x05, -- type is router alert
0x02, -- length 2 bytes
0x00, -- router alert MLD
0x01, -- padding type PadN
0x00 -- padding length 0
)
probe.ip6_nhdr = packet.IPPROTO_HOPOPTS
probe:build_ipv6_packet()
probe:build_ether_frame()
-- send the query packet
dnet:ethernet_send(probe.frame_buf)
-- wait for responses to the query packet
pcap:set_timeout(1000)
local pcap_timeout_count = 0
local nse_timeout = arg_timeout or 10
local start_time = nmap:clock()
local addrs = {}
nmap.registry[reg_entry] = {}
repeat
local status, length, layer2, layer3 = pcap:pcap_receive()
local cur_time = nmap:clock()
if status then
local l2reply = packet.Frame:new(layer2)
local l3reply = packet.Packet:new(layer3, length, true)
local target_ip = l3reply.ip_src
if l3reply.ip6_nhdr == packet.MLD_LISTENER_REPORT or l3reply.ip6_nhdr == packet.MLDV2_LISTENER_REPORT then
table.insert(
nmap.registry[reg_entry],
{ if_nfo.device, l2reply, l3reply }
)
end
end
until ( cur_time - start_time >= nse_timeout )
-- clean up
dnet:ethernet_close()
pcap:pcap_close()
mutex('done')
return nmap.registry[reg_entry]
end
---
-- Extracts IP addresses from MLD reports captured by the mld_query function.
--
-- @param reports The output of the mld_query function.
--
-- @return A list of tables, each table containing three items, namely device, mac and a list of addresses.
--
mld_report_addresses = function(reports)
local rep_addresses = {}
for _, report in pairs(reports) do
local device = report[1]
local l2reply = report[2]
local l3reply = report[3]
local target_ip = l3reply.ip_src
if l3reply.ip6_nhdr == packet.MLD_LISTENER_REPORT or l3reply.ip6_nhdr == packet.MLDV2_LISTENER_REPORT then
-- if this is the first reply from the target, make an entry for it
if not rep_addresses[target_ip] then
rep_addresses[target_ip] = stdnse.output_table()
end
local rep = rep_addresses[target_ip]
rep.device = device
rep.mac = stdnse.format_mac(l2reply.mac_src)
rep.multicast_ips = rep.multicast_ips or {}
-- depending on the MLD version of the report, add appropriate IP addresses
if l3reply.ip6_nhdr == packet.MLD_LISTENER_REPORT then
local multicast_ip = ipOps.str_to_ip( l3reply:raw(0x38, 16) ) -- IP starts at byte 0x38 and is 16 bytes long
table.insert(rep.multicast_ips, multicast_ip)
elseif l3reply.ip6_nhdr == packet.MLDV2_LISTENER_REPORT then
local no_records = l3reply:u16(0x36)
local record_offset = 0
local records_start = 0x38
for i = 1, no_records do
-- for the format description, see RFC3810 (ch. 5.2)
local aux_data_len = l3reply:u8(records_start + record_offset + 1)
local no_sources = l3reply:u16(records_start + record_offset + 2)
local multicast_ip = ipOps.str_to_ip(l3reply:raw(records_start + record_offset + 4, 16))
table.insert(rep.multicast_ips, multicast_ip)
record_offset = record_offset + 4 + 16 + no_sources * 16 + aux_data_len * 4
end
end
end
end
return rep_addresses
end
return _ENV
|
--[[
Gangi: Definicje
@author Jakub 'XJMLN' Starzak <[email protected]
@package PSZMTA.psz-gangi
@copyright Jakub 'XJMLN' Starzak <[email protected]>
Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie.
]]--
function isGOWindowOpen(wnd)
return guiGetVisible(wnd)
end
|
-- Targets:
--
-- {
-- fullname = full name of target
-- dir = target's build directory
-- outs = target's object files
-- is = { set of rule types which made the target }
-- }
local posix = require("posix")
local emitter = {}
local rules = {}
local targets = {}
local buildfiles = {}
local globals
local cwd = "."
local vars = {}
local parente = {}
local loadingstack = {}
-- Forward references
local loadtarget
local function print(...)
local function print_no_nl(list)
for _, s in ipairs(list) do
if (type(s) == "table") then
io.stderr:write("{")
for k, v in pairs(s) do
print_no_nl({k})
io.stderr:write("=")
print_no_nl({v})
io.stderr:write(" ")
end
io.stderr:write("}")
else
io.stderr:write(tostring(s))
end
end
end
print_no_nl({...})
io.stderr:write("\n")
end
local function assertString(s, i)
if (type(s) ~= "string") then
error(string.format("parameter %d must be a string", i))
end
end
local function concat(...)
local r = {}
local function process(list)
for _, t in ipairs(list) do
if (type(t) == "table") and not t.is then
process(t)
else
r[#r+1] = t
end
end
end
process({...})
return r
end
-- Test table membership (crudely).
local function contains(needle, haystack)
for _, k in ipairs(haystack) do
if (k == needle) then
return true
end
end
return false
end
local function inherit(high, low)
local o = {}
setmetatable(o, {
__index = function(self, k)
local x = high[k]
if x then
return x
end
return low[k]
end
})
for k, v in pairs(high) do
local _, _, kk = k:find("^%+(.*)$")
if kk then
o[kk] = concat(low[kk], v)
end
end
return o
end
local function asstring(o)
local t = type(o)
if (t == "nil") then
return ""
elseif (t == "string") then
return o
elseif (t == "number") then
return o
elseif (t == "table") then
if o.is then
return asstring(o.outs)
else
local s = {}
for _, v in pairs(o) do
s[#s+1] = asstring(v)
end
return table.concat(s, " ")
end
else
error(string.format("can't turn values of type '%s' into strings", t))
end
end
local function concatpath(...)
local p = table.concat({...}, "/")
return (p:gsub("/+", "/"):gsub("^%./", ""):gsub("/%./", "/"))
end
-- Returns a list of the targets within the given collection; the keys of any
-- keyed items are lost. Lists and wildcards are expanded.
local function targetsof(...)
local o = {}
local function process(items)
for _, item in pairs(items) do
if (type(item) == "table") then
if item.is then
-- This is a target.
o[#o+1] = item
else
-- This is a list.
process(item)
end
elseif (type(item) == "string") then
-- Filename!
if item:find("^%+") then
item = cwd..item
elseif item:find("^%./") then
item = concatpath(cwd, item)
end
o[#o+1] = loadtarget(item)
else
error(string.format("member of target list is not a string or a target"))
end
end
end
process({...})
return o
end
local function filenamesof(...)
local targets = targetsof(...)
local f = {}
for _, r in ipairs(targets) do
if (type(r) == "table") and r.is then
if r.outs then
for _, o in ipairs(r.outs) do
f[#f+1] = o
end
end
elseif (type(r) == "string") then
f[#f+1] = r
else
error(string.format("list of targets contains a %s which isn't a target",
type(r)))
end
end
return f
end
local function targetnamesof(...)
local targets = targetsof(...)
local f
for _, r in pairs(targets) do
if (type(r) == "table") and r.is then
f[#f+1] = r.fullname
elseif (type(r) == "string") then
f[#f+1] = r
else
error(string.format("list of targets contains a %s which isn't a target",
type(r)))
end
end
return f
end
local function dotocollection(files, callback)
if (#files == 1) and (type(files[1]) == "string") then
return callback(files[1])
end
local o = {}
local function process(files)
for _, s in ipairs(files) do
if (type(s) == "table") then
if s.is then
error("passed target to a filename manipulation function")
else
process(s)
end
else
local b = callback(s)
if (b ~= "") then
o[#o+1] = b
end
end
end
end
process(files)
return o
end
local function abspath(...)
return dotocollection({...},
function(filename)
assertString(filename, 1)
if not filename:find("^[/$]") then
filename = concatpath(posix.getcwd(), filename)
end
return filename
end
)
end
local function basename(...)
return dotocollection({...},
function(filename)
assertString(filename, 1)
local _, _, b = filename:find("^.*/([^/]*)$")
if not b then
return filename
end
return b
end
)
end
local function dirname(...)
return dotocollection({...},
function(filename)
assertString(filename, 1)
local _, _, b = filename:find("^(.*)/[^/]*$")
if not b then
return ""
end
return b
end
)
end
local function replace(files, pattern, repl)
return dotocollection({files},
function(filename)
return filename:gsub(pattern, repl)
end
)
end
local function fpairs(...)
return ipairs(filenamesof(...))
end
local function matching(collection, pattern)
local o = {}
dotocollection(collection,
function(filename)
if filename:find(pattern) then
o[#o+1] = filename
end
end
)
return o
end
-- Selects all targets containing at least one output file that matches
-- the pattern (or all, if the pattern is nil).
local function selectof(targets, pattern)
local targets = targetsof(targets)
local o = {}
for k, v in pairs(targets) do
if v.is and v.outs then
local matches = false
for _, f in pairs(v.outs) do
if f:find(pattern) then
matches = true
break
end
end
if matches then
o[#o+1] = v
end
end
end
return o
end
local function uniquify(...)
local s = {}
return dotocollection({...},
function(filename)
if not s[filename] then
s[filename] = true
return filename
end
end
)
end
local function startswith(needle, haystack)
return haystack:sub(1, #needle) == needle
end
local function emit(...)
local n = select("#", ...)
local args = {...}
for i=1, n do
local s = asstring(args[i])
io.stdout:write(s)
if not s:find("\n$") then
io.stdout:write(" ")
end
end
end
local function templateexpand(list, vars)
vars = inherit(vars, globals)
local o = {}
for _, s in ipairs(list) do
o[#o+1] = s:gsub("%%%b{}",
function(expr)
expr = expr:sub(3, -2)
local chunk, e = loadstring("return ("..expr..")", expr)
if e then
error(string.format("error evaluating expression: %s", e))
end
setfenv(chunk, vars)
local value = chunk()
if (value == nil) then
error(string.format("template expression '%s' expands to nil (probably an undefined variable)", expr))
end
return asstring(value)
end
)
end
return o
end
local function loadbuildfile(filename)
if contains(filename, loadingstack) then
error(string.format("build file cycle; '%s' refers to itself indirectly; stack is: %s %s",
filename, asstring(loadingstack), filename))
end
loadingstack[#loadingstack+1] = filename
if not buildfiles[filename] then
buildfiles[filename] = true
local fp, data, chunk, e
io.stderr:write("loading ", filename, "\n")
fp, e = io.open(filename)
if not e then
data, e = fp:read("*a")
fp:close()
if not e then
local thisglobals = {}
thisglobals._G = thisglobals
setmetatable(thisglobals, {__index = globals})
chunk, e = loadstring(data, "@"..filename)
if not e then
setfenv(chunk, thisglobals)
end
end
end
if e then
error(string.format("couldn't load '%s': %s", filename, e))
end
local oldcwd = cwd
cwd = dirname(filename)
chunk()
cwd = oldcwd
end
loadingstack[#loadingstack] = nil
end
local function loadbuildfilefor(filepart, targetpart)
local normalname = concatpath(filepart, "/build.lua")
if posix.access(normalname, "r") then
loadbuildfile(normalname)
return
end
local extendedname = concatpath(filepart, "/build-"..targetpart..".lua")
if posix.access(extendedname, "r") then
loadbuildfile(extendedname)
return
end
error(string.format("could not access either '%s' or '%s'", normalname, extendedname))
end
loadtarget = function(targetname)
if targets[targetname] then
return targets[targetname]
end
local target
if not targetname:find("%+") then
local files
if targetname:find("[?*]") then
files = posix.glob(targetname)
if not files then
files = {}
end
else
files = {targetname}
end
target = {
outs = files,
is = {
__implicitfile = true
}
}
targets[targetname] = target
else
local _, _, filepart, targetpart = targetname:find("^([^+]*)%+([%w-_]+)$")
if not filepart or not targetpart then
error(string.format("malformed target name '%s'", targetname))
end
if (filepart == "") then
filepart = cwd
end
loadbuildfilefor(filepart, targetpart)
target = targets[targetname]
if not target then
error(string.format("build file '%s' contains no target '%s'",
filepart, targetpart))
end
end
return target
end
local typeconverters = {
targets = function(propname, i)
if (type(i) == "string") then
i = {i}
elseif (type(i) ~= "table") then
error(string.format("property '%s' must be a target list", propname))
end
local m = {}
for k, v in pairs(i) do
local ts = targetsof(v)
if (type(k) == "number") then
for _, t in ipairs(ts) do
m[#m+1] = t
end
else
if (#ts ~= 1) then
error(string.format("named target '%s' can only be assigned from a single target", k))
else
m[k] = ts[1]
end
end
end
return m
end,
strings = function(propname, i)
if (type(i) == "string") then
i = {i}
elseif (type(i) ~= "table") then
error(string.format("property '%s' must be a string list", propname))
end
return concat(i)
end,
boolean = function(propname, i)
if (type(i) ~= "boolean") then
error(string.format("property '%s' must be a boolean", propname))
end
return i
end,
string = function(propname, i)
if (type(i) ~= "string") then
error(string.format("property '%s' must be a string", propname))
end
return i
end,
table = function(propname, i)
if (type(i) ~= "table") then
error(string.format("property '%s' must be a table", propname))
end
return i
end,
object = function(propname, i)
return i
end,
}
local function definerule(rulename, types, cb)
if rulename and rules[rulename] then
error(string.format("rule '%s' is already defined", rulename))
end
types.name = { type="string" }
types.cwd = { type="string", optional=true }
types.vars = { type="table", default={} }
for propname, typespec in pairs(types) do
if not typeconverters[typespec.type] then
error(string.format("property '%s' has unrecognised type '%s'",
propname, typespec.type))
end
end
local rulecwd = cwd
local rule = function(e)
local definedprops = {}
for propname, _ in pairs(e) do
definedprops[propname] = true
end
local args = {}
for propname, typespec in pairs(types) do
if e[propname] == nil then
if not typespec.optional and (typespec.default == nil) then
error(string.format("missing mandatory property '%s'", propname))
end
args[propname] = typespec.default
else
args[propname] = typeconverters[typespec.type](propname, e[propname])
definedprops[propname] = nil
end
end
local propname, _ = next(definedprops)
if propname then
error(string.format("don't know what to do with property '%s'", propname))
end
if not args.cwd then
args.cwd = cwd
end
args.fullname = args.cwd.."+"..args.name
local oldparente = parente
parente = args
args.vars = inherit(args.vars, oldparente.vars)
local result = cb(args) or {}
parente = oldparente
result.is = result.is or {}
if rulename then
result.is[rulename] = true
end
result.fullname = args.fullname
if targets[arg.fullname] and (targets[arg.fullname] ~= result) then
error(string.format("target '%s' is already defined", args.fullname))
end
targets[result.fullname] = result
return result
end
if rulename then
if rules[rulename] then
error(string.format("rule '%s' is already defined", rulename))
end
rules[rulename] = rule
end
return rule
end
-----------------------------------------------------------------------------
-- DEFAULT RULES --
-----------------------------------------------------------------------------
local function install_make_emitter()
emit("hide = @\n")
function emitter:var(name, value)
-- Don't let emit insert spaces.
emit(name.."="..value.."\n")
end
function emitter:rule(name, ins, outs)
if (#outs == 0) then
local n = name.."-IMAGINARY-OUT"
emit(".INTERMEDIATE:", n, "\n")
outs = {n}
end
local impl = name.."-IMPL"
emit(".INTERMEDIATE:", name, "\n")
emit(".INTERMEDIATE:", impl, "\n")
for i = 1, #outs do
emit(name..":", outs[i], "\n")
end
for i = 1, #outs do
emit(outs[i]..":", impl, ";\n")
end
for i = 1, #ins do
emit(impl..":", ins[i], "\n")
end
emit(impl..":", "\n")
local dirs = uniquify(dirname(outs))
if (#dirs > 0) then
emit("\t@mkdir -p", dirs, "\n")
end
end
function emitter:phony(name, ins, outs)
emit(".PHONY:", name, "\n")
self:rule(name, ins, outs)
end
function emitter:label(...)
local s = table.concat({...}, " ")
emit("\t@echo", s, "\n")
end
function emitter:exec(commands)
for _, s in ipairs(commands) do
emit("\t$(hide)", s, "\n")
end
end
function emitter:endrule()
emit("\n")
end
end
local function install_ninja_emitter()
emit("rule build\n")
emit(" command = $command\n")
emit("\n")
local function unmake(collection)
return dotocollection({collection},
function(s)
return s:gsub("%$%b()",
function(expr)
return "${"..expr:sub(3, -2).."}"
end
)
end
)
end
function emitter:var(name, value)
-- Don't let emit insert spaces.
emit(name.."="..unmake(value).."\n")
end
function emitter:rule(name, ins, outs)
if (#outs == 0) then
emit("build", name, ": phony", unmake(ins), "\n")
else
emit("build", name, ": phony", unmake(outs), "\n")
emit("build", unmake(outs), ": build", unmake(ins), "\n")
end
end
function emitter:label(...)
end
function emitter:exec(commands)
emit(" command =", table.concat(unmake(commands), " && "), "\n")
end
function emitter:endrule()
emit("\n")
end
end
definerule("simplerule",
{
ins = { type="targets" },
outs = { type="strings" },
deps = { type="targets", default={} },
label = { type="string", optional=true },
commands = { type="strings" },
vars = { type="table", default={} },
},
function (e)
emitter:rule(e.fullname, filenamesof(e.ins, e.deps), e.outs)
emitter:label(e.fullname, " ", e.label or "")
local vars = inherit(e.vars, {
ins = filenamesof(e.ins),
outs = filenamesof(e.outs)
})
emitter:exec(templateexpand(e.commands, vars))
emitter:endrule()
return {
outs = e.outs
}
end
)
definerule("installable",
{
map = { type="targets", default={} },
deps = { type="targets", default={} },
},
function (e)
local deps = filenamesof(e.deps)
local commands = {}
local srcs = {}
local outs = {}
local dests = {}
for dest, src in pairs(e.map) do
if src.is.installable then
if (type(dest) ~= "number") then
error("can't specify a destination filename when installing an installable")
end
deps[#deps+1] = src.fullname
outs = concat(outs, filenamesof(src))
elseif (type(dest) == "number") then
error("only references to other installables can be missing a destination")
else
local f = filenamesof(src)
if (#f ~= 1) then
error("installable can only cope with targets emitting single files")
end
deps[#deps+1] = f
dests[#dests+1] = dest
outs[#outs+1] = dest
commands[#commands+1] = "cp "..f[1].." "..dest
end
end
emitter:rule(e.fullname, deps, dests)
emitter:label(e.fullname, " ", e.label or "")
if (#commands > 0) then
emitter:exec(commands)
end
emitter:endrule()
return {
outs = outs
}
end
)
-----------------------------------------------------------------------------
-- MAIN PROGRAM --
-----------------------------------------------------------------------------
local function parse_arguments(argmap, arg)
local i = 1
local files = {}
local function unrecognisedarg(arg)
argmap[" unrecognised"](arg)
end
while (i <= #arg) do
local o = arg[i]
local op
if (o:byte(1) == 45) then
-- This is an option.
if (o:byte(2) == 45) then
-- ...with a -- prefix.
o = o:sub(3)
local fn = argmap[o]
if not fn then
unrecognisedarg("--"..o)
end
i = i + fn(arg[i+1], arg[i+2])
else
-- ...without a -- prefix.
local od = o:sub(2, 2)
local fn = argmap[od]
if not fn then
unrecognisedarg("-"..od)
end
op = o:sub(3)
if (op == "") then
i = i + fn(arg[i+1], arg[i+2])
else
fn(op)
end
end
else
files[#files+1] = o
end
i = i + 1
end
argmap[" files"](files)
end
globals = {
posix = posix,
abspath = abspath,
asstring = asstring,
basename = basename,
concat = concat,
concatpath = concatpath,
cwd = function() return cwd end,
definerule = definerule,
dirname = dirname,
emit = emit,
filenamesof = filenamesof,
fpairs = fpairs,
include = loadbuildfile,
inherit = inherit,
print = print,
replace = replace,
matching = matching,
selectof = selectof,
startswith = startswith,
uniquify = uniquify,
vars = vars,
}
setmetatable(globals,
{
__index = function(self, k)
local rule = rules[k]
if rule then
return rule
else
return _G[k]
end
end
}
)
vars.cflags = {}
parente.vars = vars
setmetatable(_G,
{
__index = function(self, k)
local value = rawget(_G, k)
if not value then
error(string.format("access of undefined variable '%s'", k))
end
return value
end
}
)
do
local emitter_type = install_make_emitter
parse_arguments(
{
["make"] = function()
emitter_type = install_make_emitter
return 0
end,
["ninja"] = function()
emitter_type = install_ninja_emitter
return 0
end,
[" unrecognised"] = function(arg)
error(string.format("unrecognised argument '%s'", arg))
end,
[" files"] = function(files)
emitter_type()
for _, f in ipairs(files) do
local _, _, name, value = f:find("^([%w_]+)=(.*)$")
if name then
emitter:var(name, value)
end
end
for _, f in ipairs(files) do
if not f:find("=") then
loadbuildfile(f)
end
end
end
},
{...}
)
end
|
-- require'lspinstall'.setup()
-- important
-- local servers = require'lspinstall'.installed_servers()
-- for _, server in pairs(servers) do
-- require'lspconfig'[server].setup{}
-- end
|
--WiFi SetUp
station_cfg={}
station_cfg.ssid="WLAN_SSID"
station_cfg.pwd="WLAN_PWD"
wifi.sta.config(station_cfg)
--Mqtt SetUp
mqttKeepAlive = 60; --sec
host = "bro.ker.add.res"
port = "1883"
m = mqtt.Client("backlighter", mqttKeepAlive);
mqttMainTopic = "/desk/backlight"
--functions
function split(s, sep)
local fields = {}
local sep = sep or " "
local pattern = string.format("([^%s]+)", sep)
string.gsub(s, pattern, function(c) fields[#fields + 1] = c end)
return fields
end
function ws2812NewSettings(configs)
file.open(configfile, "w+")
file.writeline("LEDs="..configs[1])
file.writeline("Colours="..configs[2])
file.close()
end
--WS2812 SetUp
configfile = ".config"
if not file.exists(configfile) then
BytesPerLed = 4
NumOfLeds = 1
ws2812NewSettings({NumOfLeds,BytesPerLed})
else
file.open(configfile, "r")
line = file.readline()
while line ~= nil do
line = split(line,"=")
if line[1] == "LEDs" then
NumOfLeds = line[2]
elseif line[1] == "Colours" then
BytesPerLed = line[2]
end
line = file.readline()
end
file.close()
end
bfrleft = ws2812.newBuffer(NumOfLeds, BytesPerLed)
--bfrright = ws2812.newBuffer(NumOfLeds, BytesPerLed)
--bfrright:fill(0,0,0,0)
bfrleft:fill(0,0,0,0)
bfrleft:set(1,0,0,0,255)
ws2812.init(ws2812.MODE_SINGLE)
ws2812.write(bfrleft)
bfrleft:set(1,0,0,0,0)
--for led=1,8,1 --64 is included
--do
-- bfrleft:set(led,2^(led-1),0,0,0)
--end
--for led=9,16,1 --64 is included
--do
-- bfrleft:set(led,0,2^(led-9),0,0)
--end
--for led=17,24,1 --64 is included
--do
-- bfrleft:set(led,0,0,2^(led-17),0)
--end
--for led=25,32,1 --64 is included
--do
-- bfrleft:set(led,0,0,0,2^(led-25))initializing
--end
--for led=33,40,1 --64 is included
--do
-- bfrleft:set(led,0,0,2^(led-32),2^(led-32))
--end
tmr.alarm(1,1000, 1, function()
if wifi.sta.getip()==nil then
else
tmr.stop(1)
--host, port, secure, autoreconnect,function on success, function on fail
m:connect(host, port,0 ,0,
function (client)
m:subscribe({[mqttMainTopic .. "/numcolours"]=0, --number of colours, each LED has (RGB, RGBW, RGBWW)
[mqttMainTopic .. "/numleds"]=0, --number of LEDs, which are connected via WS2812
[mqttMainTopic .. "/colour"]=0}, --byte-stream, which contains the colour-settings (incl. white)
--two cases:
--multiple of NumColours -> LEDs starting at 1st, will be set
--multiple of NumColours + 1 -> first byte will be interpreted as Offset of LEDs (so max is 255)
function(conn)
-- print("subscribe success")
bfrleft:set(1,255,0,0,0)
ws2812.write(bfrleft)
end)
end,
function(client,reason)
-- print("connection failed: "..reason)
bfrleft:set(1,0,255,0,0)
ws2812.write(bfrleft)
end)
end
end)
--interpreting of incoming messages
m:on("message", function(client, topic, data)
if (topic == mqttMainTopic .. "/numcolours") and
(string.len(data) == 1) and
(tonumber(data) >=3 and tonumber(data) <=5) then
BytesPerLed = data;
ws2812NewSettings({NumOfLeds,data})
elseif (topic == mqttMainTopic .. "/numleds") then
NumOfLeds = data;
ws2812NewSettings({NumOfLeds,BytesPerLed})
elseif topic == mqttMainTopic .. "/colour" then
if (string.len(data) % BytesPerLed) == 0 then
bfrleft:replace(data)
elseif (string.len(data) % BytesPerLed) == 1 then
bfrleft:replace(string.sub(data,1),string.byte(data,1))
end
ws2812.write(bfrleft)
end
end)
|
local scene_maker = require("scene")
config = { }
love.load = function()
config.scene = scene_maker.make()
end
love.update = function(dt)
do
if config.scene.update then
config.scene.update(dt)
end
return config
end
end
love.draw = function()
do
if config.scene.draw then
config.scene.draw()
end
return config
end
end
|
-- vim:foldmethod=marker
---@diagnostic disable: different-requires
-- Automatically download packer.nvim if it doesn't exist
local fn = vim.fn
local install_path = fn.stdpath "data" .. "/site/pack/packer/start/packer.nvim"
if fn.empty(fn.glob(install_path)) > 0 then
fn.system { "git", "clone", "--depth", "1", "https://github.com/wbthomason/packer.nvim", install_path }
vim.cmd "packadd packer.nvim"
end
-- Automatically run :PackerCompile after every time this file is changed
vim.api.nvim_create_augroup("packer_user_config", { clear = true })
vim.api.nvim_create_autocmd("BufWritePost", {
group = "packer_user_config",
pattern = "plugins.lua",
command = "source <afile> | PackerCompile",
})
local packer = require "packer"
-- Use packer.nvim to manage all of the plugins
return packer.startup {
function(use)
-- Core {{{
use { "wbthomason/packer.nvim" }
use {
"neovim/nvim-lspconfig",
config = function()
require "core.lspconfig"
end,
after = { "nvim-lsp-installer" },
}
use {
"williamboman/nvim-lsp-installer",
config = function()
require "core.lsp-installer"
end,
}
use {
"jose-elias-alvarez/null-ls.nvim",
config = function()
require "core.null-ls"
end,
requires = {
{ "nvim-lua/plenary.nvim" },
{ "neovim/nvim-lspconfig" },
},
}
use {
"ahmedkhalf/project.nvim",
config = function()
require "core.project"
end,
}
use { "tpope/vim-sleuth" }
use {
"nvim-treesitter/nvim-treesitter",
run = ":TSUpdate",
config = function()
require "core.treesitter"
end,
requires = {
{ "nvim-treesitter/nvim-treesitter-refactor" },
{ "windwp/nvim-ts-autotag" },
{ "p00f/nvim-ts-rainbow" },
{ "RRethy/nvim-treesitter-endwise" },
{ "RRethy/nvim-treesitter-textsubjects", disable = true },
{ "JoosepAlviste/nvim-ts-context-commentstring" },
},
}
use { "tpope/vim-unimpaired" }
use {
"folke/which-key.nvim",
config = function()
require "core.which-key"
end,
}
use {
"linty-org/key-menu.nvim",
disable = true,
-- Alternative to which-key.nvim
}
use {
"b0o/mapx.nvim",
disable = true,
-- Plugin organize keymaps
-- Disable because lots of refactorings needs to be done
}
use { "lewis6991/impatient.nvim" }
use {
"nathom/filetype.nvim",
config = function()
require "core.filetype"
end,
}
-- }}}
-- Text Editing {{{
use {
"github/copilot.vim",
config = function()
require "edit.copilot"
end,
}
use {
"hrsh7th/nvim-cmp",
config = function()
require "edit.cmp"
end,
requires = {
{ "hrsh7th/cmp-buffer" },
{ "hrsh7th/cmp-nvim-lsp" },
{ "hrsh7th/cmp-nvim-lsp-signature-help" },
{ "hrsh7th/cmp-buffer" },
{ "hrsh7th/cmp-path" },
{ "hrsh7th/cmp-cmdline" },
{ "hrsh7th/cmp-calc" },
{ "hrsh7th/cmp-nvim-lua" },
{ "kdheepak/cmp-latex-symbols" },
{ "saadparwaiz1/cmp_luasnip" },
{ "kristijanhusak/vim-dadbod-completion" },
{ "lukas-reineke/cmp-under-comparator" },
},
}
use {
"L3MON4D3/LuaSnip",
config = function()
require "edit.luasnip"
end,
}
use { "rafamadriz/friendly-snippets" }
use {
"b3nj5m1n/kommentary",
config = function()
require "edit.kommentary"
end,
}
use { "tpope/vim-surround" }
use { "tpope/vim-repeat" }
use {
"lewis6991/spellsitter.nvim",
config = function()
require "edit.spellsitter"
end,
disable = true,
-- Spell check is less needed at this time
}
use {
"brymer-meneses/grammar-guard.nvim",
disable = true,
-- Now grammar check is provided by ltex languages server
}
use {
"windwp/nvim-autopairs",
config = function()
require "edit.autopairs"
end,
}
use {
"dhruvasagar/vim-table-mode",
ft = { "markdown", "org" },
}
use {
"ekickx/clipboard-image.nvim",
disable = true,
}
use {
"ThePrimeagen/refactoring.nvim",
config = function()
require "edit.refactoring"
end,
requires = {
{ "nvim-lua/plenary.nvim" },
{ "nvim-treesitter/nvim-treesitter" },
},
disable = true,
-- Plugin surpporting refactorings
-- Disable because it needs neovim nightly
}
-- }}}
-- Interface Extension {{{
use {
"stevearc/stickybuf.nvim",
disable = true,
-- Disable because it brings a more buggy behavior
-- https://github.com/neovim/neovim/issues/12517
}
use {
"akinsho/nvim-bufferline.lua",
config = function()
require "interface.bufferline"
end,
requires = { "kyazdani42/nvim-web-devicons" },
}
use {
"nvim-lualine/lualine.nvim",
config = function()
require "interface.lualine"
end,
requires = {
{ "kyazdani42/nvim-web-devicons" },
{ "ofseed/lualine-copilot" },
},
}
use {
"SmiteshP/nvim-navic",
config = function()
require "interface.navic"
end,
}
use {
"RRethy/vim-illuminate",
config = function()
require "interface.illuminate"
end,
}
use {
"anuvyklack/pretty-fold.nvim",
config = function()
require "interface.pretty-fold"
end,
requires = { "anuvyklack/nvim-keymap-amend" },
}
use {
"m-demare/hlargs.nvim",
config = function()
require "interface.hlargs"
end,
after = { "catppuccin" },
-- hlargs should be loaded after colorscheme
}
use {
"zbirenbaum/neodim",
config = function()
require "interface.dim"
end,
}
use {
"lukas-reineke/indent-blankline.nvim",
config = function()
require "interface.indent-blankline"
end,
}
use {
"stevearc/dressing.nvim",
config = function()
require "interface.dressing"
end,
}
use {
"ray-x/lsp_signature.nvim",
config = function()
require "interface.lsp_signature"
end,
}
use {
"onsails/lspkind-nvim",
config = function()
require "interface.lspkind"
end,
}
use {
"weilbith/nvim-code-action-menu",
cmd = { "CodeActionMenu" },
disable = true,
-- Disable because it not stable
}
use {
"goolord/alpha-nvim",
config = function()
require "interface.alpha"
end,
}
use {
"j-hui/fidget.nvim",
config = function()
require "interface.fidget"
end,
}
use {
"rcarriga/nvim-notify",
config = function()
require "interface.notify"
end,
}
use {
"nvim-treesitter/nvim-treesitter-context",
config = function()
require "interface.treesitter-context"
end,
}
use {
"norcalli/nvim-colorizer.lua",
config = function()
require "interface.colorizer"
end,
}
use { "dstein64/nvim-scrollview" }
use {
"lewis6991/satellite.nvim",
config = function()
require "interface.satellite"
end,
disable = true,
-- A substitue for nvim-scrollview
-- which support search results, lsp diagnostics and git hunks
-- Disable because it's work in progress
}
use {
"kevinhwang91/nvim-bqf",
config = function()
require "interface.bqf"
end,
}
use {
"kevinhwang91/nvim-fFHighlight",
config = function()
require "interface.ffhighlight"
end,
after = { "catppuccin" },
disable = true,
-- Plugin show inline search highlight
-- Disable because it's not very useful
}
use {
"folke/todo-comments.nvim",
config = function()
require "interface.todo-comments"
end,
}
use {
"folke/zen-mode.nvim",
config = function()
require "interface.zen-mode"
end,
cmd = { "ZenMode" },
}
use {
"folke/twilight.nvim",
config = function()
require "interface.twilight"
end,
cmd = { "Twilight" },
}
use {
"winston0410/range-highlight.nvim",
config = function()
require "interface.range-highlight"
end,
requires = {
"winston0410/cmd-parser.nvim",
},
}
use {
"psliwka/vim-smoothie",
disable = true,
-- Try to get rid of dependency on moving animations.
}
use {
"edluffy/specs.nvim",
config = function()
require "interface.specs"
end,
disable = true,
-- Disable because it's conflicting with the chinese text
}
use {
"chentoast/marks.nvim",
config = function()
require "interface.marks"
end,
}
use {
"tversteeg/registers.nvim",
config = function()
require "interface.registers"
end,
disable = true,
-- Behaves strangely when used with text objects
}
use {
"edluffy/hologram.nvim",
disable = true,
}
use {
"jubnzv/virtual-types.nvim",
disable = true,
-- Disable because few languages sever support it
}
use {
"bennypowers/nvim-regexplainer",
config = function()
require "interface.regexplainer"
end,
requires = {
"nvim-lua/plenary.nvim",
"MunifTanjim/nui.nvim",
},
}
use {
"jbyuki/nabla.nvim",
config = function()
require "interface.nabla"
end,
ft = { "tex", "markdown" },
}
use {
"sunjon/Shade.nvim",
config = function()
require "interface.shade"
end,
disable = true,
-- Disable because conflict with other floating window plugins
}
use {
"luukvbaal/stabilize.nvim",
config = function()
require "interface.stabilize"
end,
disable = true,
}
use {
-- "EdenEast/nightfox.nvim",
"catppuccin/nvim",
-- "folke/tokyonight.nvim",
-- "navarasu/onedark.nvim",
-- "Mofiqul/vscode.nvim",
-- "Mofiqul/dracula.nvim",
-- "projekt0n/github-nvim-theme",
-- "tanvirtin/monokai.nvim",
-- "ellisonleao/gruvbox.nvim",
-- "shaunsingh/solarized.nvim",
-- "shaunsingh/moonlight.nvim",
-- "shaunsingh/nord.nvim",
-- commit = "d83145614e8082b24a001643f1c6c00c0ea9aaef", -- After this commit, nightfox has changed a lot
as = "catppuccin",
config = function()
require "interface.colorscheme"
end,
-- requires = { "rktjmp/lush.nvim" }, -- Required by gruvbox
after = "nvim-tree.lua", -- Nvim-tree needs to be loaded before colorschemes
}
-- }}}
-- Tool Integration {{{
use {
"kyazdani42/nvim-tree.lua",
config = function()
require "tool.tree"
end,
requires = { "kyazdani42/nvim-web-devicons" },
}
use {
"sidebar-nvim/sidebar.nvim",
config = function()
require "config.interface.sidebar"
end,
requires = { "sidebar-nvim/sections-dap" },
disable = true,
}
use {
"nvim-neo-tree/neo-tree.nvim",
config = function()
require "tool.neo-tree"
end,
branch = "v2.x",
requires = {
"nvim-lua/plenary.nvim",
"kyazdani42/nvim-web-devicons", -- not strictly required, but recommended
"MunifTanjim/nui.nvim",
},
disable = true,
-- Subtitute for nvim-tree
-- Disable because few colorschemes support it
}
use {
"simrat39/symbols-outline.nvim",
config = function()
require "tool.symbols-outline"
end,
requires = { "kyazdani42/nvim-web-devicons" },
cmd = { "SymbolsOutline" },
disable = true,
-- Subtitute for aerial.nvim
-- Disable because better to use aerial.nvim
}
use {
"onsails/diaglist.nvim",
disable = true,
}
use {
"akinsho/nvim-toggleterm.lua",
config = function()
require "tool.toggleterm"
end,
}
use {
"stevearc/aerial.nvim",
config = function()
require "tool.aerial"
end,
}
use {
"lewis6991/gitsigns.nvim",
config = function()
require "tool.gitsigns"
end,
requires = "nvim-lua/plenary.nvim",
}
use {
"TimUntersberger/neogit",
config = function()
require "tool.neogit"
end,
requires = {
"nvim-lua/plenary.nvim",
"sindrets/diffview.nvim",
},
cmd = { "Neogit" },
}
use {
"sindrets/diffview.nvim",
config = function()
require "tool.diffview"
end,
cmd = { "DiffviewOpen", "DiffviewFileHistory" },
}
use {
"akinsho/git-conflict.nvim",
config = function()
require "tool.git-conflict"
end,
}
use {
"aserowy/tmux.nvim",
config = function()
require "tool.tmux"
end,
}
use {
"iamcco/markdown-preview.nvim",
config = function()
require "tool.markdown-preview"
end,
run = "cd app && yarn install",
ft = { "markdown" },
}
use {
"Saecki/crates.nvim",
config = function()
require "tool.crates"
end,
requires = { "nvim-lua/plenary.nvim" },
event = { "BufRead Cargo.toml" },
}
use {
"vuki656/package-info.nvim",
config = function()
require "tool.package-info"
end,
requires = "MunifTanjim/nui.nvim",
event = {
"BufRead package.json",
"BufRead package-lock.json",
},
}
use {
"pwntester/octo.nvim",
config = function()
require "tool.octo"
end,
cmd = { "Octo" },
disable = true,
-- Subtitute for gh.nvim
-- Disable because better to use gh.nvim
}
use {
"ldelossa/gh.nvim",
config = function()
require "tool.gh"
end,
requires = "ldelossa/litee.nvim",
}
use {
"tpope/vim-dadbod",
disable = true,
}
use {
"kristijanhusak/vim-dadbod-ui",
cmd = { "DBUIToggle" },
disable = true,
}
use {
"nvim-orgmode/orgmode",
config = function()
require "tool.orgmode"
end,
disable = true,
-- Need reconfigre, especially keymaps
}
use {
"akinsho/org-bullets.nvim",
config = function()
require "tool.org-bullets"
end,
ft = { "org" },
diable = true,
-- Disable with orgmode
}
-- }}}
-- Efficiency Improvement {{{
use {
"nvim-telescope/telescope.nvim",
config = function()
require "efficiency.telescope"
end,
requires = {
{ "nvim-lua/popup.nvim" },
{ "nvim-lua/plenary.nvim" },
{ "nvim-telescope/telescope-fzf-native.nvim", run = "make" },
{ "nvim-telescope/telescope-hop.nvim" },
{ "nvim-telescope/telescope-project.nvim" },
{ "nvim-telescope/telescope-file-browser.nvim" },
{ "nvim-telescope/telescope-media-files.nvim" },
{ "nvim-telescope/telescope-dap.nvim" },
},
}
use {
"phaazon/hop.nvim",
config = function()
require "efficiency.hop"
end,
}
use {
"mfussenegger/nvim-treehopper",
config = function()
require "efficiency.treehopper"
end,
}
use { "kevinhwang91/vim-ibus-sw" }
use {
"ethanholz/nvim-lastplace",
config = function()
require "efficiency.lastplace"
end,
}
use {
"Shatur/neovim-session-manager",
config = function()
require "efficiency.session-manager"
end,
requires = {
{ "nvim-lua/plenary.nvim" },
},
}
use {
"dstein64/vim-startuptime",
cmd = { "StartupTime" },
}
use {
"t9md/vim-choosewin",
disable = true,
}
-- }}}
-- Debug And Run {{{
use {
"michaelb/sniprun",
config = function()
require "debug.sniprun"
end,
run = "bash install.sh",
}
use {
"rcarriga/neotest",
requires = {
"nvim-lua/plenary.nvim",
"nvim-treesitter/nvim-treesitter",
"antoinemadec/FixCursorHold.nvim",
},
disable = true,
}
use {
"rafcamlet/nvim-luapad",
disable = true,
}
use {
"mfussenegger/nvim-dap",
config = function()
require "debug.dap"
end,
}
use {
"theHamsta/nvim-dap-virtual-text",
config = function()
require "debug.dap-virtual-text"
end,
}
use {
"rcarriga/nvim-dap-ui",
config = function()
require "debug.dap-ui"
end,
}
use {
"Pocco81/dap-buddy.nvim",
run = "make",
disable = true,
}
use {
"mfussenegger/nvim-dap-python",
config = function()
require "debug.dap-python"
end,
ft = { "python" },
}
use {
"Shatur/neovim-cmake",
config = function()
require "debug.cmake"
end,
ft = { "c", "cpp", "cmake" },
}
-- Language Specific
use {
"lervag/vimtex",
config = function()
require "language.tex"
end,
ft = { "tex" },
}
use {
"plasticboy/vim-markdown",
ft = { "markdown" },
}
use {
"jakewvincent/mkdnflow.nvim",
disable = true,
}
use {
"p00f/clangd_extensions.nvim",
config = function()
require "language.clangd_extensions"
end,
after = { "nvim-lsp-installer" },
}
use {
"simrat39/rust-tools.nvim",
config = function()
require "language.rust-tools"
end,
after = { "nvim-lsp-installer" },
}
use {
"mfussenegger/nvim-jdtls",
config = function()
require "language.jdtls"
end,
ft = { "java" },
disable = true,
}
use {
"akinsho/flutter-tools.nvim",
disable = true,
}
use {
"jose-elias-alvarez/typescript.nvim",
config = function()
require "language.typescript"
end,
after = { "nvim-lsp-installer" },
}
use {
"nanotee/sqls.nvim",
disable = true,
after = { "nvim-lsp-installer" },
}
-- }}}
end,
config = {
display = {
prompt_border = "rounded",
},
compile_path = vim.fn.stdpath "config" .. "/lua/packer_compiled.lua",
},
}
|
-- Requires Automato version 1.78!
-- This script shows very simple and basic web access using the new LuaSocket version 3.0-rc1 module compiled into Automato for us by Jimbly.
-- It also shows how you can add additional modules and use them in Automato. You will need to open the console to see any output at all.
-- There is a lot more you can do with LuaSockets than just a simple http request. Visit http://w3.impa.br/~diego/software/luasocket/ to learn
-- more about this very handy module.
local http = require("socket.http"); -- load http functions.
-- If you...
-- goto http://dkolf.de/src/dkjson-lua.fsl/home/ and get the dkjson.lua script
-- and put it in the new Automato\luaLibs\ folder that contains the new socket.lua file.
-- ... and uncomment the next line...
-- local json = require("dkjson"); -- If you put the dkjson.lua script in the right location, you'll now have access to this module.
-- ... you can then uncomment the commented lines in doit() to see json decoding (one of the easier methods of encoding, transfering, and decoding data).
-- Many many many thanks to Jimb for adding the LuaSocket module! This opens a lot of possibilities for us, like being able to harvest mushrooms
-- and automatically update the mushroom databases online with the location, date, time, and count of mushroom spawns without having to switch to
-- a browser to do so, or having to take notes to manually enter these values later.
-- If I get a chance, I plan to do such a script and others using the features of LuaSocket. Until then I wanted to at least show my appreciation
-- to Jimb and help everyone else to get started using this new feature.
-- Catch ya in ATiTD!
-- ~ Dreger ~
function doit()
lsPrintln(socket._VERSION); -- LuaSocket 3.0-rc1
local res = http.request("http://jt-development.com/luaSocketExample.php"); -- http://jt-development.com/luaSocketExample.php will output JSON encoded data
lsPrintln(res); -- print to console what we got.
-- local values = json.decode(res); -- convert json encoded data to lua data.
-- lsPrintln(values['bugs']); -- null
-- lsPrintln(values['instruments'][1]); -- violin
-- lsPrintln(values['animals'][2]); -- cat
res = http.request("http://jt-development.com/luaSocketExample.php?test=ohBuggar!"); -- adding "?test=something" to this script will tell the script to return a simple json encoded test="something" string.
lsPrintln(res); -- { "test":"ohBuggar!" }
-- values = json.decode(res); -- convert json encoded data to lua data.
-- lsPrintln(values['test']); -- ohBuggar!
end
-- This is the luaSocketExample.php script on my server:
-- <?PHP
-- if (!isset($_REQUEST['test']))
-- print('{ "bugs":null, "instruments":["violin","trombone","theremin"], "animals":["dog","cat","aardvark"] }');
-- else
-- print('{ "test":"' . $_REQUEST['test'] . '" }');
-- ?>
|
require 'luacov'
local Delaunay = (require "delaunay")
local Point = Delaunay.Point
local Triangle = Delaunay.Triangle
context("Delaunay", function()
test('is a module containing binding to Point, Edge, Triangle primitives', function()
assert_true(type(Delaunay) == 'table')
assert_true(type(Delaunay.Point) == 'table')
assert_true(type(Delaunay.Edge) == 'table')
assert_true(type(Delaunay.Triangle) == 'table')
end)
it('offers a triangulation function', function()
assert_true(type(Delaunay.triangulate) == 'function')
end)
it('also have a _VERSION member', function()
assert_true(type(Delaunay._VERSION) == 'string')
end)
should('throw an error when receiving a vertex', function()
local function triangulate1vertex()
Delaunay.triangulate(Point())
end
assert_error(triangulate1vertex)
end)
should('throw an error when receiving two vertices', function()
local function triangulate2vertices()
Delaunay.triangulate(Point(), Point(1,1))
end
assert_error(triangulate2vertices)
end)
should('return a unique triangle made when receiving 3 vertices', function()
local p1, p2, p3 = Point(), Point(2,0), Point(1,1)
local t = Delaunay.triangulate(p1, p2, p3)
assert_equal(#t, 1)
assert_equal(getmetatable(t[1]), Triangle)
assert_equal(t[1].p1, p1)
assert_equal(t[1].p2, p2)
assert_equal(t[1].p3, p3)
end)
should('return 2 triangles for those 4 vertices', function()
local p1, p2, p3, p4 = Point(), Point(1,0), Point(1,1), Point(0,1)
local t = Delaunay.triangulate(p1, p2, p3, p4)
assert_equal(#t, 2)
assert_equal(getmetatable(t[1]), Triangle)
assert_equal(t[1].p1, p2)
assert_equal(t[1].p2, p1)
assert_equal(t[1].p3, p4)
assert_equal(getmetatable(t[2]), Triangle)
assert_equal(t[2].p1, p3)
assert_equal(t[2].p2, p2)
assert_equal(t[2].p3, p4)
end)
should('return 4 triangles for those 5 vertices', function()
local p1, p2, p3, p4, p5 = Point(), Point(1,0), Point(1,1), Point(0,1), Point(0.5, 0.5)
local t = Delaunay.triangulate(p1, p2, p3, p4, p5)
assert_equal(#t, 4)
assert_equal(getmetatable(t[1]), Triangle)
assert_equal(t[1].p1, p3)
assert_equal(t[1].p2, p2)
assert_equal(t[1].p3, p5)
assert_equal(getmetatable(t[2]), Triangle)
assert_equal(t[2].p1, p4)
assert_equal(t[2].p2, p3)
assert_equal(t[2].p3, p5)
assert_equal(getmetatable(t[3]), Triangle)
assert_equal(t[3].p1, p2)
assert_equal(t[3].p2, p1)
assert_equal(t[3].p3, p5)
assert_equal(getmetatable(t[4]), Triangle)
assert_equal(t[4].p1, p1)
assert_equal(t[4].p2, p4)
assert_equal(t[4].p3, p5)
end)
should('return 3 triangles for those 4 vertices', function()
local p1, p2, p3, p4 = Point(0,0), Point(200,1), Point(400,0), Point(300,5)
local t = Delaunay.triangulate(p1, p2, p3, p4)
assert_equal(#t, 3)
assert_equal(getmetatable(t[1]), Triangle)
assert_equal(t[1].p1, p1)
assert_equal(t[1].p2, p2)
assert_equal(t[1].p3, p3)
assert_equal(getmetatable(t[2]), Triangle)
assert_equal(t[2].p1, p3)
assert_equal(t[2].p2, p2)
assert_equal(t[2].p3, p4)
assert_equal(getmetatable(t[3]), Triangle)
assert_equal(t[3].p1, p2)
assert_equal(t[3].p2, p1)
assert_equal(t[3].p3, p4)
end)
end)
|
-- Automatically generated packer.nvim plugin loader code
if vim.api.nvim_call_function('has', {'nvim-0.5'}) ~= 1 then
vim.api.nvim_command('echohl WarningMsg | echom "Invalid Neovim version for packer.nvim! | echohl None"')
return
end
vim.api.nvim_command('packadd packer.nvim')
local no_errors, error_msg = pcall(function()
local time
local profile_info
local should_profile = false
if should_profile then
local hrtime = vim.loop.hrtime
profile_info = {}
time = function(chunk, start)
if start then
profile_info[chunk] = hrtime()
else
profile_info[chunk] = (hrtime() - profile_info[chunk]) / 1e6
end
end
else
time = function(chunk, start) end
end
local function save_profiles(threshold)
local sorted_times = {}
for chunk_name, time_taken in pairs(profile_info) do
sorted_times[#sorted_times + 1] = {chunk_name, time_taken}
end
table.sort(sorted_times, function(a, b) return a[2] > b[2] end)
local results = {}
for i, elem in ipairs(sorted_times) do
if not threshold or threshold and elem[2] > threshold then
results[i] = elem[1] .. ' took ' .. elem[2] .. 'ms'
end
end
_G._packer = _G._packer or {}
_G._packer.profile_output = results
end
time([[Luarocks path setup]], true)
local package_path_str = "/Users/yjqpro/.cache/nvim/packer_hererocks/2.1.0-beta3/share/lua/5.1/?.lua;/Users/yjqpro/.cache/nvim/packer_hererocks/2.1.0-beta3/share/lua/5.1/?/init.lua;/Users/yjqpro/.cache/nvim/packer_hererocks/2.1.0-beta3/lib/luarocks/rocks-5.1/?.lua;/Users/yjqpro/.cache/nvim/packer_hererocks/2.1.0-beta3/lib/luarocks/rocks-5.1/?/init.lua"
local install_cpath_pattern = "/Users/yjqpro/.cache/nvim/packer_hererocks/2.1.0-beta3/lib/lua/5.1/?.so"
if not string.find(package.path, package_path_str, 1, true) then
package.path = package.path .. ';' .. package_path_str
end
if not string.find(package.cpath, install_cpath_pattern, 1, true) then
package.cpath = package.cpath .. ';' .. install_cpath_pattern
end
time([[Luarocks path setup]], false)
time([[try_loadstring definition]], true)
local function try_loadstring(s, component, name)
local success, result = pcall(loadstring(s), name, _G.packer_plugins[name])
if not success then
vim.schedule(function()
vim.api.nvim_notify('packer.nvim: Error running ' .. component .. ' for ' .. name .. ': ' .. result, vim.log.levels.ERROR, {})
end)
end
return result
end
time([[try_loadstring definition]], false)
time([[Defining packer_plugins]], true)
_G.packer_plugins = {
["asyncrun.vim"] = {
config = { " vim.g.asyncrun_open = 10\n " },
load_after = {
["asynctasks.vim"] = true
},
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/asyncrun.vim",
url = "https://github.com/skywind3000/asyncrun.vim"
},
["asynctasks.vim"] = {
after = { "asyncrun.vim" },
commands = { "AsyncRun", "AsyncStop", "AsyncTask", "AsyncTaskEdit" },
loaded = false,
needs_bufread = false,
only_cond = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/asynctasks.vim",
url = "https://github.com/skywind3000/asynctasks.vim"
},
["cmp-nvim-lsp"] = {
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/cmp-nvim-lsp",
url = "https://github.com/hrsh7th/cmp-nvim-lsp"
},
["gruvbox.nvim"] = {
config = { ' vim.g.gruvbox_invert_selection=0\n vim.cmd("colorscheme gruvbox")\n ' },
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/gruvbox.nvim",
url = "https://github.com/ellisonleao/gruvbox.nvim"
},
["lualine.nvim"] = {
config = { " require('config.lualine')\n " },
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/lualine.nvim",
url = "https://github.com/hoob3rt/lualine.nvim"
},
["lush.nvim"] = {
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/lush.nvim",
url = "https://github.com/rktjmp/lush.nvim"
},
["nvim-autopairs"] = {
config = { "\t\trequire('nvim-autopairs').setup{}\n\t\t" },
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/nvim-autopairs",
url = "https://github.com/windwp/nvim-autopairs"
},
["nvim-cmp"] = {
config = { " require('cmp').setup{\n sources = {\n { name = 'nvim_lsp'}\n }\n }\n " },
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/nvim-cmp",
url = "https://github.com/hrsh7th/nvim-cmp"
},
["nvim-comment"] = {
config = { " require('nvim_comment').setup {}\n " },
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/nvim-comment",
url = "https://github.com/terrortylor/nvim-comment"
},
["nvim-lspconfig"] = {
config = { " require('config.nvim-lspconfig')\n " },
loaded = false,
needs_bufread = false,
only_cond = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/nvim-lspconfig",
url = "https://github.com/neovim/nvim-lspconfig"
},
["nvim-web-devicons"] = {
config = { " require'nvim-web-devicons'.setup {}\n " },
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/nvim-web-devicons",
url = "https://github.com/kyazdani42/nvim-web-devicons"
},
["packer.nvim"] = {
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/packer.nvim",
url = "https://github.com/wbthomason/packer.nvim"
},
["plenary.nvim"] = {
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/plenary.nvim",
url = "https://github.com/nvim-lua/plenary.nvim"
},
["sqlite.lua"] = {
config = { " if vim.fn.has('win32') ~= 0 then\n vim.g.sqlite_clib_path = \"d:/libs/sqlite/sqlite3.dll\"\n end\n " },
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/sqlite.lua",
url = "https://github.com/tami5/sqlite.lua"
},
["telescope-frecency.nvim"] = {
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/telescope-frecency.nvim",
url = "https://github.com/nvim-telescope/telescope-frecency.nvim",
wants = { "sqlite.lua" }
},
["telescope-fzf-native.nvim"] = {
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/telescope-fzf-native.nvim",
url = "https://github.com/nvim-telescope/telescope-fzf-native.nvim"
},
["telescope.nvim"] = {
commands = { "Telescope" },
config = { "\t\t require('config.telescope')\n\t\t " },
loaded = false,
needs_bufread = true,
only_cond = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/telescope.nvim",
url = "https://github.com/nvim-telescope/telescope.nvim",
wants = { "plenary.nvim", "telescope-fzf-native.nvim", "telescope-frecency.nvim" }
},
["vim-abolish"] = {
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/vim-abolish",
url = "https://github.com/tpope/vim-abolish"
},
["vim-clang-format"] = {
commands = { "ClangFormat" },
config = { " vim.g['clang_format#auto_format'] = 0\n vim.g['clang_format#code_style'] = 'chromium'\n vim.g['clang_format#style_options'] = {SortIncludes = 'false'}\n " },
loaded = false,
needs_bufread = false,
only_cond = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-clang-format",
url = "https://github.com/rhysd/vim-clang-format"
},
["vim-dirvish"] = {
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/vim-dirvish",
url = "https://github.com/justinmk/vim-dirvish"
},
["vim-fugitive"] = {
commands = { "Git", "G" },
loaded = false,
needs_bufread = true,
only_cond = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-fugitive",
url = "https://github.com/tpope/vim-fugitive"
},
["vim-rooter"] = {
config = { " vim.g.rooter_silent_chdir = 1\n vim.g.rooter_patterns = {'.git', '.root'}\n\t\t" },
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-rooter",
url = "https://github.com/airblade/vim-rooter"
},
["vim-startuptime"] = {
commands = { "StartupTime" },
loaded = false,
needs_bufread = false,
only_cond = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-startuptime",
url = "https://github.com/dstein64/vim-startuptime"
},
["vim-surround"] = {
loaded = true,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/start/vim-surround",
url = "https://github.com/tpope/vim-surround"
},
["vim-textobj-parameter"] = {
load_after = {
["vim-textobj-user"] = true
},
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-textobj-parameter",
url = "https://github.com/sgur/vim-textobj-parameter"
},
["vim-textobj-user"] = {
after = { "vim-textobj-parameter" },
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-textobj-user",
url = "https://github.com/kana/vim-textobj-user"
},
["vim-unimpaired"] = {
loaded = false,
needs_bufread = false,
path = "/Users/yjqpro/.local/share/nvim/site/pack/packer/opt/vim-unimpaired",
url = "https://github.com/tpope/vim-unimpaired"
}
}
time([[Defining packer_plugins]], false)
-- Setup for: vim-textobj-user
time([[Setup for vim-textobj-user]], true)
try_loadstring("\27LJ\2\nS\0\0\3\0\4\0\a6\0\0\0'\2\1\0B\0\2\0029\0\2\0'\2\3\0B\0\2\1K\0\1\0\21vim-textobj-user\21packer_lazy_load\nutils\frequire\0", "setup", "vim-textobj-user")
time([[Setup for vim-textobj-user]], false)
-- Setup for: vim-unimpaired
time([[Setup for vim-unimpaired]], true)
try_loadstring("\27LJ\2\nQ\0\0\3\0\4\0\a6\0\0\0'\2\1\0B\0\2\0029\0\2\0'\2\3\0B\0\2\1K\0\1\0\19vim-unimpaired\21packer_lazy_load\nutils\frequire\0", "setup", "vim-unimpaired")
time([[Setup for vim-unimpaired]], false)
-- Config for: nvim-web-devicons
time([[Config for nvim-web-devicons]], true)
require'nvim-web-devicons'.setup {}
time([[Config for nvim-web-devicons]], false)
-- Config for: nvim-cmp
time([[Config for nvim-cmp]], true)
require('cmp').setup{
sources = {
{ name = 'nvim_lsp'}
}
}
time([[Config for nvim-cmp]], false)
-- Config for: nvim-autopairs
time([[Config for nvim-autopairs]], true)
require('nvim-autopairs').setup{}
time([[Config for nvim-autopairs]], false)
-- Config for: nvim-comment
time([[Config for nvim-comment]], true)
require('nvim_comment').setup {}
time([[Config for nvim-comment]], false)
-- Config for: lualine.nvim
time([[Config for lualine.nvim]], true)
require('config.lualine')
time([[Config for lualine.nvim]], false)
-- Config for: gruvbox.nvim
time([[Config for gruvbox.nvim]], true)
vim.g.gruvbox_invert_selection=0
vim.cmd("colorscheme gruvbox")
time([[Config for gruvbox.nvim]], false)
-- Command lazy-loads
time([[Defining lazy-load commands]], true)
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file AsyncRun lua require("packer.load")({'asynctasks.vim'}, { cmd = "AsyncRun", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file AsyncStop lua require("packer.load")({'asynctasks.vim'}, { cmd = "AsyncStop", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file AsyncTask lua require("packer.load")({'asynctasks.vim'}, { cmd = "AsyncTask", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file AsyncTaskEdit lua require("packer.load")({'asynctasks.vim'}, { cmd = "AsyncTaskEdit", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file Git lua require("packer.load")({'vim-fugitive'}, { cmd = "Git", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file G lua require("packer.load")({'vim-fugitive'}, { cmd = "G", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file StartupTime lua require("packer.load")({'vim-startuptime'}, { cmd = "StartupTime", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file Telescope lua require("packer.load")({'telescope.nvim'}, { cmd = "Telescope", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
pcall(vim.cmd, [[command -nargs=* -range -bang -complete=file ClangFormat lua require("packer.load")({'vim-clang-format'}, { cmd = "ClangFormat", l1 = <line1>, l2 = <line2>, bang = <q-bang>, args = <q-args>, mods = "<mods>" }, _G.packer_plugins)]])
time([[Defining lazy-load commands]], false)
vim.cmd [[augroup packer_load_aucmds]]
vim.cmd [[au!]]
-- Event lazy-loads
time([[Defining lazy-load event autocommands]], true)
vim.cmd [[au BufReadPre * ++once lua require("packer.load")({'nvim-lspconfig'}, { event = "BufReadPre *" }, _G.packer_plugins)]]
time([[Defining lazy-load event autocommands]], false)
-- Function lazy-loads
time([[Defining lazy-load function autocommands]], true)
vim.cmd[[au FuncUndefined FindRootDirectory ++once lua require("packer.load")({'vim-rooter'}, {}, _G.packer_plugins)]]
time([[Defining lazy-load function autocommands]], false)
vim.cmd("augroup END")
if should_profile then save_profiles() end
end)
if not no_errors then
vim.api.nvim_command('echohl ErrorMsg | echom "Error in packer_compiled: '..error_msg..'" | echom "Please check your config for correctness" | echohl None')
end
|
--
-- Copyright (c) 2022 outdead.
-- Use of this source code is governed by the MIT license
-- that can be found in the LICENSE file.
--
-- LastDay mod created for Last Day server.
--
LDMainOptions = {
Original = {
create = MainOptions.create
}
}
LDMainOptions.create = function(self)
LDMainOptions.Original.create(self)
for optID, gameOption in pairs(self.gameOptions.options) do
if gameOption.name == "aimOutline" and SandboxVars.LastDay.DisableAimOutline then
gameOption.control.options[2] = nil
gameOption.control.options[3] = nil
end
end
end
function LDMainOptions.init()
MainOptions.create = LDMainOptions.create;
end
|
--X・Y・Zコンバイン
--
--Script by JoyJ
function c101107061.initial_effect(c)
--Activate
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_ACTIVATE)
e0:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e0)
--spsummon from deck
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(101107061,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetRange(LOCATION_SZONE)
e1:SetCode(EVENT_REMOVE)
e1:SetCountLimit(1,101107061)
e1:SetCondition(c101107061.spcon)
e1:SetTarget(c101107061.sptg)
e1:SetOperation(c101107061.spop)
c:RegisterEffect(e1)
--spsummon from removed
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,101107061+100)
e2:SetCost(c101107061.sprcost)
e2:SetTarget(c101107061.sprtg)
e2:SetOperation(c101107061.sprop)
c:RegisterEffect(e2)
end
function c101107061.cfilter(c,tp)
return c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_LIGHT)
and c:IsType(TYPE_UNION) and c:IsPreviousControler(tp)
end
function c101107061.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c101107061.cfilter,1,nil,tp)
end
function c101107061.spfilter(c,e,tp)
return c:IsCode(62651957,65622692,64500000) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c101107061.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101107061.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c101107061.spop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c101107061.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if #g>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c101107061.sprcfilter(c,tp)
return c:IsFaceup() and c:IsType(TYPE_FUSION) and c:IsAbleToExtraAsCost() and Duel.GetMZoneCount(tp,c)>0
end
function c101107061.sprcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101107061.sprcfilter,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c101107061.sprcfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
Duel.SendtoDeck(g,nil,2,REASON_COST)
end
function c101107061.sprtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c101107061.spfilter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
local max=2
if Duel.IsPlayerAffectedByEffect(tp,59822133) or Duel.GetMZoneCount(tp)<2 then max=1 end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,max,tp,LOCATION_REMOVED)
end
function c101107061.sprop(e,tp,eg,ep,ev,re,r,rp)
local max=2
if Duel.GetMZoneCount(tp)<1 then return end
if Duel.IsPlayerAffectedByEffect(tp,59822133) or Duel.GetMZoneCount(tp)<2 then max=1 end
local g=Duel.GetMatchingGroup(c101107061.spfilter,tp,LOCATION_REMOVED,0,nil,e,tp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:SelectSubGroup(tp,aux.dncheck,false,1,max)
if sg then
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
|
---
-- The main program logic flow.
--
-- Bootstraps the core APIs used by the rest of the application, and implements
-- the program entry point and overall execution flow.
---
local options = require('options')
local path = require('path')
local premake = require('premake')
local m = {}
m.PROJECT_SCRIPT_NAME = 'premake6.lua'
m.SYSTEM_SCRIPT_NAME = 'premake6-system.lua'
doFile('./core_fields.lua', m)
doFile('./core_options.lua', m)
doFile('./core_modules.lua', m)
premake.snapshotStateForTesting()
-- Bootstrapping functions, in execution order
function m.runSystemScript()
local name = options.valueOf('--systemscript')
if name ~= m.SYSTEM_SCRIPT_NAME and not os.isFile(name) then
error(string.format('no such file `%s`', name), 0)
end
doFileOpt(name)
end
function m.locateProjectScript()
local name = options.valueOf('--file')
if name ~= m.PROJECT_SCRIPT_NAME and not os.isFile(name) then
error(string.format('no such file `%s`', name), 0)
end
local location = premake.locateScript(name) or name
_PREMAKE.MAIN_SCRIPT = location
_PREMAKE.MAIN_SCRIPT_DIR = path.getDirectory(location)
end
function m.runProjectScript()
doFileOpt(_PREMAKE.MAIN_SCRIPT)
end
function m.validateCommandLineOptions()
local ok, err = options.validate()
if not ok then
error(err, 0)
end
end
function m.executeCommandLineOptions()
if #_ARGS > 0 then
for trigger, value in options.each() do
_G._ACTION = trigger
options.execute(trigger, value)
end
else
printf('Type `%s --help` for help', path.getName(_ARGS[0]))
end
end
---
-- Main program entry point
---
m.steps = {
m.runSystemScript,
m.locateProjectScript,
m.runProjectScript,
m.validateCommandLineOptions,
m.executeCommandLineOptions
}
function m.run()
premake.callArray(m.steps)
end
return m
|
local curSong = nil
local start = math.max(0,GHETTOGAMESTATE:getLastPlayedSecond())
local delay = 1
local startFromPreview = true
local loop = themeConfig:get_data().global.SongPreview == 2
local curPath = ""
local sampleStart = 0
local musicLength = 0
GHETTOGAMESTATE:setLastPlayedSecond(0)
-- SongPreview == 1 (SM STYLE)
-- Disable this stuff, loops from SampleStart to SampleStart+SampleLength
-- SongPreview == 2 (current osu!)
-- Loops from SampleStart to end of the song.
-- If a player exits midway in a song, play from last point to end of song, then loop from SampleStart.
-- SongPreview == 3 (old osu!)
-- Play from SampleStart to end of the song. then Loop from the start of the song to the end.
-- If a player exits midway in a song, play from last point to end of song, then loop from start.
local deltaSum = 0
local function playMusic(self, delta)
deltaSum = deltaSum + delta
if deltaSum > delay then
deltaSum = 0
if curSong and curPath then
if startFromPreview then -- When starting from preview point
SOUND:PlayMusicPart(curPath,sampleStart,musicLength-sampleStart,2,2,loop,true,true)
if themeConfig:get_data().global.SongPreview == 3 then
startFromPreview = false
end
else -- When starting from start of from exit point.
SOUND:PlayMusicPart(curPath,start,musicLength-start,2,2,false,true,false)
start = 0
if themeConfig:get_data().global.SongPreview == 2 then
startFromPreview = true
end
end
end
end
end
local t = Def.ActorFrame{
InitCommand = function(self)
if themeConfig:get_data().global.SongPreview ~= 1 then
self:SetUpdateFunction(playMusic)
end
end;
CurrentSongChangedMessageCommand = function(self)
SOUND:StopMusic()
deltaSum = 0
curSong = GAMESTATE:GetCurrentSong()
if curSong ~= nil then
curPath = curSong:GetMusicPath()
if not curPath then
SCREENMAN:SystemMessage("Invalid music file path.")
return
end
sampleStart = curSong:GetSampleStart()
musicLength = curSong:MusicLengthSeconds()
startFromPreview = start == 0
end
end;
}
return t
|
local Native = require('lib.native.native')
---@class GameEvent
local GameEvent = {
Victory = Native.ConvertGameEvent(0), --EVENT_GAME_VICTORY
EndLevel = Native.ConvertGameEvent(1), --EVENT_GAME_END_LEVEL
VariableLimit = Native.ConvertGameEvent(2), --EVENT_GAME_VARIABLE_LIMIT
StateLimit = Native.ConvertGameEvent(3), --EVENT_GAME_STATE_LIMIT
TimerExpired = Native.ConvertGameEvent(4), --EVENT_GAME_TIMER_EXPIRED
EnterRegion = Native.ConvertGameEvent(5), --EVENT_GAME_ENTER_REGION
LeaveRegion = Native.ConvertGameEvent(6), --EVENT_GAME_LEAVE_REGION
TrackableHit = Native.ConvertGameEvent(7), --EVENT_GAME_TRACKABLE_HIT
TrackableTrack = Native.ConvertGameEvent(8), --EVENT_GAME_TRACKABLE_TRACK
ShowSkill = Native.ConvertGameEvent(9), --EVENT_GAME_SHOW_SKILL
BuildSubmenu = Native.ConvertGameEvent(10), --EVENT_GAME_BUILD_SUBMENU
Loaded = Native.ConvertGameEvent(256), --EVENT_GAME_LOADED
TournamentFinishSoon = Native.ConvertGameEvent(257), --EVENT_GAME_TOURNAMENT_FINISH_SOON
TournamentFinishNow = Native.ConvertGameEvent(258), --EVENT_GAME_TOURNAMENT_FINISH_NOW
Save = Native.ConvertGameEvent(259), --EVENT_GAME_SAVE
CustomUiFrame = Native.ConvertGameEvent(310), --EVENT_GAME_CUSTOM_UI_FRAME
}
return GameEvent
|
--[[
Pixel Vision 8 - New Template Script
Copyright (C) 2017, Pixel Vision 8 (http://pixelvision8.com)
Created by Jesse Freeman (@jessefreeman)
This project was designed to display some basic instructions when you create
a new tool. Simply delete the following code and implement your own Init(),
Update() and Draw() logic.
Learn more about making Pixel Vision 8 games at https://www.gitbook.com/@pixelvision8
]]--
-- Load in the editor framework script to access tool components
LoadScript("sb-sprites")
LoadScript("editor-ui")
-- The Init() method is part of the game's lifecycle and called a game starts. We are going to
-- use this method to configure background color, ScreenBufferChip and draw a text box.
function Init()
BackgroundColor(22)
-- Get a reference to the Editor UI
editorUI = EditorUI:Init()
titleData = editorUI:CreateText({x = 8, y = 32}, "UI Demo")
-- We are going to render the message in a box as tiles.
messageData = editorUI:CreateText({x = 8, y = 48, w = 248}, "This project shows off how to use the GameCreator's UI components.")
toolTipData = editorUI:CreateText({x = 8, y = 224}, "Tool tip message goes here.", "system-font", 24, - 4)
-- Configure hSlider
hSliderData = editorUI:CreateSlider(1, {x = 8, y = 112, w = 112, h = 8}, "hsliderhandle", "This is a horizontal slider.", true)
hSliderData.onAction = OnValueChange
vSliderData = editorUI:CreateSlider(11, {x = 240, y = 104, w = 8, h = 72}, "vsliderhandle", "This is a vertical slider")
vSliderData.onAction = OnValueChange
-- Buttons
backBtnData = editorUI:CreateButton(8, {x = 192, y = 184}, "stepperback", "This is the picker back button.")
backBtnData.onAction = OnPickerBack
nextBtnData = editorUI:CreateButton(10, {x = 232, y = 184}, "steppernext", "This is the picker next button.")
nextBtnData.onAction = OnPickerNext
-- Toggle Button
muteBtnData = editorUI:CreateToggleButton(3, {x = 168, y = 104}, "mute", "This is a toggle button.")
muteBtnData.hitRect = {x = 168 + 2, y = 104 + 4, w = 28, h = 15}
muteBtnData.onAction = OnMute
-- Create a toggle group for the pagination buttons
paginationBtnData = editorUI:CreateToggleGroup(5)
paginationBtnData.onAction = OnPage
-- Create pagination buttons
for i = 1, 4 do
local offsetX = ((i - 1) * 8) + 40
local rect = {x = offsetX, y = 168, w = 8, h = 16}
editorUI:ToggleGroupButton(paginationBtnData, rect, "pagebutton" .. tostring(i), "This is page button " .. tostring(i))
end
editorUI:SelectToggleButton(paginationBtnData, 1, false)
-- Input fields
volumeInputData = editorUI:CreateInputField(2, {x = 136, y = 112, w = 24}, "0", "The volume is set to %02s. Click to edit it.", "number")
volumeInputData.min = 0
volumeInputData.max = 100
volumeInputData.disabledColorOffset = 8
volumeInputData.onAction = OnVolumeFieldUpdate
volumeInputData.colorOffset = 32
volumeInputData.disabledColorOffset = 34
nameInputData = editorUI:CreateInputField(6, {x = 16, y = 192, w = 11 * 8}, "Untitled", "Enter in a file name to this string input field.", "file")
nameInputData.colorOffset = 32
pickerInputData = editorUI:CreateInputField(9, {x = 216, y = 192, w = 8}, "1", "You are on page %s of 9. Enter new page number.", "number")
pickerInputData.min = 1
pickerInputData.max = 9
pickerInputData.onAction = UpdatePickerButtons
pickerInputData.colorOffset = 32
editorUI:ChangeInputField(pickerInputData, 1)
inputAreaData = editorUI:CreateInputArea(4, {x = 16, y = 136, w = 208, h = 32}, "Lorem ipsum dolor sit amet\n, consectetur adipiscing elit. \nVivamus ultricies nunc ex, \nid commodo mauris iaculis nec.", "Text editor help")
inputAreaData.colorOffset = 32
-- Check boxes
checkboxGroupData = editorUI:CreateToggleGroup(7, false)
checkboxGroupData.onAction = OnCheckbox
editorUI:ToggleGroupButton(checkboxGroupData, {x = 120, y = 184, w = 8, h = 8}, "checkbox", "This is checkbox 1.")
editorUI:ToggleGroupButton(checkboxGroupData, {x = 160, y = 184, w = 8, h = 8}, "checkbox", "This is checkbox 2.")
editorUI:ToggleGroupButton(checkboxGroupData, {x = 120, y = 192, w = 8, h = 8}, "checkbox", "This is checkbox 3.")
editorUI:ToggleGroupButton(checkboxGroupData, {x = 160, y = 192, w = 8, h = 8}, "checkbox", "This is checkbox 4.")
end
function OnVolumeFieldUpdate(text)
local value = tonumber(text / 100)
editorUI:ChangeSlider(hSliderData, value, false)
editorUI:ChangeSlider(vSliderData, value, false)
end
function OnValueChange(value)
--print("New value", value)
editorUI:ChangeInputField(volumeInputData, tostring(value * 100))
if(hSliderData.value ~= value) then
editorUI:ChangeSlider(hSliderData, value)
end
if(vSliderData.value ~= value) then
editorUI:ChangeSlider(vSliderData, value)
end
end
function OnPickerBack()
local value = tonumber(pickerInputData.text)
OnPageChange(value - 1)
end
function OnPickerNext()
local value = tonumber(pickerInputData.text)
OnPageChange(value + 1)
end
function OnPageChange(value)
if(value < pickerInputData.min) then
value = pickerInputData.min
elseif(value > pickerInputData.max) then
value = pickerInputData.max
end
local stringValue = tostring(value)
if(pickerInputData.text ~= stringValue) then
editorUI:ChangeInputField(pickerInputData, stringValue)
end
UpdatePickerButtons(stringValue)
end
function OnCheckbox(value)
local selections = editorUI:ToggleGroupSelections(checkboxGroupData)
local total = #selections
local message = "There are now " .. total .. " selected checkboxes"
if(total > 0) then
message = message .. ": " .. table.concat(selections, ",")
end
-- pixelVisionOS:DisplayMessage(message ..".")
end
function UpdatePickerButtons(text)
if(text == "") then
text = "0"
end
-- convert the text value to a number
local value = tonumber(text)
-- update buttons
editorUI:Enable(backBtnData, value > pickerInputData.min)
editorUI:Enable(nextBtnData, value < pickerInputData.max)
end
function OnMute(value)
-- Enable or disable the volume input field and sliders based on the mute value
editorUI:Enable(volumeInputData, not value)
editorUI:Enable(hSliderData, not value)
editorUI:Enable(vSliderData, not value)
end
function OnPage(value)
-- pixelVisionOS:DisplayMessage("Page " .. value .. " selected")
end
-- The Update() method is part of the game's life cycle. The engine calls Update() on every frame
-- before the Draw() method. It accepts one argument, timeDelta, which is the difference in
-- milliseconds since the last frame.
function Update(timeDelta)
-- This needs to be the first call to make sure all of the OS and editor UI is updated first
editorUI:Update(timeDelta)
-- TODO add your own update logic here
-- Update Text
editorUI:UpdateText(titleData)
editorUI:UpdateText(messageData)
editorUI:UpdateText(toolTipData)
-- Update Slider
editorUI:UpdateSlider(hSliderData)
editorUI:UpdateSlider(vSliderData)
-- Update buttons
editorUI:UpdateButton(backBtnData)
editorUI:UpdateButton(nextBtnData)
editorUI:UpdateButton(muteBtnData)
-- Update toggle groups
editorUI:UpdateToggleGroup(paginationBtnData)
editorUI:UpdateToggleGroup(checkboxGroupData)
--
editorUI:UpdateInputField(volumeInputData)
editorUI:UpdateInputField(nameInputData)
editorUI:UpdateInputField(pickerInputData)
--
editorUI:UpdateInputArea(inputAreaData)
end
-- The Draw() method is part of the game's life cycle. It is called after Update() and is where
-- all of our draw calls should go. We'll be using this to render sprites to the display.
function Draw()
-- We can use the RedrawDisplay() method to clear the screen and redraw the tilemap in a
-- single call.
RedrawDisplay()
-- We have to manually display the tool tip
local toolTip = ""
if(editorUI.inFocusUI ~= nil and editorUI.inFocusUI.toolTip ~= nil) then
toolTip = editorUI.inFocusUI.toolTip
end
editorUI:ChangeText(toolTipData, string.lpad(toolTip, 60, " "))
-- The UI should be the last thing to draw after your own custom draw calls
editorUI:Draw()
end
|
--[[
global table BCC_IdleTimer
function BCC_IdleTimer_OnUpdate(time)
function BCC_IdleTimer_Reset(void)
function BCC_IdleTimer_Zero(void)
--]]
-- /////////////////////////////////////////////////////////////////////////////
-- /////////////////////////////////////////////////////////////////////////////
BCC_IdleTimer = {
-- global variable for tracking player idle time.
-- saved: no
CurTime = 0,
NextTime = 0
}
-- /////////////////////////////////////////////////////////////////////////////
-- /////////////////////////////////////////////////////////////////////////////
function BCC_IdleTimer_OnUpdate(time)
BCC_IdleTimer.CurTime = BCC_IdleTimer.CurTime + time
if(BCC_IdleTimer.CurTime > BCC_IdleTimer.NextTime) then
BCC_SpellMessage_OnSpellCast("idle timer")
BCC_IdleTimer_Reset()
end
end
-- /////////////////////////////////////////////////////////////////////////////
-- /////////////////////////////////////////////////////////////////////////////
function BCC_IdleTimer_Reset()
local mult
-- be more spammy in an instance than in the open world to let people know
-- that you are bored when they waste your time in instances.
if(IsInInstance()) then mult = 1
else mult = BCCDB.IdleWorldMult end
BCC_IdleTimer.CurTime = 0
BCC_IdleTimer.NextTime = math.random(
(((BCCDB.IdleProc * mult)) * 60),
(((BCCDB.IdleProc * mult) + 1) * 60)
)
end
function BCC_IdleTimer_Zero()
BCC_IdleTimer.CurTime = 0
end
|
local stageStartX = love.graphics.getWidth() / 4
local stageStartY = 0
local stageEndX = love.graphics.getWidth()
local stageEndY = love.graphics.getHeight() - love.graphics.getHeight() / 3
local stageWidth = love.graphics.getWidth() - stageStartX
local stageHeight = love.graphics.getHeight() - love.graphics.getHeight() / 3
local stageMidX = stageWidth / 2 + stageStartX
local stageMidY = stageHeight / 2 + stageStartY
function getStageMouseX()
return love.mouse.getX() - stageMidX
end
function getStageMouseY()
return stageMidY - love.mouse.getY()
end
function decorateStage()
local font = love.graphics.newFont(14)
local function drawLines()
love.graphics.setColor{255, 0, 0, 140}
love.graphics.line(stageStartX, stageMidY, stageEndX, stageMidY)
love.graphics.line(stageMidX, stageStartY, stageMidX, stageEndY)
end
local function drawMouseCoord()
love.graphics.setColor{255,255,255,230}
love.graphics.setFont(font)
love.graphics.print("Mouse: (" .. getStageMouseX() .. ", " .. getStageMouseY() .. ")", stageStartX + 10, stageStartY + 3)
end
local function drawHelp()
love.graphics.setColor{255,255,255,230}
love.graphics.setFont(font)
love.graphics.print("wasd : move active box", stageStartX + 10, stageEndY - 20 - 16 * 3)
love.graphics.print("ujhk: resize active box", stageStartX + 10, stageEndY - 20 - 16 * 2)
love.graphics.print("mouse click: select active box", stageStartX + 10, stageEndY - 20 - 16 * 1)
end
local function drawFrameImage()
if currentFrameImage then
local rx = stageMidX - currentFrameImage:getWidth() / 2
local ry = stageMidY - currentFrameImage:getHeight() / 2
love.graphics.draw(currentFrameImage, rx, ry)
end
end
local function drawSingleBox(x, y, w, h, c1, c2)
love.graphics.setColor(c1)
love.graphics.rectangle("line", x + stageMidX, stageMidY - y, w, h)
love.graphics.setColor(c2)
love.graphics.rectangle("fill", x + stageMidX, stageMidY - y, w, h)
end
-- I know, I know, all hacked up code, but what the h*ll
local inactive_alpha = 80
local active_alpha = 120
local function drawActiveHitBox(x,y,w,h)
drawSingleBox(x,y,w,h,{240,10,10,active_alpha + 40},{240,10,10,active_alpha})
end
-- i need to refactor this
local function drawInactiveHitBox(x,y,w,h)
drawSingleBox(x,y,w,h,{240,10,10,inactive_alpha + 40},{240,10,10,inactive_alpha})
end
local function drawActiveHurtBox(x,y,w,h)
drawSingleBox(x,y,w,h,{10,240,10,active_alpha + 40},{10,240,10,active_alpha})
end
local function drawInactiveHurtBox(x,y,w,h)
drawSingleBox(x,y,w,h,{10,240,10,inactive_alpha + 40},{10,240,10,inactive_alpha})
end
local function drawActiveCollisionBox(x,y,w,h)
drawSingleBox(x,y,w,h,{240,240,240,active_alpha + 40},{240,240,240,active_alpha})
end
local function drawInactiveCollisionBox(x,y,w,h)
drawSingleBox(x,y,w,h,{240,240,240,inactive_alpha + 40},{240,240,240,inactive_alpha})
end
local function drawAllBoxes()
for k,v in pairs(getCurrentWhiteBoxes()) do
if v.active then
drawActiveCollisionBox(v.x,v.y,v.w,v.h)
else
drawInactiveCollisionBox(v.x,v.y,v.w,v.h)
end
end
for k,v in pairs(getCurrentGreenBoxes()) do
if v.active then
drawActiveHurtBox(v.x,v.y,v.w,v.h)
else
drawInactiveHurtBox(v.x,v.y,v.w,v.h)
end
end
for k,v in pairs(getCurrentRedBoxes()) do
if v.active then
drawActiveHitBox(v.x,v.y,v.w,v.h)
else
drawInactiveHitBox(v.x,v.y,v.w,v.h)
end
end
end
drawLines()
drawMouseCoord()
drawHelp()
drawFrameImage()
if currentFrameData then
drawAllBoxes()
end
end
stage = {}
function stage.getActiveBox()
local active = nil
if not currentFrameData then
return nil
end
for k,v in pairs(getCurrentGreenBoxes()) do
if v.active then
return v
end
end
for k,v in pairs(getCurrentRedBoxes()) do
if v.active then
return v
end
end
for k,v in pairs(getCurrentWhiteBoxes()) do
if v.active then
return v
end
end
end
function tableMerge(t1, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
if type(t1[k] or false) == "table" then
tableMerge(t1[k] or {}, t2[k] or {})
else
t1[k] = v
end
else
t1[k] = v
end
end
return t1
end
function stage.getAllBoxes()
return tableMerge(getCurrentGreenBoxes(), getCurrentRedBoxes())
end
function stage.mousereleased(x,y,button)
end
function stage.mouseWithinStage()
local wx = (love.mouse.getX() > stageStartX and love.mouse.getX() < (stageStartX + stageWidth))
local wy = (love.mouse.getY() > stageStartY and love.mouse.getY() < (stageStartY + stageHeight))
return wx and wy
end
function stage.onMouseClick(x,y)
if currentFrameData and stage.mouseWithinStage() then
local fx = getStageMouseX()
local fy = getStageMouseY()
print("x " .. tostring(fx) .. "| y" .. tostring(fy))
local active_one = nil
for k,v in pairs(getCurrentGreenBoxes()) do
local rect = v
v.active = false
print(rect.x .. " " .. rect.y)
if (fx > rect.x and fx < (rect.x + rect.w)) and (fy < rect.y and fy > (rect.y - rect.h)) then
print("within find range")
v.active = true
print(v == rect)
end
end
for k,v in pairs(getCurrentRedBoxes()) do
local rect = v
v.active = false
print(rect.x .. " " .. rect.y)
if (fx > rect.x and fx < (rect.x + rect.w)) and (fy < rect.y and fy > (rect.y - rect.h)) then
print("within find range")
v.active = true
print(v == rect)
end
end
for k,v in pairs(getCurrentWhiteBoxes()) do
local rect = v
v.active = false
print(rect.x .. " " .. rect.y)
if (fx > rect.x and fx < (rect.x + rect.w)) and (fy < rect.y and fy > (rect.y - rect.h)) then
print("within find range")
v.active = true
print(v == rect)
end
end
if active_one then
active_one.active = true
else
print("did not find active")
end
refreshBoxList()
end
end
function stage.updateKeyStroke()
if stage.getActiveBox() then
local function updateMove()
if love.keyboard.isDown("w") then
stage.getActiveBox().y = stage.getActiveBox().y + 1
refreshBoxList()
end
if love.keyboard.isDown("s") then
stage.getActiveBox().y = stage.getActiveBox().y - 1
refreshBoxList()
end
if love.keyboard.isDown("a") then
stage.getActiveBox().x = stage.getActiveBox().x - 1
refreshBoxList()
end
if love.keyboard.isDown("d") then
stage.getActiveBox().x = stage.getActiveBox().x + 1
refreshBoxList()
end
end
local function updateResize()
if love.keyboard.isDown("u") then
stage.getActiveBox().h = stage.getActiveBox().h - 1
refreshBoxList()
end
if love.keyboard.isDown("j") then
stage.getActiveBox().h = stage.getActiveBox().h + 1
refreshBoxList()
end
if love.keyboard.isDown("h") then
stage.getActiveBox().w = stage.getActiveBox().w - 1
refreshBoxList()
end
if love.keyboard.isDown("k") then
stage.getActiveBox().w = stage.getActiveBox().w + 1
refreshBoxList()
end
end
local function updateDelete()
if love.keyboard.isDown("backspace") or love.keyboard.isDown("delete") then
deleteActiveBox()
end
end
local function updateSave()
local sys = love.keyboard.isDown("rctrl") or love.keyboard.isDown("lctrl") or love.keyboard.isDown("rgui") or love.keyboard.isDown("lgui")
if love.keyboard.isDown("s") and (sys) then
datautils.saveCurrentState()
return true
end
end
if(updateSave()) then
else
updateMove()
end
updateResize()
updateDelete()
end
end
|
-- basic functions
local type=type
local make_eval_f=function(env)
local f
local loadstring,setfenv
return function(str)
f=loadstring(str)
return f and setfenv(f,env)()
end
end
local convert=function(tp,o,p,ref)
local tmp=tp and ref[tp]
tp=type(tmp)
return tp=="function" and tmp(o,p) or (gsub(tmp,"@(.-)@",o))
end
local obj2str
obj2str=function(obj,ref)
if type(obj)~="table" then return obj end
for i,v in ipairs(obj) do
obj[i]=obj2str(obj,ref)
end
obj.VALUE=#obj>0 and table.concat(obj,"\n")
return convert(obj.TYPE,obj,nil,ref)
end
export=function(obj,path)
local str=obj2str(o)
if not path then print(str) return end
local f=path and io.open(path,"w")
if f then f:write(str); f:close() end
end
-- objs
local copy
copy=function(src,dst)
if type(src)~="table" then return src end
dst={}
for k,v in pairs(src) do
dst[k]=copy(v)
end
return dst
end
local match,tonumber=string.match,tonumber
local dir2xy=function(op)
local x,y,r,d,offset=0,0,0,0
if op then
offset=match(op,"U(%-?%d*)"); if offset then y=tonumber(offset) or 0; d=-1 end
offset=match(op,"D(%-?%d*)"); if offset then y=tonumber(offset) or 0; d=1 end
offset=match(op,"L(%-?%d*)"); if offset then x=tonumber(offset) or 0; r=-1 end
offset=match(op,"R(%-?%d*)"); if offset then x=tonumber(offset) or 0; r=1 end
end
return x,y,r,d
end
-- make functions
local type=type
make_obj=function(tp,cx,cy,rx,ry)
local o= type(tp)=="table" and copy(tp) or {TYPE=tp}
o.cx=cx or o.cx or 0; o.cy=cy or o.cy or 0; o.rx=rx or o.rx or 1; o.ry=ry or o.ry or 1;
return o
end
make_label=function(label,dir,fs)
dir=dir or "CM"
local x,y,r,d=dir2xy(dir)
align= r==1 and "start" or r==-1 and "end" or "middle"
y= d==1 and y+fs or d==0 and y+fs/2 or y
return {TYPE="label",label=label,cx=x,cy=y,align=align}
end
local POINT_FMT="%s %d %d"
local format=string.format
local CUBIC_CURVE_POINT="M %d %d C %d %d %d %d %d %d"
local QUADRATIC_CURVE_POINT="M %d %d Q %d %d %d %d"
local points2path=function(t,curve)
local n=#t
if curve and n==4 then return format(CUBIC_CURVE_POINT,t[1][1],t[1][2],t[2][1],t[2][2],t[3][1],t[3][2],t[4][1],t[4][2]) end
if curve and n==3 then return format(QUADRATIC_CURVE_POINT,t[1][1],t[1][2],t[2][1],t[2][2],t[3][1],t[3][2]) end
for i,v in ipairs(t) do
t[i]= format(POINT_FMT,i==1 and "M" or "L",unpack(v))
end
return table.concat(t," ")
end
make_path=function(pt,tp)
local curve,cls=match(tp,"^%s*C:(%S+)%s*$")
cls=cls or tp or "solid"
return {TYPE=cls,path=points2path(pt,curve)}
end
-- orgnize functions
local push=push or table.insert
append=function(p,c)
c.fs=p.fs
push(p,c)
return c
end
rank=function(dir,...)
local n=#arg
local ref,to
local x,y,r,d=dir2xy(dir)
if n>1 then
for i=1,n-1 do
ref=arg[i];to=arg[i+1]
to.cx=ref.cx+r*(ref.rx+to.rx+x);
to.cy=ref.cy+d*(ref.ry+to.ry+y);
end
end
return to
end
-- generate functions
local make_eval_f=function(t)
local loadstring,setfenv=loadstring,setfenv
local eval,f
eval=function(str)
f=loadstring("return "..str)
if f then return setfenv(f,t)() end
end
return eval
end
local gsub,concat=gsub or string.gsub,table.concat
local obj2str
obj2str=function(o)
if type(o)~="table" then return o end
local cx,cy=o.cx,o.cy
for i,v in ipairs(o) do
v.cx=v.cx+cx;v.cy=v.cy+cy;
o[i]=obj2str(v)
end
o.VALUE=#o>0 and concat(o,"\n") or ""
local tmp=shapes[o.TYPE] or shapes.rect
return (gsub(tmp,"@(.-)@",make_eval_f(o)))
end
export=function(o,path)
local str=obj2str(o)
if not path then print(str) return end
local f=path and io.open(path,"w")
if f then f:write(str); f:close() end
end
-- grammer sugars
copy_node=copy
make_svg=function(x,y,w,h,fs)
x=x or 0;
y=y or 0;
w=w or 600;
h=h or 600;
return {TYPE="SVG",cx=x+w/2,cy=y+h/2,rx=w/2,ry=h/2, fs=fs or 20}
end
make_node=function(label,tp,cx,cy,rx,ry)
local n=make_obj(tp,cx,cy,rx,ry)
n.label=label or n.label
return n
end
make_edge=function(label,p,from,to,shape,cls)
local fcx,fcy,frx,fry=from.cx,from.cy,from.rx,from.ry
local tcx,tcy,trx,try=to.cx,to.cy,to.rx,to.ry
local fs=from.fs
local pt={}
local tx,ty,align=(fcx+tcx)/2,(fcy+tcy)/2
shape=shape or "-"
cls=cls or "solid"
if shape=="-" then
pt[1]={fcx>tcx and fcx-frx or fcx+frx,fcy}
pt[2]={fcx>tcx and tcx+trx or tcx-trx,tcy}
align="middle";
elseif shape=="|" then
pt[1]={fcx,fcy>tcy and fcy-fry or fcy+fry}
pt[2]={tcx,fcy>tcy and tcy+try or tcy-try}
ty=ty+fs/2
align="start"
elseif shape=="7" then
tx,ty=tcx,fcy
pt[1]={fcx>tcx and fcx-frx or fcx+frx,fcy}
pt[2]={tcx,fcy}
pt[3]={tcx,fcy>tcy and tcy+try or tcy-try}
align="start"
elseif shape=="L" then
tx,ty=fcx,tcy
pt[1]={fcx,fcy>tcy and fcy-fry or fcy+fry}
pt[2]={fcx,tcy}
pt[3]={fcx>tcx and tcx+trx or tcx-trx,tcy}
ty=ty+fs
align="end"
elseif shape=="Z" then
pt[1]={fcx>tx and fcx-frx or fcx+frx,fcy}
pt[2]={tx,fcy}
pt[3]={tx,tcy}
pt[4]={tx>tcx and tcx+trx or tcx-trx,tcy}
ty=ty+fs/2
align="start"
elseif shape=="N" then
pt[1]={fcx,fcy>ty and fcy-fry or fcy+fry}
pt[2]={fcx,ty}
pt[3]={tcx,ty}
pt[4]={tcx,ty>tcy and tcy+try or tcy-try}
align="middle"
end
local e=make_path(pt,cls)
e.cx=tx; e.cy=ty; e.align=align;
e.label=label
return e
end
-- shape templates
shapes={
ellipse=[[<ellipse cx="@cx@" cy="@cy@" rx="@rx@" ry="@ry@" fill="url(#node)"/><text x="@cx@" y="@cy+fs/2@" stroke-width="0" fill="black" text-anchor="middle">@label or ""@</text> ]],
roundrect=[[<rect x="@cx-rx@" y="@cy-ry@" rx="10" ry="10" width="@rx+rx@" height="@ry+ry@" fill="url(#node)"/><text x="@cx@" y="@cy+fs/2@" stroke-width="0" fill="black" text-anchor="middle">@label or ""@</text>]],
rect=[[<rect x="@cx-rx@" y="@cy-ry@" width="@rx+rx@" height="@ry+ry@" fill="url(#node)"/><text x="@cx@" y="@cy+fs/2@" stroke-width="0" fill="black" text-anchor="middle">@label or ""@</text>]],
point=[[<circle cx="@cx@" cy="@cy@" r="@rx@" fill="url(#point)" />]],
solid=[[<path d = "@path@" fill = "none" stroke = "black" marker-end = "url(#arrow-head)" /><text x="@cx@" y="@cy@" stroke-width="0" fill="black" text-anchor="@align@">@label or ""@</text>]],
dashed=[[<path d = "@path@" fill = "none" stroke = "black" marker-end = "url(#arrow-head)" style="stroke-dasharray:10,3"/>]],
dotted=[[<path d = "@path@" fill = "none" stroke = "black" marker-end = "url(#arrow-head)" style="stroke-dasharray:3,3"/>]],
text=[[<text x="@cx@" y="@cy@" stroke-width="0" fill="black" text-anchor="@align@">@txt@</text>]],
img=[[<image x="@cx+rx@" y="@cy+ry@" width="@rx+rx@" height="@ry+ry@" xlink:href="@src@" />]],
group=[[@VALUE@]],
SVG=[[
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="@rx+rx@" height="@ry+ry@" version="1.1"
xmlns="http://www.w3.org/2000/svg" font-size="@fs@" stroke-width = "3" fill="white" stroke="black">
<defs>
<marker id = "arrow-head" viewBox = "0 0 20 20" refX = "20" refY = "10" markerUnits = "strokeWidth" markerWidth = "5" markerHeight = "5" stroke = "black" fill = "none" orient = "auto">
<path d = "M 0 0 L 20 10 L 0 20"/>
</marker>
<linearGradient id="node" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
<stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
</linearGradient>
<radialGradient id="point" cx="30%" cy="30%" r="50%">
<stop offset="0%" style="stop-color:rgb(255,255,255); stop-opacity:0" />
<stop offset="100%" style="stop-color:rgb(0,0,255);stop-opacity:1" />
</radialGradient>
</defs>
@VALUE@
</svg>
]],
}
|
local SWS_ADDON_NAME, StatWeightScore = ...;
local ScoreModule = StatWeightScore:NewModule(SWS_ADDON_NAME.."Score");
local SpecModule;
local StatsModule;
local GemsModule;
local ScanningTooltipModule;
local Utils;
local L;
function ScoreModule:OnInitialize()
SpecModule = StatWeightScore:GetModule(SWS_ADDON_NAME.."Spec");
StatsModule = StatWeightScore:GetModule(SWS_ADDON_NAME.."Stats");
GemsModule = StatWeightScore:GetModule(SWS_ADDON_NAME.."Gems");
ScanningTooltipModule = StatWeightScore:GetModule(SWS_ADDON_NAME.."ScanningTooltip");
Utils = StatWeightScore.Utils;
L = StatWeightScore.L;
self.Matcher = {
Stats = {
},
PreCheck = {
L["Matcher_Precheck_Equip"],
L["Matcher_Precheck_Use"],
gsub(L["Matcher_Precheck_BonusArmor"], "BONUS_ARMOR", BONUS_ARMOR)
},
Partial = {
["cdmin"] = L["Matcher_Partial_CdMin"],
["cdsec"] = L["Matcher_Partial_CdSec"]
},
Matchers = {
}
};
self:RegisterStatMatcher("Armor", function(pattern)
return gsub(pattern, "RESISTANCE0_NAME", RESISTANCE0_NAME);
end);
self:RegisterStatMatcher("DPS");
self:RegisterStatMatcher("Stat");
self:RegisterMatcher("RPPM", "rppm");
self:RegisterMatcher("RPPM2", "rppm");
self:RegisterMatcher("RPPM3", "rppm");
self:RegisterMatcher("RPPM4", "rppm");
self:RegisterMatcher("SoliumBand", "soliumband");
self:RegisterMatcher("ICD", "icd");
self:RegisterMatcher("ICD2", "icd");
self:RegisterMatcher("ICD3", "icd");
self:RegisterMatcher("InsigniaOfConquest", "insigniaofconquest");
self:RegisterMatcher("InsigniaOfConquest2", "insigniaofconquest");
self:RegisterMatcher("Use", "use");
self:RegisterMatcher("Use2", "use");
self:RegisterMatcher("Use3", "use");
self:RegisterMatcher("Use4", "use");
self:RegisterMatcher("BonusArmor", "bonusarmor", function(pattern)
return gsub(pattern, "BONUS_ARMOR", BONUS_ARMOR);
end);
self:RegisterMatcher("BlackhandTrinket", "blackhandtrinket");
self:RegisterMatcher("BlackhandTrinket2", "blackhandtrinket");
self:RegisterMatcher("BlackhandTrinket3", "blackhandtrinket");
self:RegisterMatcher("StoneOfFire", "stoneoffire");
end
function ScoreModule:RegisterStatMatcher(name, patternModFunc)
local pattern = L["Matcher_StatTooltipParser_"..name];
if(patternModFunc) then
pattern = patternModFunc(pattern);
end
pattern = Utils.UnescapeUnicode(pattern);
self.Matcher.Stats[name] = {
Pattern = pattern,
ArgOrder = Utils.SplitString(L["Matcher_StatTooltipParser_"..name.."_ArgOrder"])
};
end
function ScoreModule:RegisterMatcher(name, fx, patternModFunc)
local pattern = L["Matcher_"..name.."_Pattern"];
if(not pattern or pattern:len() == 0) then
return;
end
if(patternModFunc) then
pattern = patternModFunc(pattern);
end
pattern = Utils.UnescapeUnicode(pattern);
self.Matcher.Matchers[name] = {
Pattern = pattern,
Fx = fx,
ArgOrder = Utils.SplitString(L["Matcher_"..name.."_ArgOrder"])
};
end
local function UpdateResult(result, type, stat, averageStatValue, weight)
result.Score = result.Score + averageStatValue * weight
result[type] = {
AverageValue = averageStatValue;
Stat = stat.DisplayName;
};
end
function ScoreModule:GetStatsFromTooltip(tooltip)
local stats = {};
if(tooltip) then
for l = 1,tooltip:NumLines() do
local tooltipText = getglobal(tooltip:GetName().."TextLeft"..l);
if(tooltipText) then
local line = (tooltipText:GetText() or "");
local value, stat;
for _, matcher in pairs(self.Matcher.Stats) do
local match = Utils.Pack(line:match(matcher.Pattern));
if(match) then
local argOrder = matcher.ArgOrder;
local args = {};
for i = 1, match.n do
local argName = argOrder[i];
local argValue = match[i]
args[argName] = argValue;
end
value = args["value"];
stat = args["stat"];
break;
end
end
if(value and stat) then
local statInfo = StatsModule:GetStatInfoByDisplayName(stat);
if(statInfo) then
stats[statInfo.Key] = Utils.ToNumber(value);
end
end
end
end
end
return stats;
end
local function GetStatsFromLink(link)
return GetItemStats(link);
end
local primaryStatIndex = {
["str"] = 1,
["agi"] = 2,
["int"] = 4
};
local function GetPrimaryStatForSpec(weights)
local primaryStatValue, primaryStat;
for _, alias in ipairs({"str","agi","int"}) do
if(weights[alias]) then
primaryStatValue = UnitStat("player", primaryStatIndex[alias]);
primaryStat = alias;
break;
end
end
return primaryStat, primaryStatValue;
end
ScoreModule.Fx = {
["rppm"] = function(result, stats, weights, args)
local statInfo = StatsModule:GetStatInfoByDisplayName(args["stat"]);
if(not statInfo or not weights[statInfo.Alias]) then
return;
end
local value = Utils.ToNumber(args["value"]);
local duration = tonumber(args["duration"]);
local ppm = Utils.ToNumber(args["ppm"]);
local haste = GetCombatRatingBonus(CR_HASTE_RANGED);
local uptime = ppm * duration * (1 + haste / 100) / 60;
local averageStatValue = uptime * value;
UpdateResult(result, "Proc", statInfo, averageStatValue, weights[statInfo.Alias]);
end,
["icd"] = function(result, stats, weights, args)
local statInfo = StatsModule:GetStatInfoByDisplayName(args["stat"]);
if(not statInfo or not weights[statInfo.Alias]) then
return;
end
local value = Utils.ToNumber(args["value"]);
local duration = tonumber(args["duration"]);
local cd = tonumber(args["cd"]);
local chance = tonumber(args["chance"])/100;
local attackSpeed = UnitAttackSpeed("player");
local assumedAttacksPerSecond = 1/(attackSpeed/2);
local uptime = duration / (cd + (1/chance) * assumedAttacksPerSecond);
local averageStatValue = uptime * value;
UpdateResult(result, "Proc", statInfo, averageStatValue, weights[statInfo.Alias]);
end,
["use"] = function(result, stats, weights, args)
local statInfo = StatsModule:GetStatInfoByDisplayName(args["stat"]);
if(not statInfo or not weights[statInfo.Alias]) then
return;
end
local value = Utils.ToNumber(args["value"]);
local duration = tonumber(args["duration"]);
local cd = args["cd"]
local cdmin = tonumber(cd:match(ScoreModule.Matcher.Partial["cdmin"]));
local cdsec = tonumber(cd:match(ScoreModule.Matcher.Partial["cdsec"]) or 0);
local cooldown = cdmin * 60 + cdsec;
local uptime = duration / cooldown;
local averageStatValue = uptime * value;
UpdateResult(result, "Use", statInfo, averageStatValue, weights[statInfo.Alias]);
end,
["bonusarmor"] = function(result, stats, weights, args)
local armorKey = StatsModule:AliasToKey("armor");
local value = tonumber(args["value"]);
stats[armorKey] = stats[armorKey] - value;
stats[StatsModule:AliasToKey("bonusarmor")] = value;
end,
["insigniaofconquest"] = function(result, stats, weights, args)
args["chance"] = 15;
args["cd"] = 55;
ScoreModule.Fx["icd"](result, stats, weights, args);
end,
["soliumband"] = function(result, stats, weights, args)
local primaryStat, primaryStatValue = GetPrimaryStatForSpec(weights);
local buff = 0.1;
if(args["type"] == L["Matcher_SoliumBand_BuffType_Greater"]) then
buff = 0.15;
end
local statInfo = StatsModule:GetStatInfo(primaryStat);
if(not statInfo)
then
return;
end
args["stat"] = statInfo.DisplayName;
args["value"] = primaryStatValue * buff;
ScoreModule.Fx["rppm"](result, stats, weights, args);
end,
["blackhandtrinket"] = function(result, stats, weights, args)
local overtimeValue = 0;
local currentTick = 0;
local duration = tonumber(args["duration"]);
local tick = Utils.ToNumber(args["tick"]);
local maxStack = tonumber(args["maxstack"]);
local tickValue = tonumber(args["value"]);
while(currentTick * tick < duration) do
currentTick = currentTick + 1;
if(currentTick < maxStack) then
overtimeValue = overtimeValue + currentTick * tickValue;
else
overtimeValue = overtimeValue + maxStack * tickValue;
end
end
args["value"] = overtimeValue / (duration / tick);
ScoreModule.Fx["rppm"](result, stats, weights, args);
end,
["stoneoffire"] = function(result, stats, weights, args)
local primaryStat = GetPrimaryStatForSpec(weights);
local statInfo = StatsModule:GetStatInfo(primaryStat);
if(not statInfo)
then
return;
end
args["chance"] = 35;
args["cd"] = 55;
args["stat"] = statInfo.DisplayName;
ScoreModule.Fx["icd"](result, stats, weights, args);
end
};
function ScoreModule:CalculateItemScore(link, loc, tooltip, spec)
local fixBonusArmor = StatWeightScore.db.profile.GetStatsMethod == "api";
return self:CalculateItemScoreCore(link, loc, tooltip, spec, function()
if(StatWeightScore.db.profile.GetStatsMethod == "tooltip") then
return self:GetStatsFromTooltip(tooltip);
else
return GetStatsFromLink(link);
end
end, false, fixBonusArmor);
end
function ScoreModule:CalculateItemScoreCM(link, loc, tooltip, spec)
if(tooltip == nil) then
return nil
end
return self:CalculateItemScoreCore(link, loc, tooltip, spec, function()
return self:GetStatsFromTooltip(tooltip);
end, true, false);
end
function ScoreModule:CalculateItemScoreCore(link, loc, tooltip, spec, getStatsFunc, ignoreCm, fixBonusArmor)
local weights = SpecModule:GetWeights(spec);
local stats = getStatsFunc() or {};
local secondaryStat = StatsModule:GetBestGemStat(spec);
local locStr = getglobal(loc);
local db = StatWeightScore.db.profile;
local result = {
Score = 0;
};
local socketStats = GetStatsFromLink(link) or {};
if(not ignoreCm) then
if(socketStats[StatsModule:AliasToKey("socket")]) then
local _, gemLink = GetItemGem(link, 1);
local enchantLevel;
local gemStatWeight;
local gemStat;
local statValue;
if(not db.ForceSelectedGemStat and gemLink) then
local gemStats = self:GetStatsFromTooltip(ScanningTooltipModule:ScanTooltip(gemLink));
for stat, value in pairs(gemStats) do
local alias = StatsModule:KeyToAlias(stat);
local weight = weights[alias];
if(weight) then
statValue = value;
gemStat = StatsModule:GetStatInfo(alias);
gemStatWeight = weight;
end
end
elseif(secondaryStat) then
statValue = GemsModule:GetGemValue(db.EnchantLevel);
gemStat = secondaryStat.Stat;
gemStatWeight = secondaryStat.Weight;
end
if(gemStat) then
result.Score = result.Score + statValue * gemStatWeight;
result.Gem = {
Stat = gemStat.Alias;
Value = statValue;
};
end
end
end
if((ignoreCm and locStr == INVTYPE_TRINKET) or (not ignoreCm and (locStr == INVTYPE_TRINKET or locStr == INVTYPE_FINGER or weights["bonusarmor"]))) then
if(tooltip) then
for l = 1,tooltip:NumLines() do
local tooltipText = getglobal(tooltip:GetName().."TextLeft"..l);
if(tooltipText) then
local line = (tooltipText:GetText() or "");
local precheck = false;
for _, preCheckPattern in ipairs(self.Matcher.PreCheck) do
if(line:match(preCheckPattern)) then
precheck = true;
break;
end
end
if(precheck) then
for _, matcher in pairs(self.Matcher.Matchers) do
if(matcher.Fx == "bonusarmor" and not fixBonusArmor) then
else
local match = Utils.Pack(line:match(matcher.Pattern));
if(match) then
local argOrder = matcher.ArgOrder;
local args = {};
for i = 1, match.n do
local argName = argOrder[i];
local argValue = match[i]
if(argName == "stat" and argValue:lower() == RESISTANCE0_NAME:lower()) then
-- armor procs actually add bonus armor
argValue = BONUS_ARMOR;
end
args[argName] = argValue;
end
self.Fx[matcher.Fx](result, stats, weights, args);
end
end
end
end
end
end
end
end
if((locStr == INVTYPE_WEAPON or (SpecModule:IsDualWielding2h() and locStr == INVTYPE_2HWEAPON)) and weights["wohdps"]) then
result.Offhand = result.Score;
end
for stat, value in pairs(stats) do
local alias = StatsModule:KeyToAlias(stat);
local weight = weights[alias];
if(weight) then
if(result.Offhand ~= nil) then
if(alias == "dps") then
result.Offhand = result.Offhand + value * weights["wohdps"];
else
result.Offhand = result.Offhand + value * weight;
end
end
result.Score = result.Score + value * weight;
end
end
return result;
end
|
log = regroup.logging.makelog("data-final-fixes")
--double check active mods to save performance...
if type(dimoresenable) == "nil" and type(inventorychanges) == "nil" then
--5dim seems to be offline...
regroup.config.active_mods["5dim"] = nil
log("5dim force disabled")
end
if not data.raw.item["circuit-floor"] then
--more_floors seems to be offline
regroup.config.active_mods["more_floors"] = nil
log("More_Floors force disabled")
end
local mapping = {
["items"] = "item",
["recipes"] = "recipe",
["tools"] = "mining-tool",
["guns"] = "gun",
["modules"] = "module",
["ammos"] = "ammo",
["armors"] = "armor",
["capsules"] = "capsule",
}
--create shortcuts
table.each(mapping, function(v,k)
regroup.group[k] = regroup.group.createSelector(v)
end)
regroup.modloader.loadmods(regroup.config.active_mods, regroup.config.mod_order)
if regroup.config.DEBUG_MODE then
--log("[NAMES] => %s", go.dumpvar(data.raw, 3, 1))
--log("[GROUPS] => %s", go.dumpvar(data.raw["item-group"], 2, 0))
--log("[S_GROUPS] => %s", go.dumpvar(data.raw["item-subgroup"], 3, 0))
--log("[ITEMS] => %s", go.dumpvar(data.raw.item, 2, 0))
end
|
return {
coravp = {
acceleration = 0,
brakerate = 0,
buildangle = 1024,
buildcostenergy = 28365,
buildcostmetal = 3479,
builder = true,
buildinggrounddecaldecayspeed = 3000,
buildinggrounddecalsizex = 10,
buildinggrounddecalsizey = 8,
buildinggrounddecaltype = "coravp_aoplane.dds",
buildpic = "coravp.dds",
buildtime = 36000,
canmove = true,
canpatrol = true,
canstop = 1,
category = "LEVEL1 ALL SURFACE",
collisionvolumescales = "124 30 104",
collisionvolumetype = "Box",
corpse = "dead1",
description = "Produces T2 Vehicles",
energystorage = 200,
energyuse = 0,
explodeas = "LARGE_BUILDINGEX",
firestandorders = 1,
footprintx = 9,
footprintz = 7,
icontype = "building",
idleautoheal = 5,
idletime = 1800,
losemitheight = 29,
mass = 3885,
maxdamage = 4650,
maxslope = 15,
maxvelocity = 0,
maxwaterdepth = 0,
mobilestandorders = 1,
name = "Vehicle Plant",
noautofire = false,
objectname = "CORAVP",
radaremitheight = 29,
seismicsignature = 0,
selfdestructas = "LARGE_BUILDING",
shownanospray = false,
sightdistance = 286,
sortbias = 0,
standingfireorder = 2,
standingmoveorder = 1,
turninplaceanglelimit = 140,
turninplacespeedlimit = 0,
turnrate = 0,
unitname = "coravp",
usebuildinggrounddecal = true,
workertime = 400,
yardmap = "oooooooooooooooooooocccccoooocccccoooocccccoooocccccoooocccccoo",
buildoptions = {
[1] = "coracv",
[2] = "corassis",
[3] = "corvrad",
[4] = "coreter",
[5] = "cormart",
[6] = "corseal",
[7] = "corsent",
[8] = "correap",
[9] = "corvroc",
[10] = "cormabm",
[11] = "corbanisher",
[12] = "cortremor",
[13] = "corgol",
[14] = "coraegis",
},
customparams = {
buildpic = "coravp.dds",
faction = "CORE",
providetech = "T2 Factory",
},
featuredefs = {
dead1 = {
blocking = true,
collisionvolumeoffsets = "0 -6 0",
collisionvolumescales = "124 30 104",
collisionvolumetype = "Box",
damage = 3788,
description = "Advanced Vehicle Plant Wreckage",
energy = 1600,
featuredead = "heap1",
footprintx = 6,
footprintz = 6,
metal = 2913,
object = "CORAVP_DEAD",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
heap1 = {
blocking = false,
damage = 4735,
description = "Advanced Vehicle Plant Debris",
energy = 800,
footprintx = 6,
footprintz = 6,
metal = 1554,
object = "6X6C",
reclaimable = true,
customparams = {
fromunit = 1,
},
},
},
nanocolor = {
[1] = 0.26,
[2] = 0.61,
[3] = 0.61,
},
sfxtypes = {
explosiongenerators = {
[1] = "custom:WhiteLight",
},
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
build = "pvehwork",
canceldestruct = "cancel2",
underattack = "warning1",
unitcomplete = "untdone",
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
select = {
[1] = "pvehactv",
},
},
},
}
|
return {
summary = 'Get the draw range of the Mesh.',
description = [[
Retrieve the current draw range for the Mesh. The draw range is a subset of the vertices of the
Mesh that will be drawn.
]],
arguments = {},
returns = {
{
name = 'start',
type = 'number',
description = [[
The index of the first vertex that will be drawn, or nil if no draw range is set.
]]
},
{
name = 'count',
type = 'number',
description = [[
The number of vertices that will be drawn, or nil if no draw range is set.
]]
}
}
}
|
local awful = require('awful')
local gears = require('gears')
local ruled = require('ruled')
local beautiful = require('beautiful')
local client_keys = require('configuration.client.keys')
local client_buttons = require('configuration.client.buttons')
ruled.client.connect_signal(
'request::rules',
function()
-- All clients will match this rule.
ruled.client.append_rule {
id = 'global',
rule = {},
properties = {
focus = awful.client.focus.filter,
raise = true,
floating = false,
maximized = false,
above = false,
below = false,
ontop = false,
sticky = false,
maximized_horizontal = false,
maximized_vertical = false,
keys = client_keys,
buttons = client_buttons,
screen = awful.screen.preferred,
placement = awful.placement.no_overlap + awful.placement.no_offscreen
}
}
ruled.client.append_rule {
id = 'round_clients',
rule_any = {
type = {
'normal',
'dialog'
}
},
except_any = {
name = {'Discord Updater'}
},
properties = {
round_corners = true,
shape = beautiful.client_shape_rounded
}
}
-- Titlebar rules
ruled.client.append_rule {
id = 'titlebars',
rule_any = {
type = {
'normal',
'dialog',
'modal',
'utility'
}
},
properties = {
titlebars_enabled = true
}
}
-- Dialogs
ruled.client.append_rule {
id = 'dialog',
rule_any = {
type = {'dialog'},
class = {'Wicd-client.py', 'calendar.google.com'}
},
properties = {
titlebars_enabled = true,
floating = true,
above = true,
skip_decoration = true,
placement = awful.placement.centered
}
}
-- Modals
ruled.client.append_rule {
id = 'modal',
rule_any = {
type = {'modal'}
},
properties = {
titlebars_enabled = true,
floating = true,
above = true,
skip_decoration = true,
placement = awful.placement.centered
}
}
-- Utilities
ruled.client.append_rule {
id = 'utility',
rule_any = {
type = {'utility'}
},
properties = {
titlebars_enabled = false,
floating = true,
skip_decoration = true,
placement = awful.placement.centered
}
}
-- Splash
ruled.client.append_rule {
id = 'splash',
rule_any = {
type = {'splash'},
name = {'Discord Updater'}
},
properties = {
titlebars_enabled = false,
round_corners = false,
floating = true,
above = true,
skip_decoration = true,
placement = awful.placement.centered
}
}
-- Image viewers
ruled.client.append_rule {
id = 'image_viewers',
rule_any = {
class = {
'feh',
'Pqiv',
'Sxiv'
},
},
properties = {
titlebars_enabled = true,
skip_decoration = true,
floating = true,
ontop = true,
placement = awful.placement.centered
}
}
-- Floating
ruled.client.append_rule {
id = 'floating',
rule_any = {
instance = {
'file_progress',
'Popup',
'nm-connection-editor',
},
class = {
'scrcpy',
'Mugshot',
'Pulseeffects'
},
role = {
'AlarmWindow',
'ConfigManager',
'pop-up'
}
},
properties = {
titlebars_enabled = true,
skip_decoration = true,
ontop = true,
floating = true,
focus = awful.client.focus.filter,
raise = true,
keys = client_keys,
buttons = client_buttons,
placement = awful.placement.centered
}
}
end
)
|
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or ''
local QuadExport = require(current_folder.. ".QuadExport")
local History = require(current_folder.. ".History")
local table = require(current_folder.. ".tableplus")
local libquadtastic = require(current_folder.. ".libquadtastic")
local common = require(current_folder.. ".common")
local exporters = require(current_folder.. "Exporters")
local Path = require(current_folder.. "Path")
local os = require(current_folder.. ".os")
local S = require(current_folder.. ".strings")
local Recent = require(current_folder.. "Recent")
local Grid = require(current_folder.. "Grid")
-- Shared library
local lfs = require("lfs")
local function add_path_to_recent_files(interface, data, filepath)
-- Insert new file into list of recently loaded files
-- Remove duplicates from recent files
filepath = os.path(filepath)
Recent.promote(data.settings.recent, filepath)
Recent.truncate(data.settings.recent, 10)
-- Update latest qua dir
data.settings.latest_qua = common.split(filepath)
interface.store_settings(data.settings)
end
local QuadtasticLogic = {}
function QuadtasticLogic.transitions(interface) return {
-- luacheck: no unused args
quit = function(app, data)
if not app.quadtastic.proceed_despite_unsaved_changes() then
return
else
return 0
end
end,
rename = function(app, data, quads)
if not quads then quads = data.selection:get_selection() end
if #quads == 0 then return
elseif #quads > 1 then
interface.show_dialog(S.dialogs.rename.err_only_one)
return
else
local quad = quads[1]
local current_keys = {table.find_key(data.quads, quad)}
local old_key = table.concat(current_keys, ".")
local new_key = old_key
local ret
ret, new_key = interface.query(S.dialogs.rename.name_prompt, new_key,
{escape = S.buttons.cancel,
enter = S.buttons.ok})
local function replace(tab, old_keys, new_keys, element)
-- Make sure that the new keys form a valid path, that is, all but the
-- last key must be tables that are not quads
local current_table = tab
for i=1,#new_keys do
if type(current_table) == "table" and libquadtastic.is_quad(current_table) then
local keys_so_far = table.concat(new_keys, ".", 1, i)
interface.show_dialog(S.dialogs.rename.err_nested_quad(keys_so_far))
return
end
-- This does intentionally not check the very last key, since it is
-- fine when that one is a quad
if i < #new_keys then
local next_key = new_keys[i]
-- Create a new empty table if necessary
if not current_table[next_key] then
current_table[next_key] = {}
end
current_table = current_table[next_key]
end
end
local do_action = function()
-- Remove the entry under the old key
table.set(data.quads, nil, unpack(old_keys))
-- Add the entry under the new key
table.set(data.quads, element, unpack(new_keys))
end
local undo_action = function()
-- Remove the entry under the new key
table.set(data.quads, nil, unpack(new_keys))
-- Add the entry under the old key
table.set(data.quads, element, unpack(old_keys))
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end
if ret == S.buttons.ok then
if new_key == old_key then return end
local new_keys = {}
for k in string.gmatch(new_key, "([^.]+)") do
-- Convert the key to a number if possible
k = tonumber(k) or k
table.insert(new_keys, k)
end
-- Check if that key already exists
if table.get(data.quads, unpack(new_keys)) then
local action = interface.show_dialog(
S.dialogs.rename.err_exists(new_key),
{S.buttons.cancel, S.buttons.swap, S.buttons.replace})
if action == S.buttons.swap then
local old_value = table.get(data.quads, unpack(new_keys))
local do_action = function()
table.set(data.quads, old_value, unpack(current_keys))
table.set(data.quads, quad, unpack(new_keys))
end
local undo_action = function()
table.set(data.quads, old_value, unpack(new_keys))
table.set(data.quads, quad, unpack(current_keys))
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then
app.quadtastic.turbo_workflow_on_change()
end
elseif action == S.buttons.replace then
replace(data.quads, current_keys, new_keys, quad)
else -- Cancel option
return
end
else
replace(data.quads, current_keys, new_keys, quad)
end
-- Set the focus of the quad list to the renamed quad
interface.move_quad_into_view(data.quad_scrollpane_state, quad)
end
end
end,
sort = function(app, data, quads)
if not quads then quads = data.selection:get_selection() end
if #quads == 0 then return end
-- Find the shared parent of the selected quads.
local first_keys = {table.find_key(data.quads, quads[1])}
-- Remove the last element of the key list to get the shared key
table.remove(first_keys)
local shared_keys = first_keys
local shared_parent = table.get(data.quads, unpack(shared_keys))
local individual_keys = {}
local numeric_quads = 0
local new_group = {}
for _,v in ipairs(quads) do
-- This is an N^2 search and it sucks, but it probably won't matter.
local key = table.find_key(shared_parent, v)
if not key then
interface.show_dialog(S.dialogs.sort.err_not_shared_group)
return
else
individual_keys[v] = key
end
if type(key) == "number" and libquadtastic.is_quad(v) then
numeric_quads = numeric_quads + 1
end
end
if numeric_quads == 0 then
interface.show_dialog(S.dialogs.sort.err_no_numeric_quads)
return
end
-- Filter out non-quad elements and elements with non-numeric keys
for _,v in ipairs(quads) do
if libquadtastic.is_quad(v) and type(individual_keys[v]) == "number" then
table.insert(new_group, v)
end
end
-- Sort the quads
local function sort(quad_a, quad_b)
return quad_a.y < quad_b.y or quad_a.y == quad_b.y and quad_a.x < quad_b.x
end
table.sort(new_group, sort)
local do_action = function()
-- Remove the quads from their parent
for _,v in ipairs(new_group) do
local key = individual_keys[v]
-- Remove the element from the shared parent
shared_parent[key] = nil
end
-- Now add the quads to the parent in order
for _,v in ipairs(new_group) do
table.insert(shared_parent, v)
end
end
local undo_action = function()
for _,v in ipairs(new_group) do
-- Remove the quad from its shared parent, starting at the end
table.remove(shared_parent)
end
-- We cannot do this in a single pass since these actions can interfere
for _,v in ipairs(new_group) do
-- Add the quads to its parent at its original position
local key = individual_keys[v]
shared_parent[key] = v
end
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
remove = function(app, data, quads)
if not quads then quads = data.selection:get_selection() end
if #quads == 0 then
return
else
local was_collapsed = {}
local selected_elements = {}
local keys = {}
for _,element in ipairs(quads) do
if data.selection:is_selected(element) then
table.insert(selected_elements, element)
end
was_collapsed[element] = data.collapsed_groups[element]
keys[element] = {table.find_key(data.quads, element)}
end
local do_action = function()
-- Deselect those elements
data.selection:deselect(quads)
for _,element in ipairs(quads) do
if #keys[element] > 0 then
-- Remove the elements from the quad tree
table.set(data.quads, nil, unpack(keys[element]))
-- Remove the element from the list of collapsed groups. This will have
-- no effect if the element was a quad.
data.collapsed_groups[element] = nil
end
end
end
local undo_action = function()
-- Select those quads
data.selection:set_selection(selected_elements)
for _,element in ipairs(quads) do
if #keys[element] > 0 then
-- Restore the elements from the quad tree
table.set(data.quads, element, unpack(keys[element]))
-- Restore their entries from the list of collapsed groups
data.collapsed_groups[element] = was_collapsed[element]
end
end
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end
end,
create = function(app, data, new_quad)
-- If a group is currently selected, add the new quad to that group
-- If a quad is currently selected, add the new quad to the same
-- group.
local selection = data.selection:get_selection()
local group -- the group to which the new quad will be added
if #selection == 1 then
local keys = {table.find_key(data.quads, selection[1])}
if libquadtastic.is_quad(selection[1]) then
-- Remove the last key so that the new quad is added to the
-- group that contains the currently selected quad
table.remove(keys)
end
group = table.get(data.quads, unpack(keys))
else
-- Just add it to the root
group = data.quads
end
local do_action, undo_action
if libquadtastic.is_quad(new_quad) then
local new_index = #group + 1
do_action = function()
group[new_index] = new_quad
end
undo_action = function()
group[new_index] = nil
end
else
assert(type(new_quad) == "table")
do_action = function()
for _,quad in ipairs(new_quad) do
table.insert(group, quad)
end
end
undo_action = function()
for _,quad in ipairs(new_quad) do
table.remove(group)
end
end
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
if libquadtastic.is_quad(new_quad) then
data.selection:set_selection({new_quad})
interface.move_quad_into_view(data.quad_scrollpane_state, new_quad)
else
assert(type(new_quad) == "table")
assert(#new_quad >= 1)
data.selection:set_selection(new_quad)
interface.move_quad_into_view(data.quad_scrollpane_state, new_quad[1])
end
end,
--[[
_
_ __ ___ _____ _____ __ _ _ _ __ _ __| |___
| '_ ` _ \ / _ \ \ / / _ \ / _` | | | |/ _` |/ _` / __|
| | | | | | (_) \ V / __/ | (_| | |_| | (_| | (_| \__ \
|_| |_| |_|\___/ \_/ \___| \__, |\__,_|\__,_|\__,_|___/
|_|
]]
-- Moves the given quads by the given delta as far as possible.
-- original_pos should be a table that contains the original position of each
-- quad before the user started to move them. Each element of this table
-- should have its x coordinate at index x and its y coordinate at index x.
-- The nth element in original_pos should contain the coordinates of the nth
-- quad in quads.
-- dx, dy should be the accumulative delta by which the quads should be moved.
-- That is, if the user moves the mouse by 4 pixels first, and then by another
-- 8 pixels, then the delta in the second call should be 12, and not 8.
-- All this is necessary because the movement of each quad is limited by the
-- image's border, and therefore a quad right next to the right border cannot
-- move as far to the right as a quad further to the left. Thus, as the user
-- moves the quads around, we want to keep them inside the image, but we also
-- want to preserve the relative positions of the quads. Otherwise moving all
-- quads to the bottom right corner and them moving them in the opposite
-- direction by the same distance would not restore the quad's original
-- position.
move_quads = function(app, data, quads, original_pos, dx, dy, img_w, img_h, snap_to_grid)
if not quads then quads = data.selection:get_selection() end
if #quads == 0 then return end
assert(#quads == #original_pos)
for i=1,#quads do
local quad = quads[i]
local pos = original_pos[i]
if libquadtastic.is_quad(quad) then
-- Offset the position by the given deltas
quad.x = pos.x + dx
quad.y = pos.y + dy
-- Clamp the coordinates
quad.x = math.max(0, math.min(img_w - quad.w, quad.x))
quad.y = math.max(0, math.min(img_h - quad.h, quad.y))
if snap_to_grid then
-- Snap the position of the quad to a grid point.
quad.x = Grid.floor(data.settings.grid.x, quad.x)
quad.y = Grid.floor(data.settings.grid.y, quad.y)
end
end
end
end,
-- Finishes moving the given quad. Without calling this function the movements
-- that were made with move_quads are not added to the undo history.
-- The table original_pos should follow the same format as documented in
-- move_quads.
commit_movement = function(app, data, quads, original_pos)
local deltas = {} -- table containing for each quad how far it was moved
assert(#quads == #original_pos)
for i=1,#quads do
if libquadtastic.is_quad(quads[i]) then
deltas[i] = {
x = quads[i].x - original_pos[i].x,
y = quads[i].y - original_pos[i].y
}
end
end
local do_action = function()
for i=1,#quads do
if libquadtastic.is_quad(quads[i]) then
quads[i].x = quads[i].x + deltas[i].x
quads[i].y = quads[i].y + deltas[i].y
end
end
end
local undo_action = function()
for i=1,#quads do
if libquadtastic.is_quad(quads[i]) then
quads[i].x = quads[i].x - deltas[i].x
quads[i].y = quads[i].y - deltas[i].y
end
end
end
data.history:add(do_action, undo_action)
-- Note that we deliberately do not call the do_action here, since the quads
-- are already at the position where the user wants them.
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
-- Resizes all given quads by the given amount, in the given direction.
-- The direction should be a table containing the keys n, e, s, w when
-- the quads are resized in the respective direction. For example, if a
-- quad is resized at the south-east corner, then direction.s and direction.e
-- should be set to `true`. All other keys should be `false` or `nil`.
-- original_quad is a table that has at the nth index the original x, y, width
-- and height at index x, y, w and h, respectively, of the nth quad in quads.
-- The image dimensions are needed so that the position and size of the quads
-- can be restricted.
resize_quads = function(app, data, quads, original_quad, direction, dx, dy, img_w, img_h, snap_to_grid)
dx, dy = dx or 0, dy or 0
-- All quads have their position in the upper left corner, and their
-- size extends to the lower right corner.
-- The change in position to be applied to all quads
local dpx, dpy = 0, 0
-- The change in size to be applied to all quads
local dw, dh = 0, 0
if direction.n and dy ~= 0 then
dpy = dy -- move the quad by the given amount
dh = -dy -- but reduce the height accordingly
elseif direction.s and dy ~= 0 then
dh = dy
end
if direction.w and dx ~= 0 then
dpx = dx -- move the quad by the given amount
dw = -dx -- but reduce the height accordingly
elseif direction.e and dx ~= 0 then
dw = dx
end
-- Now apply all changes
for i,quad in pairs(quads) do
local ox, oy = original_quad[i].x, original_quad[i].y
local ow, oh = original_quad[i].w, original_quad[i].h
-- Calculate deltas specific to this quad in case we need to snap the
-- quad size to the grid
local idpx, idpy, idw, idh = dpx, dpy, dw, dh
if snap_to_grid then
local gx, gy = data.settings.grid.x, data.settings.grid.y
local grid_w, grid_h = Grid.mult(gx, ow + dx), Grid.mult(gy, oh + dy)
-- deltas after grid snapping
local gdx, gdy = grid_w - ow - dx, grid_h - oh - dy
-- Adjust position and size deltas
if direction.n then
idpy = idpy + gdy
idh = idh - gdy
elseif direction.s then
idh = idh + gdy
end
if direction.w then
idpx = idpx + gdx
idw = idw - gdx
elseif direction.e then
idw = idw + gdx
end
end
-- Resize the quads, but restrict their dimensions and position
quad.x = math.max(0, math.min(img_w, ox + math.min(ow - 1, idpx)))
quad.y = math.max(0, math.min(img_h, oy + math.min(oh - 1, idpy)))
quad.w = math.max(1, math.min(img_w - quad.x,
ow + (direction.w and math.min(ox, idw) or idw)))
quad.h = math.max(1, math.min(img_h - quad.y,
oh + (direction.n and math.min(oy, idh) or idh)))
end
end,
commit_resizing = function(app, data, quads, original_quad)
local deltas = {}
assert(#quads == #original_quad)
for i=1,#quads do
if libquadtastic.is_quad(quads[i]) then
deltas[i] = {
x = quads[i].x - original_quad[i].x,
y = quads[i].y - original_quad[i].y,
w = quads[i].w - original_quad[i].w,
h = quads[i].h - original_quad[i].h,
}
end
end
local do_action = function()
for i=1,#quads do
if libquadtastic.is_quad(quads[i]) then
quads[i].x = quads[i].x + deltas[i].x
quads[i].y = quads[i].y + deltas[i].y
quads[i].w = quads[i].w + deltas[i].w
quads[i].h = quads[i].h + deltas[i].h
end
end
end
local undo_action = function()
for i=1,#quads do
if libquadtastic.is_quad(quads[i]) then
quads[i].x = quads[i].x - deltas[i].x
quads[i].y = quads[i].y - deltas[i].y
quads[i].w = quads[i].w - deltas[i].w
quads[i].h = quads[i].h - deltas[i].h
end
end
end
data.history:add(do_action, undo_action)
-- Note that we deliberately do not call the do_action here, since the quads
-- are already resized to the size that the user wants.
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
group = function(app, data, quads)
if not quads then quads = data.selection:get_selection() end
if #quads == 0 then return end
-- Find the shared parent of the selected quads.
local first_keys = {table.find_key(data.quads, quads[1])}
-- Remove the last element of the key list to get the shared key
table.remove(first_keys)
local shared_keys = first_keys
local shared_parent = table.get(data.quads, unpack(shared_keys))
local individual_keys = {}
for _,v in ipairs(quads) do
-- This is an N^2 search and it sucks, but it probably won't matter.
local key = table.find_key(shared_parent, v)
if not key then
interface.show_dialog(S.dialogs.group.err_not_shared_group)
return
else
individual_keys[v] = key
end
end
-- Do the second pass, this time with destructive actions
local new_group = {}
local numeric_indices = {}
for _,v in ipairs(quads) do
local key = individual_keys[v]
-- We don't necessarily want to preserve the numeric index, but we do
-- want to preserve the order of those quads with numeric indices
if type(key) == "number" then
table.insert(numeric_indices, key)
else
new_group[key] = v
end
end
table.sort(numeric_indices)
for i,old_key in ipairs(numeric_indices) do
new_group[i] = shared_parent[old_key]
end
local do_action = function()
for _,v in ipairs(quads) do
-- Remove the element from the shared parent
local key = individual_keys[v]
shared_parent[key] = nil
end
table.insert(shared_parent, new_group)
-- Focus quad list on new group
interface.move_quad_into_view(data.quad_scrollpane_state, new_group)
-- Select the newly created group
data.selection:set_selection({new_group})
end
local undo_action = function()
for _,v in ipairs(quads) do
-- Restore the element in its original position in shared parent
local key = individual_keys[v]
shared_parent[key] = v
end
-- We used a simple insert to add the new group to the parent.
-- Therefore the group was inserted at the very end of the parent, and
-- can be removed with table.remove
table.remove(shared_parent)
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
ungroup = function(app, data, quads)
if not quads then quads = data.selection:get_selection() end
if #quads == 0 then return end
if #quads > 1 then
interface.show_dialog(S.dialogs.ungroup.err_only_one)
return
end
if libquadtastic.is_quad(quads[1]) then
return
end
local group = quads[1]
local keys = {table.find_key(data.quads, group)}
-- Remove the last element of the key list to get the parent's keys
local group_key = table.remove(keys)
local parent_keys = keys
local parent = table.get(data.quads, unpack(parent_keys))
-- Check that we can break up this group by making sure that the parent
-- element and the group don't have any conflicting keys
local ignore_numeric_clash = false
for k,_ in pairs(group) do
if parent[k] and k ~= group_key then
local parent_name
for _,v in ipairs(parent_keys) do
parent_name = (parent_name and (parent_name .. ".") or "") .. tostring(v)
end
if type(k) == "number" then
if not ignore_numeric_clash then
local ret = interface.show_dialog(S.dialogs.ungroup.warn_numeric_clash(k),
{S.buttons.yes, S.buttons.no})
if ret == S.buttons.yes then
ignore_numeric_clash = true
else
return
end
end
else
interface.show_dialog(S.dialogs.ungroup.err_name_conflict(k))
return
end
end
end
local do_action = function()
-- Remove group from parent
parent[group_key] = nil
data.collapsed_groups[group_key] = nil
for k,v in pairs(group) do
if type(k) == "number" then
table.insert(parent, v)
else
parent[k] = v
end
end
end
local undo_action = function()
-- Remove the group's elements from the parent
for k,v in pairs(group) do
if type(k) == "number" then
table.remove(parent)
else
parent[k] = nil
end
end
-- Add the group to the parent
parent[group_key] = group
end
data.history:add(do_action, undo_action)
do_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
offer_reload = function(app, data, callback)
local image_path = data.quads._META.image_path
local ret = interface.show_dialog(
S.dialogs.offer_reload(image_path),
{enter=S.buttons.yes, escape=S.buttons.no})
if ret == S.buttons.yes then
app.quadtastic.load_image(image_path, callback)
end
end,
undo = function(app, data)
if not data.history:can_undo() then return end
local undo_action = data.history:undo()
undo_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
redo = function(app, data)
if not data.history:can_redo() then return end
local redo_action = data.history:redo()
redo_action()
if data.turbo_workflow then app.quadtastic.turbo_workflow_on_change() end
end,
new = function(app, data)
local proceed = app.quadtastic.proceed_despite_unsaved_changes()
if not proceed then return end
data.quads = {
_META = {}
}
data.quadpath = nil -- path to the file containing the quad definitions
-- The name of the last used exporter
data.prev_exporter = nil
-- A mapping from exporter name to last used path. This is convenient
-- in case specific export targets are always saved in the same location.
-- These are populated from the loaded application settings.
data.exportpath = {}
data.image = nil -- the loaded image
interface.reset_view(data)
-- Reset list of collapsed groups
data.collapsed_groups = {}
data.file_timestamps = {}
data.history = History()
data.history:mark() -- A new file doesn't have any changes worth saving
-- until the user actually does something
app.quadtastic.switch_tool("create")
end,
-- The steps that need to be taken when turbo workflow is enabled and
-- some quads changed.
turbo_workflow_on_change = function(app, data)
app.quadtastic.save()
if data.prev_exporter then
app.quadtastic.repeat_export()
end
end,
switch_tool = function(app, data, tool)
data.tool = tool
data.toolstate = {}
end,
save = function(app, data, callback)
if not data.quadpath or data.quadpath == "" then
app.quadtastic.save_as(callback)
else
local success, err = pcall(app.quadtastic.export_with,
data.quadpath, common.exporter_table)
if success then
data.history:mark()
if callback then callback(data.quadpath) end
else
interface.show_dialog(S.dialogs.err_save_quads(err))
end
end
end,
-- Have user pick a path where to save the quad file.
-- This is separate from export_as so that data.quadpath and data.exportpath
-- don't get mixed up.
save_as = function(app, data, callback)
local basepath
if data.quadpath then
basepath = data.quadpath
elseif data.quads and data.quads._META and data.quads._META.image_path then
basepath = common.split(data.quads._META.image_path)
elseif data.settings.latest_qua then
basepath = data.settings.latest_qua
else
basepath = love.filesystem.getUserDirectory()
end
local ret, filepath = interface.save_file(basepath, "lua")
if ret == S.buttons.save then
data.quadpath = filepath
-- pass a callback to the save function that stores the used path in the
-- list of recently opened files if saving succeeded.
local function save_as_callback(quadpath)
add_path_to_recent_files(interface, data, quadpath)
if callback then callback(quadpath) end
end
app.quadtastic.save(save_as_callback)
end
end,
-- Exports the current quads to the previously used file, using the previously
-- used exporter.
repeat_export = function(app, data, callback)
if not data.prev_exporter then return end
local exporter = data.prev_exporter
if not data.exportpath[exporter.name] then
-- Have user pick an export file
app.quadtastic.export_as(exporter, callback)
else
local path = data.exportpath[exporter.name]
-- Check that the exporter can indeed export the quad definitions.
-- If the exporter does not define this function, we assume that it can
-- export everything.
if exporter.can_export then
local success, can_export, msg = pcall(exporter.can_export, data.quads)
if success then
if not can_export then
interface.show_dialog(S.dialogs.err_cannot_export(msg))
return
end
else
local err = can_export -- the second returned value contains the error
interface.show_dialog(S.dialogs.err_exporting(err))
return
end
end
local success, err = pcall(app.quadtastic.export_with, path, exporter)
if success then
if callback then callback(path) end
else
interface.show_dialog(S.dialogs.err_exporting(err))
end
end
end,
-- Exports the current quads using the given exporter. The user will be asked
-- to pick a file.
export_as = function(app, data, exporter, callback)
local basepath
if data.exportpath[exporter.name] then
basepath = data.exportpath[exporter.name]
elseif data.quadpath then
local path, filename = common.split(data.quadpath)
local export_filename = string.format("%s.%s",
Path.split_extension(filename),
exporter.ext)
basepath = path .. export_filename
elseif data.quads and data.quads._META and data.quads._META.image_path then
basepath = common.split(data.quads._META.image_path)
elseif data.settings.latest_qua then
basepath = data.settings.latest_qua
else
basepath = love.filesystem.getUserDirectory()
end
local save_button_label = S.buttons.export_as(exporter.name)
local ret, filepath = interface.save_file(basepath, exporter.ext,
save_button_label)
if ret == save_button_label then
-- Store that path, so that the file browser starts off at that path in
-- the future for this exporter.
data.exportpath[exporter.name] = filepath
data.prev_exporter = exporter
app.quadtastic.repeat_export(callback)
end
end,
-- expect this function to fail! Wrap it in a pcall!
export_with = function(app, data, path, exporter)
QuadExport.export(data.quads, exporter, path)
end,
choose_quad = function(app, data, basepath)
if not basepath and data.settings.latest_qua then
basepath = data.settings.latest_qua
else
basepath = love.filesystem.getUserDirectory()
end
local ret, filepath = interface.open_file(basepath)
if ret == S.buttons.open then
app.quadtastic.load_quad(filepath)
end
end,
-- Checks with the user how they want to handle unsaved changes before an
-- action is executed that would override those changes.
-- The user can save or discard the changes, or cancel the action.
-- This function returns whether the user chose an action that indicates that
-- they want to go ahead with the action (i.e. the function returns true if
-- the user pressed save or discard, false otherwise).
-- This function will also return true if there are no unsaved changes.
proceed_despite_unsaved_changes = function(app, data)
-- Return true if there are no unsaved changes
if not data.history or data.history:is_marked() then return true end
-- Otherwise check with the user
local ret = interface.show_dialog(S.dialogs.save_changes,
{S.buttons.cancel, S.buttons.discard, S.buttons.save})
if ret == S.buttons.save then
app.quadtastic.save()
end
return ret == S.buttons.save or ret == S.buttons.discard
end,
load_quad = function(app, data, filepath)
if not app.quadtastic.proceed_despite_unsaved_changes() then return end
local success, more = pcall(function()
local filehandle, err = io.open(filepath, "r")
if err then
error(err, 0)
end
if filehandle then
filehandle:close()
local filecontent, load_err = loadfile(filepath)
if not filecontent then
error(load_err, 0)
end
local quads = filecontent()
local quadpath = filepath
return {quads, quadpath}
end
end)
if success then
data.quads, data.quadpath = unpack(more)
-- Reset list of collapsed groups
data.collapsed_groups = {}
data.history = History()
-- A newly loaded project has no unsaved changes
data.history:mark()
if not data.quads._META then data.quads._META = {} end
local metainfo = libquadtastic.get_metainfo(data.quads)
-- Remove the current image from the application state
data.image = nil
if metainfo.image_path then
local abs_path
if Path.is_absolute_path(metainfo.image_path) then
abs_path = metainfo.image_path
elseif Path.is_relative_path(metainfo.image_path) then
-- Create an absolute path to the image file by concatenating the
-- absolute path to the directory containing the quadfile and the
-- relative image path
abs_path = tostring(Path(filepath):parent() .. metainfo.image_path)
else
error("Path to image is neither absolute nor relative.")
end
-- Store the image path as an absolute path. It will be converted back
-- to a relative path when the quads are saved or exported.
metainfo.image_path = abs_path
app.quadtastic.load_image(metainfo.image_path)
end
add_path_to_recent_files(interface, data, filepath)
else
interface.show_dialog(S.dialogs.err_load_quads(more))
end
end,
choose_image = function(app, data, basepath)
if not basepath then
if data.quads and data.quads._META and data.quads._META.image_path then
basepath = data.quads._META.image_path
elseif data.settings.latest_img then
basepath = data.settings.latest_img
else
basepath = love.filesystem.getUserDirectory()
end
end
local ret, filepath = interface.open_file(basepath)
if ret == S.buttons.open then
app.quadtastic.load_image(filepath)
end
end,
load_image = function(app, data, filepath, callback)
filepath = os.path(filepath)
local success, more = pcall(common.load_image, filepath)
-- success, more = pcall(love.graphics.newImage, data)
if success then
data.image = more
data.quads._META.image_path = filepath
-- Update latest image dir
data.settings.latest_img = common.split(filepath)
interface.store_settings(data.settings)
data.file_timestamps.image_loaded = lfs.attributes(filepath, "modification")
data.file_timestamps.image_latest = data.file_timestamps.image_loaded
interface.reset_view(data)
if callback then callback(filepath) end
else
interface.show_dialog(S.dialogs.err_load_image(more))
end
end,
load_dropped_file = function(app, data, filepath)
-- Determine how to treat this file depending on its extensions
local _, extension = Path.split_extension(filepath)
if extension == "lua" or extension == "qua" then
app.quadtastic.load_quad(filepath)
else
-- Try to load this as an image
app.quadtastic.load_image(filepath)
end
end,
-- Change the current grid configuration to the given grid configuration,
-- update the list of recent grid configurations and save the changed settings
change_grid_config = function(app, state, grid_x, grid_y)
-- Promote current config to the most recently used config
local comparator = function(conf_a, conf_b)
return conf_a.x == conf_b.x and conf_a.y == conf_b.y
end
local current_config = {x = state.settings.grid.x,
y = state.settings.grid.y}
Recent.promote(state.settings.grid.recent, current_config,
comparator)
-- Remove the new entry from the list of recent entries.
-- Otherwise it is shown as the current configs, but might show
-- up in the list of recent configs, too.
Recent.remove(state.settings.grid.recent, {x = grid_x, y = grid_y},
comparator)
Recent.truncate(state.settings.grid.recent, 10)
-- Update current config
state.settings.grid.x = grid_x
state.settings.grid.y = grid_y
-- Save settings
interface.store_settings(state.settings)
end,
-- Open a dialog that lets the user pick custom grid configuration.
-- When the user confirms the dialog, change the grid config to the chosen
-- grid config.
choose_custom_grid_config = function(app, state)
local ret, new_grid = interface.choose_grid_config(state.settings.grid.x,
state.settings.grid.y)
if ret == S.buttons.ok then
app.quadtastic.change_grid_config(new_grid.x, new_grid.y)
end
end,
reload_exporters = function(app, data, callback)
local success, more, count = pcall(exporters.list, {S.exporters_dirname,
S.custom_exporters_dirname})
if success then
data.exporters = more
-- Update previous exporter
if data.prev_exporter then
-- This will clear the previous exporter if there is none with that
-- name in the new set of exporters, or update the previous exporter.
data.prev_exporter = data.exporters[data.prev_exporter.name]
end
if callback then callback(count) end
else
interface.show_dialog(S.dialogs.err_reload_exporters(more))
end
end,
show_about_dialog = function(app, data)
interface.show_about_dialog()
end,
show_ack_dialog = function(app, data)
interface.show_ack_dialog()
end,
check_updates = function(app, data)
interface.check_updates()
end,
offer_update = function(app, data, current_version, latest_version)
local ret = interface.show_dialog(S.dialogs.offer_update(latest_version,
current_version),
{enter = S.buttons.yes, escape = S.buttons.no})
if ret == S.buttons.yes then
love.system.openURL(S.itchio_url)
end
end,
}
end
return QuadtasticLogic
|
return { style = 'dialog',
{ style = 'dialogHead', text = 'Settings' },
{ style = 'dialogBody', padding = 24,
{ flow = 'x', minheight = 260,
{
{ type = 'label', text = 'Seed', minheight = 32 },
{
{ type = 'radio', group = 'seed', text = 'Use random seed', value = true, id = 'seedrandom', minheight = 27 },
{ flow = 'y', { type = 'radio', group = 'seed', text = 'Use custom seed', id = 'seedselect', minheight = 27 },
{
flow = 'x',
{ type = 'text', id = 'customseed', width = 200, minheight = 32},
{ type = 'label', id = 'seedcount' }
}
}
},
{ type = 'label', text = 'Randomization Options', minheight = 32 },
{ type = 'check', value = false, id = 'puppy', text = "Puppies outside Sand Zone", minheight = 27 },
{ type = 'check', value = true, id = 'completable', text = "Guarantee access to all locations", minheight = 54},
{ flow = 'x', height = 32,
{ type = 'check', value = false, id = 'seqbreak', text = "Sequence breaks", minheight = 32, width = 170},
{ type = 'button', style = 'dialogButton', text = "Modify", id = 'seqButton', width = 70, align = 'center' },
{ width = false }
},
},
{
{ type = 'label', text = 'Objective', minheight = 32 },
{ type = 'stepper', id = 'objective', align = 'center', width = 200,
{ text = "Bad ending", value = "objBadEnd" },
{ text = "Normal ending", value = "objNormalEnd" },
{ text = "Best ending", value = "objBestEnd" },
{ text = "All bosses", value = "objAllBosses" },
{ text = "100%", value = "obj100Percent" }
},
{ type = 'label', text = 'Spawn Location', minheight = 32 },
{ type = 'stepper', id = 'spawn', align = 'middle left', height = 48, width = 200,
{ text = " Start\r\n Point", value = "Start Point", icon = "assets/icon/StartPoint2.png" },
{ text = " Arthur's\r\n House", value = "Arthur's House", icon = "assets/icon/Arthur2.png" },
{ text = " Camp", value = "Camp", icon = "assets/icon/Camp.png" }
},
{ type = 'button', style = 'dialogButton', text = "Personal Settings", id = 'musicButton', width = 200, height = 48, align = 'center' },
{ type = 'check', value = false, id = 'noFallingBlocks', text = "No Falling Blocks in Hell", minheight = 32 },
},
},
{
flow = 'x',
{ type = 'text', id = 'sharecode', width = 350 },
{ type = 'button', style = 'dialogButton', text = "Import Sharecode", id = 'importshare', width = 180, align = 'center' }
}
},
{ style = 'dialogFoot',
{},
{ style = 'dialogButton', id = 'randoButton', text = 'Random Settings', width = 120 },
{ style = 'dialogButton', id = 'closeButton', text = 'Close' }
}
}
|
object_static_worldbuilding_camping_frn_all_exceptional_meat_rack = object_static_worldbuilding_camping_shared_frn_all_exceptional_meat_rack:new {
}
ObjectTemplates:addTemplate(object_static_worldbuilding_camping_frn_all_exceptional_meat_rack, "object/static/worldbuilding/camping/frn_all_exceptional_meat_rack.iff")
|
local BASE_PATH = "pac3/"
local ICON_FILE = "icon16/group_add.png"
local ICON_FOLDER = "icon16/folder.png"
local blacklist = {
["objcache"] = true,
["__backup"] = true,
["__backup_save"] = true,
["__animations"] = true,
}
local frame = vgui.Create("DFrame")
frame:SetSize(ScrW() * 0.35, ScrH() * 0.45)
frame:Center()
frame:MakePopup()
frame:SetTitle("PAC Link Changer")
local box = frame:Add("DPanel")
box:Dock(TOP)
local textentry = box:Add("DTextEntry")
textentry:Dock(LEFT)
textentry:SetWide(frame:GetWide() * 0.8)
local scroll = frame:Add("DScrollPanel")
scroll:Dock(FILL)
scroll:DockMargin(0, 25, 0, frame:GetTall() * 0.1)
scroll:GetCanvas().Paint = function(pnl, w, h)
surface.SetDrawColor(0, 0, 0, 255)
surface.DrawRect(0, 0, w, h)
end
local cached_urls = {}
local function recursiveLinkFinder(tbl)
for k, v in pairs(tbl) do
if istable(v) then
recursiveLinkFinder(v)
elseif isstring(v) then
if v:match("https?://[^%s%\"]+") then
if cached_urls[v] then
if #cached_urls[v].tbls > 1 then
cached_urls[v].label:SetText("Multiple")
--local str = table.concat(cached_urls[v].classes, ", ")
--cached_urls[v].label:SetTooltip(str)
end
table.insert(cached_urls[v].classes, tbl.ClassName)
table.insert(cached_urls[v].tbls, tbl)
return
end
local box = scroll:Add("DPanel")
box:Dock(TOP)
local label = box:Add("DLabel")
if cached_urls[v] then
print(cached_urls[v].tbls)
end
label:SetText(tbl.ClassName[1]:upper() .. tbl.ClassName:sub(2))
label:Dock(LEFT)
label:SetContentAlignment(5)
label:SetTextColor(Color(0, 0, 0))
local textentry = box:Add("DTextEntry")
textentry.tbls = {}
table.insert(textentry.tbls, tbl)
textentry.label = label
textentry.classes = {}
table.insert(textentry.classes, tbl.ClassName)
textentry:SetText(v)
textentry:Dock(FILL)
textentry:DockMargin(0, 0, 0, 5)
textentry:SetUpdateOnType(true)
cached_urls[v] = textentry
textentry.original = v
textentry.OnValueChange = function(self, value)
if textentry.original == value then
self:SetTextColor(Color(0, 0, 0))
else
self:SetTextColor(Color(255, 0, 0))
end
end
textentry.OnEnter = function(self)
for _, tbl in ipairs(self.tbls) do
tbl[k] = self:GetText()
end
self:SetTextColor(Color(255, 200, 0))
if self.original ~= self:GetText() then
self:SetTooltip("Before: " .. v)
else
self:SetToolTip(false)
end
end
textentry.OnFocusChanged = function(self, focus)
if not focus and self.original ~= self:GetText() then
self:OnEnter()
end
end
box.textentry = textentry
box.label = label
end
end
end
end
local loaded_pac
local loaded_path
local load = box:Add("DButton")
load:Dock(RIGHT)
load:DockMargin(0, 0, 0, 0)
load:SetWide((frame:GetWide() - textentry:GetWide()) / 2)
load:SetText("Load")
load.DoClick = function()
if textentry:GetText() == "" then return end
assert(file.Exists(textentry:GetText(), "DATA"), "file does not exist?")
loaded_pac = pace.luadata.ReadFile(textentry:GetText(), "DATA")
scroll:Clear()
recursiveLinkFinder(loaded_pac)
cached_urls = {}
frame.save:SetDisabled(false)
end
local browse = box:Add("DButton")
browse:Dock(RIGHT)
browse:DockMargin(0, 0, 0, 0)
browse:SetWide(load:GetWide() - 10) --+ 20)
browse:SetText("Browse")
local function recursiveMenu(path, menu)
local files, dirs = file.Find(BASE_PATH .. path .. "*", "DATA")
for _, dir in ipairs(dirs) do
if blacklist[dir] then continue end
local m, icon = menu:AddSubMenu(dir)
icon:SetImage(ICON_FOLDER)
recursiveMenu(dir .. "/", m)
end
for _, file in ipairs(files) do
menu:AddOption(file, function() textentry:SetText(BASE_PATH .. path .. file) end):SetImage(ICON_FILE)
end
end
browse.DoClick = function()
local menu = DermaMenu()
recursiveMenu("", menu)
menu:Open()
end
local save = frame:Add("DButton")
save:Dock(BOTTOM)
save:SetText("Save")
save:SetDisabled(true)
save.DoClick = function(self)
if self:GetDisabled() then return end
for k, tbl in ipairs(scroll:GetCanvas():GetChildren()) do
tbl.textentry:SetTextColor(Color(0, 255, 0))
end
pace.luadata.WriteFile(textentry:GetText(), loaded_pac)
end
frame.save = save
|
--------------------------------
-- @module ParticleFlower
-- @extend ParticleSystemQuad
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ParticleFlower] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ParticleFlower] initWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Create a flower particle system.<br>
-- return An autoreleased ParticleFlower object.
-- @function [parent=#ParticleFlower] create
-- @param self
-- @return ParticleFlower#ParticleFlower ret (return value: cc.ParticleFlower)
--------------------------------
-- Create a flower particle system withe a fixed number of particles.<br>
-- param numberOfParticles A given number of particles.<br>
-- return An autoreleased ParticleFlower object.<br>
-- js NA
-- @function [parent=#ParticleFlower] createWithTotalParticles
-- @param self
-- @param #int numberOfParticles
-- @return ParticleFlower#ParticleFlower ret (return value: cc.ParticleFlower)
--------------------------------
-- js ctor
-- @function [parent=#ParticleFlower] ParticleFlower
-- @param self
-- @return ParticleFlower#ParticleFlower self (return value: cc.ParticleFlower)
return nil
|
local settings = {}
return settings
|
local curl = require("plenary.curl")
local M = {}
M.search = function(query, target, scalaVersion)
local q = nil
local t = nil
local v = nil
if query == nil then
return {}
else
q = string.gsub(query, "%s+", "")
end
if target == nil then
t = "JVM"
else
t = string.gsub(target, "%s+", "")
end
if scalaVersion == nil then
v = "2.13"
else
v = string.gsub(scalaVersion, "%s+", "")
end
local parameters = {
q = q,
t = t,
v = v,
}
local url = string.gsub(
"https://index.scala-lang.org/api/search?q=$q&target=$t&scalaVersion=$v",
"$(%w+)",
parameters
)
local response = curl.request({
url = url,
method = "get",
accept = "application/json",
})
if response.status ~= 200 then
error("Failed to search scaladex, got a status: " .. response.status)
return {}
end
local decoded = vim.fn.json_decode(response.body)
-- print(response.body)
return decoded
end
M.get_project = function(org, repo)
if org == nil or repo == nil then
return {}
end
local organization = string.gsub(org, "%s+", "")
local repository = string.gsub(repo, "%s+", "")
local parameters = {
organization = organization,
repository = repository,
}
local url = string.gsub(
"https://index.scala-lang.org/api/project?organization=$organization&repository=$repository",
"$(%w+)",
parameters
)
local response = curl.request({
url = url,
method = "get",
accept = "application/json",
})
if response.status ~= 200 then
error("Failed to get project from scaladex, got a status: " .. response.status)
return {}
end
local decoded = vim.fn.json_decode(response.body)
-- print(response.body)
return decoded
end
return M
|
---@meta
---
---The `lovr.conf` callback lets you configure default settings for LÖVR.
---
---It is called once right before the game starts.
---
---Make sure you put `lovr.conf` in a file called `conf.lua`, a special file that's loaded before the rest of the framework initializes.
---
---
---### NOTE:
---Disabling the headset module can improve startup time a lot if you aren't intending to use `lovr.headset`.
---
---You can set `t.window` to nil to avoid creating the window. You can do it yourself later by using `lovr.graphics.createWindow`.
---
---If the `lovr.graphics` module is disabled or the window isn't created, attempting to use any functionality requiring graphics may cause a crash.
---
---Enabling the `t.graphics.debug` flag will add additional error checks and will send messages from the GPU driver to the `lovr.log` callback.
---
---This will decrease performance but can help provide information on performance problems or other bugs.
---
---The `headset.offset` field is a vertical offset applied to the scene for headsets that do not center their tracking origin on the floor.
---
---This can be thought of as a "default user height". Setting this offset makes it easier to design experiences that work in both seated and standing VR configurations.
---
---@type fun(t: table)
lovr.conf = nil
---
---This callback is called every frame.
---
---Use it to render the scene.
---
---If a VR headset is connected, anything rendered by this function will appear in the headset display.
---
---The display is cleared to the background color before this function is called.
---
---@type fun()
lovr.draw = nil
---
---The "lovr.errhand" callback is run whenever an error occurs.
---
---It receives two parameters. The first is a string containing the error message. The second is either nil, or a string containing a traceback (as returned by "debug.traceback()"); if nil, this means "lovr.errhand" is being called in the stack where the error occurred, and it can call "debug.traceback()" itself.
---
---"lovr.errhand" should return a handler function to run in a loop to show the error screen. This handler function is of the same type as the one returned by "lovr.run" and has the same requirements (such as pumping events). If an error occurs while this handler is running, the program will terminate immediately-- "lovr.errhand" will not be given a second chance. Errors which occur inside "lovr.errhand" or in the handler it returns may not be cleanly reported, so be careful.
---
---A default error handler is supplied that renders the error message as text to the headset and to the window.
---
---@type fun(message: string, traceback: string):function
lovr.errhand = nil
---
---The `lovr.focus` callback is called whenever the application acquires or loses focus (for example, when opening or closing the Steam dashboard).
---
---The callback receives a single argument, focused, which is a boolean indicating whether or not the application is now focused.
---
---It may make sense to pause the game or reduce visual fidelity when the application loses focus.
---
---@type fun(focused: boolean)
lovr.focus = nil
---
---This callback is called when a key is pressed.
---
---@type fun(key: lovr.KeyCode, scancode: number, repeating: boolean)
lovr.keypressed = nil
---
---This callback is called when a key is released.
---
---@type fun(key: lovr.KeyCode, scancode: number)
lovr.keyreleased = nil
---
---This callback is called once when the app starts.
---
---It should be used to perform initial setup work, like loading resources and initializing classes and variables.
---
---
---### NOTE:
---If the project was loaded from a restart using `lovr.event.restart`, the return value from the previously-run `lovr.restart` callback will be made available to this callback as the `restart` key in the `args` table.
---
---The `args` table follows the [Lua standard](https://en.wikibooks.org/wiki/Lua_Programming/command_line_parameter).
---
---The arguments passed in from the shell are put into a global table named `arg` and passed to `lovr.load`, but with indices offset such that the "script" (the project path) is at index 0.
---
---So all arguments (if any) intended for the project are at successive indices starting with 1, and the executable and its "internal" arguments are in normal order but stored in negative indices.
---
---@type fun(args: table)
lovr.load = nil
---
---This callback is called when a message is logged.
---
---The default implementation of this callback prints the message to the console using `print`, but it's possible to override this callback to render messages in VR, write them to a file, filter messages, and more.
---
---The message can have a "tag" that is a short string representing the sender, and a "level" indicating how severe the message is.
---
---The `t.graphics.debug` flag in `lovr.conf` can be used to get log messages from the GPU driver (tagged as `GL`).
---
---It is also possible to emit your own log messages using `lovr.event.push`.
---
---@type fun(message: string, level: string, tag: string)
lovr.log = nil
---
---This callback is called every frame after rendering to the headset and is usually used to render a mirror of the headset display onto the desktop window.
---
---It can be overridden for custom mirroring behavior.
---
---For example, you could render a single eye instead of a stereo view, apply postprocessing effects, add 2D UI, or render the scene from an entirely different viewpoint for a third person camera.
---
---
---### NOTE:
---When this callback is called, the camera is located at `(0, 0, 0)` and is looking down the negative-z axis.
---
---Note that the usual graphics state applies while `lovr.mirror` is invoked, so you may need to reset graphics state at the end of `lovr.draw` to get the result you want.
---
---@type fun()
lovr.mirror = nil
---
---This callback contains a permission response previously requested with `lovr.system.requestPermission`.
---
---The callback contains information on whether permission was granted or denied.
---
---@type fun(permission: lovr.Permission, granted: boolean)
lovr.permission = nil
---
---This callback is called right before the application is about to quit.
---
---Use it to perform any necessary cleanup work.
---
---A truthy value can be returned from this callback to abort quitting.
---
---@type fun():boolean
lovr.quit = nil
---
---This callback is called when the desktop window is resized.
---
---@type fun(width: number, height: number)
lovr.resize = nil
---
---This callback is called when a restart from `lovr.event.restart` is happening.
---
---A value can be returned to send it to the next LÖVR instance, available as the `restart` key in the argument table passed to `lovr.load`.
---
---Object instances can not be used as the restart value, since they are destroyed as part of the cleanup process.
---
---
---### NOTE:
---Only nil, booleans, numbers, and strings are supported types for the return value.
---
---@type fun():any
lovr.restart = nil
---
---This callback is the main entry point for a LÖVR program.
---
---It is responsible for calling `lovr.load` and returning the main loop function.
---
---@type fun():function
lovr.run = nil
---
---This callback is called when text has been entered.
---
---For example, when `shift + 1` is pressed on an American keyboard, `lovr.textinput` will be called with `!`.
---
---
---### NOTE:
---Some characters in UTF-8 unicode take multiple bytes to encode.
---
---Due to the way Lua works, the length of these strings will be bigger than 1 even though they are just a single character. `lovr.graphics.print` is compatible with UTF-8 but doing other string processing on these strings may require a library.
---
---Lua 5.3+ has support for working with UTF-8 strings.
---
---@type fun(text: string, code: number)
lovr.textinput = nil
---
---The `lovr.threaderror` callback is called whenever an error occurs in a Thread.
---
---It receives the Thread object where the error occurred and an error message.
---
---The default implementation of this callback will call `lovr.errhand` with the error.
---
---@type fun(thread: lovr.Thread, message: string)
lovr.threaderror = nil
---
---The `lovr.update` callback should be used to update your game's logic.
---
---It receives a single parameter, `dt`, which represents the amount of elapsed time between frames.
---
---You can use this value to scale timers, physics, and animations in your game so they play at a smooth, consistent speed.
---
---@type fun(dt: number)
lovr.update = nil
|
---@class CallbackHandler
local CallbackHandler = {
Type = "CallbackHandler",
---@type function
Callback = nil,
CanInvoke = true,
InvokeIsFunction = false
}
CallbackHandler.__index = CallbackHandler
function CallbackHandler:Create(callback, canInvoke)
local this = {
Callback = callback
}
if canInvoke ~= nil then
this.CanInvoke = canInvoke
if type(canInvoke) == "function" then
this.InvokeIsFunction = true
end
end
setmetatable(this, CallbackHandler)
return this
end
function CallbackHandler:Invoke(...)
local canInvoke = self.CanInvoke
if self.InvokeIsFunction then
canInvoke = self.CanInvoke()
end
if canInvoke then
self.Callback(...)
end
end
Classes.CallbackHandler = CallbackHandler
|
ItemList = {
-------------------------------
-------------------------------
------- WEAPON -------
-------------------------------
-------------------------------
['weapon_carbinerifle_mk2'] = { -- ☆☆☆☆☆
type = 'weapon',
name = 'MPX-C',
subtitle = 'Rifle de Assalto',
droppable = true,
weight = 0.5
},
['weapon_specialcarbine'] = { -- ☆☆☆☆
type = 'weapon',
name = 'H&K G36C',
subtitle = 'Rifle de Assalto',
droppable = true,
weight = 0.5
},
['weapon_assaultrifle'] = { -- ☆☆☆
type = 'weapon',
name = 'AK-47',
subtitle = 'Rifle de Assalto',
droppable = true,
weight = 0.5
},
['weapon_compactrifle'] = { -- ☆☆
type = 'weapon',
name = 'Pistol',
droppable = true,
weight = 0.5
},
['weapon_assaultsmg'] = { -- ☆☆☆☆☆
type = 'weapon',
name = 'SMG de Assalto',
droppable = true,
weight = 0.5
},
['weapon_smg_mk2'] = { -- ☆☆☆☆
type = 'weapon',
-- name = 'Sig Sauer MPX',
name = 'MPX',
droppable = true,
weight = 0.5
},
['weapon_machinepistol'] = { -- ☆☆☆
type = 'weapon',
name = 'TEC-9',
droppable = true,
weight = 1.2
},
['weapon_heavypistol'] = { -- ☆☆☆☆☆
type = 'weapon',
name = '1911',
droppable = true,
weight = 1.2
},
['weapon_combatpistol'] = { -- ☆☆☆☆
type = 'weapon',
name = 'H&K P2000',
droppable = true,
weight = 1.2
},
['weapon_vintagepistol'] = { -- ☆☆☆
type = 'weapon',
name = 'FN Model 1922',
droppable = true,
weight = 2.0
},
-------------------------------
-------------------------------
------- AMMO -------
-------------------------------
-------------------------------
['ammo_carbinerifle_mk2'] = {
type = "ammo",
name = '9mm (MPX-C)',
droppable = true,
weight = 0.1
},
['ammo_specialcarbine'] = {
type = "ammo",
name = '5.56x45mm (H&K G36C)',
droppable = true,
weight = 0.1
},
['ammo_assaultrifle'] = {
type = "ammo",
name = '7.62x39mm (AK-47)',
droppable = true,
weight = 0.1
},
['ammo_compactrifle'] = {
type = "ammo",
name = '7.62x39mm (AK-47 Pistol)',
droppable = true,
weight = 0.1
},
['ammo_assaultsmg'] = {
type = "ammo",
name = '5.7x28mm (SMG de Assalto)',
droppable = true,
weight = 0.1
},
['ammo_smg_mk2'] = {
type = "ammo",
name = '9mm (MPX)',
droppable = true,
weight = 0.1
},
['ammo_machinepistol'] = {
type = "ammo",
name = '9mm (TEC-9)',
droppable = true,
weight = 0.2
},
['ammo_heavypistol'] = {
type = "ammo",
name = '.45 ACP (1911)',
droppable = true,
weight = 0.2
},
['ammo_combatpistol'] = {
type = "ammo",
name = '.357 SIG (H&K P2000)',
droppable = true,
weight = 0.2
},
['ammo_vintagepistol'] = {
type = "ammo",
name = '.32 ACP (FN Model 1922)',
droppable = true,
weight = 0.2
},
-------------------------------
------- CONSUMABLE -------
-------------------------------
['consumable_bread'] = {
type = 'food',
name = 'Pão',
droppable = true,
weight = 0.1,
hungerVar = 1.01
},
['consumable_apple'] = {
type = 'food',
name = 'Maçã',
subtitle = 'asjiasjiajioaa',
droppable = true,
weight = 0.3,
hungerVar = 1.0
},
['consumable_carrot'] = {
type = 'food',
name = 'Cenoura',
droppable = true,
weight = 0.3,
hungerVar = 1.0
},
['consumable_waterbottle'] = {
type = 'beverage',
name = 'Água',
droppable = true,
weight = 0.2,
ThirstVar = 1.0
},
-------------------------------
-------------------------------
------- GENERIC -------
-------------------------------
-------------------------------
['generic_metalbruto'] = {
type = 'normal',
name = 'Minério de Metal',
droppable = true,
weight = 1.0
},
['generic_cobrebruto'] = {
type = 'normal',
name = 'Minério de Cobre',
droppable = true,
weight = 1.0
},
['generic_provision_coal'] = {
type = 'normal',
name = 'Carvão Refinado',
droppable = true,
weight = 1.0
},
['generic_provision_rf_wood_cobalt'] = {
type = 'normal',
name = 'Madeira Bruta',
droppable = true,
weight = 1.0
},
['generic_provision_goldbar_small'] = {
type = 'normal',
name = 'Barra de Metal',
droppable = true,
weight = 1.0
},
['generic_provision_disco_ammolite'] = {
type = 'normal',
name = 'Barra de Cobre',
droppable = true,
weight = 1.0
},
['generic_potassio'] = {
type = 'normal',
name = 'Nitrato de Potássio',
droppable = true,
weight = 1.0
},
['generic_enxofre'] = {
type = 'normal',
name = 'Enxofre',
droppable = true,
weight = 1.0
},
['generic_clothing_outfit_mp_ned_kelly'] = {
type = 'normal',
name = 'Pano',
droppable = true,
weight = 1.0
},
['generic_corda'] = {
type = 'normal',
name = 'Corda',
droppable = true,
weight = 1.0
},
['generic_tobacco'] = {
type = 'normal',
name = 'Tabaco',
droppable = true,
weight = 0.5
},
['generic_corn'] = {
type = 'normal',
name = 'Milho',
droppable = true,
weight = 0.5
},
['generic_picareta'] = {
type = 'normal',
name = 'Picareta',
droppable = true,
weight = 1.5
},
['generic_potassio'] = {
type = 'normal',
name = 'Potassio',
droppable = true,
weight = 0.5
},
['generic_enxofre'] = {
type = 'normal',
name = 'Enxofre',
droppable = true,
weight = 0.5
},
['generic_sugar'] = {
type = 'normal',
name = 'Açucar',
droppable = true,
weight = 0.5
},
['generic_blackmoney'] = {
type = 'normal',
name = 'Dinheiro sujo',
droppable = true,
weight = 0.01
},
['generic_money'] = {
type = 'normal',
name = 'Dólar',
droppable = false,
weight = 0.01
},
['generic_gold'] = {
type = 'normal',
name = 'Ouro',
droppable = true,
weight = 0.1
},
-------------------------------
-------------------------------
------- OTHERS -------
-------------------------------
-------------------------------
['folder_kit_keychain'] = {
type = 'normal',
name = 'Chave Misteriosa',
droppable = true,
weight = 0.5
},
['planting_tobaccoseed'] = {
type = 'planting',
name = 'Semente de Tabaco',
droppable = true,
weight = 0.2
},
['planting_sugarcaneseed'] = {
type = 'planting',
name = 'Semente de Cana',
droppable = true,
weight = 0.2
},
['planting_planting_cornseed'] = {
type = 'planting',
name = 'Semente de Milho',
droppable = true,
weight = 0.2
},
['planting_wateringcan'] = {
type = 'planting',
name = 'Balde de Água',
droppable = true,
weight = 1.5
},
['provision_fish_bullhead_catfish'] = {
type = 'provision',
name = 'Isca de Peixe',
droppable = true,
weight = 0.1
},
['kit_camp_simple'] = {
type = 'usable',
name = 'Fogueira',
droppable = true,
weight = 3.0
},
}
|
----------------------
-- Get addon object --
----------------------
local DS = LibStub("AceAddon-3.0"):GetAddon("Doom Shards", true)
if not DS then return end
---------------
-- Libraries --
---------------
local L = LibStub("AceLocale-3.0"):GetLocale("DoomShards")
local LSM = LibStub("LibSharedMedia-3.0")
-------------
-- Options --
-------------
local function displayOptions()
return {
order = 2,
type = "group",
name = L["Display"],
childGroups = "select",
cmdHidden = true,
get = function(info) return DS.db.display[info[#info]] end,
set = function(info, value) DS.db.display[info[#info]] = value; DS:Build() end,
args = {
enable = {
order = 1,
type = "toggle",
name = L["Enable"]
},
resource = {
order = 3,
type = "group",
name = L["Soul Shard Bars"],
args = {
resourceEnable = {
order = 0,
type = "toggle",
name = L["Enable"]
},
header0 = {
order = 0.1,
type="header",
name=L["Dimensions"]
},
height = {
order = 1,
type = "range",
name = function()
if DS.db.display.orientation == "Vertical" then
return L["Width"]
else
return L["Height"]
end
end,
min = 1,
max = 100,
step = 1
},
width = {
order = 2,
type = "range",
name = function()
if DS.db.display.orientation == "Vertical" then
return L["Height"]
else
return L["Width"]
end
end,
min = 1,
max = 100,
step = 1
},
spacing = {
order = 3,
type = "range",
name = L["Spacing"],
min = 0,
max = 100,
step = 1
},
header1 = {
order = 3.5,
type="header",
name=L["Shard Colors"]
},
color1 = {
order = 4,
type = "color",
name = L["Color Shard 1"],
hasAlpha = true,
get = function()
local r, b, g, a = DS.db.display.color1.r, DS.db.display.color1.b, DS.db.display.color1.g, DS.db.display.color1.a
return r, b, g, a
end,
set = function(info, r, b, g, a)
DS.db.display.color1.r, DS.db.display.color1.b, DS.db.display.color1.g, DS.db.display.color1.a = r, b, g, a
DS:Build()
end
},
color2 = {
order = 4.1,
type = "color",
name = L["Color Shard 2"],
hasAlpha = true,
get = function()
local r, b, g, a = DS.db.display.color2.r, DS.db.display.color2.b, DS.db.display.color2.g, DS.db.display.color2.a
return r, b, g, a
end,
set = function(info, r, b, g, a)
DS.db.display.color2.r, DS.db.display.color2.b, DS.db.display.color2.g, DS.db.display.color2.a = r, b, g, a
DS:Build()
end
},
color3 = {
order = 4.2,
type = "color",
name = L["Color Shard 3"],
hasAlpha = true,
get = function()
local r, b, g, a = DS.db.display.color3.r, DS.db.display.color3.b, DS.db.display.color3.g, DS.db.display.color3.a
return r, b, g, a
end,
set = function(info, r, b, g, a)
DS.db.display.color3.r, DS.db.display.color3.b, DS.db.display.color3.g, DS.db.display.color3.a = r, b, g, a
DS:Build()
end
},
color4 = {
order = 4.3,
type = "color",
name = L["Color Shard 4"],
hasAlpha = true,
get = function()
local r, b, g, a = DS.db.display.color4.r, DS.db.display.color4.b, DS.db.display.color4.g, DS.db.display.color4.a
return r, b, g, a
end,
set = function(info, r, b, g, a)
DS.db.display.color4.r, DS.db.display.color4.b, DS.db.display.color4.g, DS.db.display.color4.a = r, b, g, a
DS:Build()
end
},
color5 = {
order = 4.4,
type = "color",
name = L["Color Shard 5"],
hasAlpha = true,
get = function()
local r, b, g, a = DS.db.display.color5.r, DS.db.display.color5.b, DS.db.display.color5.g, DS.db.display.color5.a
return r, b, g, a
end,
set = function(info, r, b, g, a)
DS.db.display.color5.r, DS.db.display.color5.b, DS.db.display.color5.g, DS.db.display.color5.a = r, b, g, a
DS:Build()
end
},
spacer2 = {
order = 5.5,
type="description",
name=""
},
resourceCappedEnable = {
order = 6,
type = "toggle",
name = L["Shard Cap Color Change"],
desc = L["Change color of all Shards when reaching cap"]
},
resourceCappedColor = {
order = 7,
type = "color",
name = L["Color When Shard Capped"],
hasAlpha = true,
get = function()
return DS.db.display.resourceCappedColor.r, DS.db.display.resourceCappedColor.b, DS.db.display.resourceCappedColor.g, DS.db.display.resourceCappedColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.resourceCappedColor.r, DS.db.display.resourceCappedColor.b, DS.db.display.resourceCappedColor.g, DS.db.display.resourceCappedColor.a = r, b, g, a
DS:Build()
end,
hidden = not DS.db.display.resourceCappedEnable
},
spacer3 = {
order = 7.1,
type="description",
name=""
},
alwaysShowBorders = {
order = 7.2,
type = "toggle",
name = L["Show Depleted Shards"]
},
emptyColor = {
order = 7.3,
type = "color",
name = L["Color of Depleted Shards"],
hasAlpha = true,
get = function()
return DS.db.display.emptyColor.r, DS.db.display.emptyColor.b, DS.db.display.emptyColor.g, DS.db.display.emptyColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.emptyColor.r, DS.db.display.emptyColor.b, DS.db.display.emptyColor.g, DS.db.display.emptyColor.a = r, b, g, a
DS:Build()
end,
hidden = not DS.db.display.alwaysShowBorders
},
header3 = {
order = 8.5,
type="header",
name=L["Textures"]
},
useTexture = {
order = 8.6,
type = "toggle",
name = L["Use Texture for Shards"],
set = function(info, val)
DS.db.display.useTexture = val
DS:Build()
end
},
textureHandle = {
order = 9,
type = "select",
dialogControl = "LSM30_Statusbar",
name = L["Texture"],
values = LSM:HashTable("statusbar"),
hidden = not DS.db.display.useTexture
},
header4 = {
order = 9.5,
type="header",
name=L["Borders"]
},
borderColor = {
order = 10,
type = "color",
name = L["Border Color"],
hasAlpha = true,
get = function()
return DS.db.display.borderColor.r, DS.db.display.borderColor.b, DS.db.display.borderColor.g, DS.db.display.borderColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.borderColor.r, DS.db.display.borderColor.b, DS.db.display.borderColor.g, DS.db.display.borderColor.a = r, b, g, a
DS:Build()
end
},
header5 = {
order = 11.5,
type="header",
name=L["Visibility"]
},
visibilityConditionals = {
order = 12,
type = "input",
name = L["Visibility Conditionals"],
desc = L["Regulate display visibility with macro conditionals"],
width = "double",
set = function(info, val)
DS.db.display.visibilityConditionals = val
DS:Build()
end
},
fadeOutDuration = {
order = 13,
type = "range",
name = L["Fade Duration"],
min = 0.1,
max = 10,
step = 0.1,
hidden = not (DS.db.display.visibilityConditionals and DS.db.display.visibilityConditionals:find("fade"))
},
}
},
animations = {
order = 10,
type = "group",
name = L["Animations"],
args = {
header6 = {
order = 13.5,
type="header",
name=L["Soul Shard Bars"]
},
gainFlash = {
order = 14,
type = "toggle",
name = L["Flash on Shard Gain"],
set = function(info, val)
DS.db.display.gainFlash = val
DS:Build()
end
},
spacer5 = {
order = 14.5,
type = "description",
name = ""
},
resourceSpendIncludeHoG = {
order = 15,
type = "toggle",
name = L["Add. HoG Shards"],
desc = L["Include Doom tick indicator in Hand of Gul'dan casts. (Demonology only)"],
set = function(info, val)
DS.db.display.resourceSpendIncludeHoG = val
DS:Build()
end
},
spacer6 = {
order = 15.5,
type="description",
name=""
},
resourceGainPrediction = {
order = 16,
type = "toggle",
name = L["Indicate Shard Building"],
desc = L["Show prediction for gaining shards through casts"],
set = function(info, val)
DS.db.display.resourceGainPrediction = val
DS:Build()
end
},
resourceGainColor = {
order = 17,
type = "color",
name = L["Shard Gain Color"],
hasAlpha = true,
get = function()
return DS.db.display.resourceGainColor.r, DS.db.display.resourceGainColor.b, DS.db.display.resourceGainColor.g, DS.db.display.resourceGainColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.resourceGainColor.r, DS.db.display.resourceGainColor.b, DS.db.display.resourceGainColor.g, DS.db.display.resourceGainColor.a = r, b, g, a
DS:Build()
end,
hidden = not DS.db.display.resourceGainPrediction
},
spacer7 = {
order = 17.5,
type="description",
name=""
},
resourceSpendPrediction = {
order = 18,
type = "toggle",
name = L["Indicate Shard Spending"],
desc = L["Show prediction for spending shards through casts"],
set = function(info, val)
DS.db.display.resourceSpendPrediction = val
DS:Build()
end
},
resourceSpendColor = {
order = 19,
type = "color",
name = L["Shard Spend Color"],
hasAlpha = true,
get = function()
return DS.db.display.resourceSpendColor.r, DS.db.display.resourceSpendColor.b, DS.db.display.resourceSpendColor.g, DS.db.display.resourceSpendColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.resourceSpendColor.r, DS.db.display.resourceSpendColor.b, DS.db.display.resourceSpendColor.g, DS.db.display.resourceSpendColor.a = r, b, g, a
DS:Build()
end,
hidden = not DS.db.display.resourceSpendPrediction
},
header7 = {
order = 19.5,
type="header",
name=L["Text"]
},
fontColorHoGPrediction = {
order = 20,
type = "color",
name = L["Font Color for Hand of Gul'dan Prediction"],
desc = L["Color the text will change to if doom will tick before next possible Hand of Gul'dan cast."],
hasAlpha = true,
get = function()
return DS.db.display.fontColorHoGPrediction.r, DS.db.display.fontColorHoGPrediction.b, DS.db.display.fontColorHoGPrediction.g, DS.db.display.fontColorHoGPrediction.a
end,
set = function(info, r, b, g, a)
DS.db.display.fontColorHoGPrediction.r, DS.db.display.fontColorHoGPrediction.b, DS.db.display.fontColorHoGPrediction.g, DS.db.display.fontColorHoGPrediction.a = r, b, g, a
DS:Build()
end
},
},
},
text = {
order = 5,
type = "group",
name = L["Text"],
args = {
textEnable = {
order = 5,
type = "toggle",
name = L["Enable"]
},
header1 = {
order = 5.5,
type="header",
name=L["Font"]
},
fontName = {
order = 6,
type = "select",
dialogControl = "LSM30_Font",
name = L["Font"],
values = LSM:HashTable("font")
},
fontSize = {
order = 8,
type = "range",
name = L["Font Size"],
min = 1,
max = 32,
step = 1
},
fontFlags = {
order = 9,
type = "select",
style = "dropdown",
name = L["Font Flags"],
values = {
["None"] = L["None"],
["Shadow"] = L["Shadow"],
["OUTLINE"] = L["OUTLINE"],
["THICKOUTLINE"] = L["THICKOUTLINE"],
["MONOCHROMEOUTLINE"] = L["MONOCHROMEOUTLINE"]
}
},
spacer0 = {
order = 9.5,
type="description",
name=""
},
fontColor = {
order = 10,
type = "color",
name = L["Font Color"],
hasAlpha = true,
get = function()
return DS.db.display.fontColor.r, DS.db.display.fontColor.b, DS.db.display.fontColor.g, DS.db.display.fontColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.fontColor.r, DS.db.display.fontColor.b, DS.db.display.fontColor.g, DS.db.display.fontColor.a = r, b, g, a
DS:Build()
end
},
header2 = {
order = 10.5,
type="header",
name=L["Functionality"]
},
desc = {
order = 11,
type = "description",
name = L["Threshold when text begins showing first decimal place"],
},
remainingTimeThreshold = {
order = 12,
type = "range",
name = L["Time Threshold"],
min = 0,
max = 10,
step = 0.1
},
header3 = {
order = 13,
type="header",
name=L["Offset"]
},
stringXOffset = {
order = 14,
type = "range",
name = L["X Offset"],
min = -1000,
max = 1000,
step = 1,
get = function()
local offset = DS.db.display.orientation == "Vertical" and -DS.db.display.stringYOffset or DS.db.display.stringXOffset
if (DS.db.display.growthDirection == "Reversed") and (DS.db.display.orientation ~= "Vertical") then offset = -offset end
return offset
end,
set = function(info, val)
if DS.db.display.orientation == "Vertical" then
DS.db.display.stringYOffset = -val
else
if DS.db.display.growthDirection == "Reversed" then val = -val end
DS.db.display.stringXOffset = val
end
DS:Build()
end
},
stringYOffset = {
order = 15,
type = "range",
name = L["Y Offset"],
min = -1000,
max = 1000,
step = 1,
get = function()
local offset = DS.db.display.orientation == "Vertical" and DS.db.display.stringXOffset or DS.db.display.stringYOffset
if DS.db.display.growthDirection == "Reversed" and DS.db.display.orientation == "Vertical" then offset = -offset end
return offset
end,
set = function(info, val)
if DS.db.display.orientation == "Vertical" then
if DS.db.display.growthDirection == "Reversed" and DS.db.display.orientation == "Vertical" then val = -val end
DS.db.display.stringXOffset = val
else
DS.db.display.stringYOffset = val
end
DS:Build()
end
}
}
},
statusbar = {
order = 4,
type = "group",
name = L["Doom Tick Indicator Bars"],
args = {
statusbarEnable = {
order = 1,
type = "toggle",
name = L["Enable"],
desc = L["Enable bars for incoming Doom ticks"]
},
header1 = {
order = 2,
type="header",
name=L["Consolidate Ticks"]
},
descConsolidateTicks = {
order = 2.1,
type = "description",
name = L["Consolidate individual ticks to full expected shards"],
},
consolidateTicks = {
order = 2.2,
type = "toggle",
name = L["Consolidate Ticks"]
},
header2 = {
order = 3,
type="header",
name=L["Colors"]
},
statusbarColor = {
order = 4,
type = "color",
name = L["Bar Color"],
hasAlpha = true,
get = function()
return DS.db.display.statusbarColor.r, DS.db.display.statusbarColor.b, DS.db.display.statusbarColor.g, DS.db.display.statusbarColor.a
end,
set = function(info, r, b, g, a)
DS.db.display.statusbarColor.r, DS.db.display.statusbarColor.b, DS.db.display.statusbarColor.g, DS.db.display.statusbarColor.a = r, b, g, a
DS:Build()
end
},
statusbarColorBackground = {
order = 5,
type = "color",
name = L["Background Color"],
hasAlpha = true,
get = function()
return DS.db.display.statusbarColorBackground.r, DS.db.display.statusbarColorBackground.b, DS.db.display.statusbarColorBackground.g, DS.db.display.statusbarColorBackground.a
end,
set = function(info, r, b, g, a)
DS.db.display.statusbarColorBackground.r, DS.db.display.statusbarColorBackground.b, DS.db.display.statusbarColorBackground.g, DS.db.display.statusbarColorBackground.a = r, b, g, a
DS:Build()
end
},
header3 = {
order = 9,
type="header",
name=L["Overcapping"]
},
statusbarCount = {
order = 10,
type = "range",
name = L["Additional Doom Indicators"],
min = 0,
max = 20,
step = 1
},
statusbarColorOverflowForeground = {
order = 10.9,
type = "color",
name = L["\"Overcap Shards\" Bar Color"],
desc = L["Color of additional indicators for overcapping with Doom ticks"],
hasAlpha = true,
get = function()
return DS.db.display.statusbarColorOverflowForeground.r, DS.db.display.statusbarColorOverflowForeground.b, DS.db.display.statusbarColorOverflowForeground.g, DS.db.display.statusbarColorOverflowForeground.a
end,
set = function(info, r, b, g, a)
DS.db.display.statusbarColorOverflowForeground.r, DS.db.display.statusbarColorOverflowForeground.b, DS.db.display.statusbarColorOverflowForeground.g, DS.db.display.statusbarColorOverflowForeground.a = r, b, g, a
DS:Build()
end
},
statusbarColorOverflow = {
order = 11,
type = "color",
name = L["\"Overcap Shards\" Color"],
hasAlpha = true,
get = function()
return DS.db.display.statusbarColorOverflow.r, DS.db.display.statusbarColorOverflow.b, DS.db.display.statusbarColorOverflow.g, DS.db.display.statusbarColorOverflow.a
end,
set = function(info, r, b, g, a)
DS.db.display.statusbarColorOverflow.r, DS.db.display.statusbarColorOverflow.b, DS.db.display.statusbarColorOverflow.g, DS.db.display.statusbarColorOverflow.a = r, b, g, a
DS:Build()
end
},
header4 = {
order = 12,
type="header",
name=L["Direction"]
},
statusbarReverse = {
order = 13,
type = "toggle",
name = L["Reverse Direction"],
desc = L["Fill indicator from right to left"]
},
header5 = {
order = 14,
type="header",
name=L["Offset"]
},
statusbarXOffset = {
order = 15,
type = "range",
name = L["X Offset"],
min = -math.ceil(GetScreenWidth()),
max = math.ceil(GetScreenWidth()),
step = 1,
get = function()
local offset = DS.db.display.orientation == "Vertical" and -DS.db.display.statusbarYOffset or DS.db.display.statusbarXOffset
if (DS.db.display.growthDirection == "Reversed") and (DS.db.display.orientation ~= "Vertical") then offset = -offset end
return offset
end,
set = function(info, val)
if DS.db.display.orientation == "Vertical" then
DS.db.display.statusbarYOffset = -val
else
if DS.db.display.growthDirection == "Reversed" then val = -val end
DS.db.display.statusbarXOffset = val
end
DS:Build()
end
},
statusbarYOffset = {
order = 16,
type = "range",
name = L["Y Offset"],
min = -math.ceil(GetScreenHeight()),
max = math.ceil(GetScreenHeight()),
step = 1,
get = function()
local offset = DS.db.display.orientation == "Vertical" and DS.db.display.statusbarXOffset or DS.db.display.statusbarYOffset
if DS.db.display.growthDirection == "Reversed" and DS.db.display.orientation == "Vertical" then offset = -offset end
return offset
end,
set = function(info, val)
if DS.db.display.orientation == "Vertical" then
if DS.db.display.growthDirection == "Reversed" and DS.db.display.orientation == "Vertical" then val = -val end
DS.db.display.statusbarXOffset = val
else
DS.db.display.statusbarYOffset = val
end
DS:Build()
end
},
}
},
positioning = {
order = 7,
type = "group",
name = L["Positioning"],
args = {
orientation = {
order = 1,
type = "select",
style = "dropdown",
name = L["Orientation"],
values = {
["Horizontal"] = L["Horizontal"],
["Vertical"] = L["Vertical"]
}
},
growthDirection = {
order = 2,
type = "select",
name = L["Growth direction"],
desc = L["Order in which Shards get filled in"],
values = {
["Regular"] = L["Regular"],
["Reversed"] = L["Reversed"]
}
},
header2 = {
order = 2.5,
type = "header",
name = L["Anchor"]
},
anchor = {
order = 3,
type = "select",
style = "dropdown",
name = L["Anchor Point"],
values = {
["CENTER"] = "CENTER",
["BOTTOM"] = "BOTTOM",
["TOP"] = "TOP",
["LEFT"] = "LEFT",
["RIGHT"] = "RIGHT",
["BOTTOMLEFT"] = "BOTTOMLEFT",
["BOTTOMRIGHT"] = "BOTTOMRIGHT",
["TOPLEFT"] = "TOPLEFT",
["TOPRIGHT"] = "TOPRIGHT"
}
},
anchorFrame = {
order = 4,
type = "input",
name = L["Anchor Frame"],
desc = L["Will change to UIParent when manually dragging frame."]
},
header3 = {
order = 4.5,
type = "header",
name = L["Position"]
},
posX = {
order = 5,
type = "range",
name = L["X Position"],
min = -math.ceil(GetScreenWidth()),
max = math.ceil(GetScreenWidth()),
step = 1
},
posY = {
order = 6,
type = "range",
name = L["Y Position"],
min = -math.ceil(GetScreenHeight()),
max = math.ceil(GetScreenHeight()),
step = 1
},
}
}
}
}
end
local defaultSettings = {
profile = {
enable = true,
resourceEnable = true,
anchor = "CENTER",
anchorFrame = "UIParent",
posX = 0,
posY = 0,
height = 8,
width = 32,
spacing = 1,
color1 = {r=0.38, b=0.23, g=0.51, a=1},
color2 = {r=0.38, b=0.23, g=0.51, a=1},
color3 = {r=0.38, b=0.23, g=0.51, a=1},
color4 = {r=0.38, b=0.23, g=0.51, a=1},
color5 = {r=0.38, b=0.23, g=0.51, a=1}, -- {r=0.51, b=0.00, g=0.24, a=1}
textEnable = true,
fontSize = 15,
fontName = "Friz Quadrata TT",
fontFlags = "Shadow",
fontColor = {r=1, b=1, g=1, a=1},
fontColorHoGPrediction = {r=0.51, b=0.00, g=0.24, a=1},
remainingTimeThreshold = 4,
stringXOffset = 0,
stringYOffset = 6,
visibilityConditionals = "[mod:alt] [harm] [combat] show; fade",
fadeOutDuration = 0.5,
orientation = "Horizontal",
growthDirection = "Regular",
useTexture = false,
textureHandle = "Empty",
borderColor = {r=0, b=0, g=0, a=1},
alwaysShowBorders = false, -- Legacy name, toggles showing of depleted resources
emptyColor = {r=0.06, b=0.06, g=0.06, a=1},
statusbarEnable = true,
statusbarColor = {r=0.33, b=0.33, g=0.33, a=0.5},
statusbarColorBackground = {r=0.06, b=0.06, g=0.06, a=1},
statusbarColorOverflowForeground = {r=0.33, b=0.33, g=0.33, a=0.5},
statusbarColorOverflow = {r=0.51, b=0.00, g=0.24, a=1},
statusbarReverse = false,
statusbarXOffset = 0,
statusbarYOffset = 6,
statusbarCount = 5,
resourceCappedEnable = true,
resourceCappedColor = {r=0.51, b=0.00, g=0.24, a=1},
gainFlash = true,
resourceGainPrediction = false,
resourceGainColor = {r=0.4, b=0.4, g=0.4, a=1},--{r=0.51, b=0.00, g=0.24, a=1},
resourceSpendPrediction = true,
resourceSpendColor = {r=0.4, b=0.4, g=0.4, a=1},
resourceSpendIncludeHoG = true,
consolidateTicks = true,
}
}
DS:AddDisplayOptions("display", displayOptions, defaultSettings)
|
-- local function data(file, tag, names, stripFunc, postFunc)
local parser = require "otherData.featParser"
local names =
{
"Commander",
"Mobilize",
"Leadership",
"Battle Conductor",
"Complex Orders",
"Tip the Scales",
"Scheme Twist"
}
local m = string.match
local function strip(parser, str)
-- local firstFeat = parser.names[1]
-- return m(str, "(.+)Cone, Line, Burst, and Blast Moves\r\n")
return str
end
return parser("commander.txt", "Commander Class", names, strip)
|
--------------------------------
-- @module TurnOffTiles
-- @extend TiledGrid3DAction
-- @parent_module cc
--------------------------------
-- brief Show the tile at specified position.<br>
-- param pos The position index of the tile should be shown.
-- @function [parent=#TurnOffTiles] turnOnTile
-- @param self
-- @param #vec2_table pos
-- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles)
--------------------------------
-- brief Hide the tile at specified position.<br>
-- param pos The position index of the tile should be hide.
-- @function [parent=#TurnOffTiles] turnOffTile
-- @param self
-- @param #vec2_table pos
-- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles)
--------------------------------
-- brief Initializes the action with grid size, random seed and duration.<br>
-- param duration Specify the duration of the TurnOffTiles action. It's a value in seconds.<br>
-- param gridSize Specify the size of the grid.<br>
-- param seed Specify the random seed.<br>
-- return If the Initialization success, return true; otherwise, return false.
-- @function [parent=#TurnOffTiles] initWithDuration
-- @param self
-- @param #float duration
-- @param #size_table gridSize
-- @param #unsigned int seed
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @overload self, float, size_table, unsigned int
-- @overload self, float, size_table
-- @function [parent=#TurnOffTiles] create
-- @param self
-- @param #float duration
-- @param #size_table gridSize
-- @param #unsigned int seed
-- @return TurnOffTiles#TurnOffTiles ret (return value: cc.TurnOffTiles)
--------------------------------
--
-- @function [parent=#TurnOffTiles] startWithTarget
-- @param self
-- @param #cc.Node target
-- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles)
--------------------------------
--
-- @function [parent=#TurnOffTiles] clone
-- @param self
-- @return TurnOffTiles#TurnOffTiles ret (return value: cc.TurnOffTiles)
--------------------------------
--
-- @function [parent=#TurnOffTiles] update
-- @param self
-- @param #float time
-- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles)
--------------------------------
--
-- @function [parent=#TurnOffTiles] TurnOffTiles
-- @param self
-- @return TurnOffTiles#TurnOffTiles self (return value: cc.TurnOffTiles)
return nil
|
vim.cmd([[
function! ToggleNerdTree()
if g:NERDTree.IsOpen()
NERDTreeToggle
else
if @% == ""
NERDTreeToggle
else
NERDTreeFind
norm zz
endif
endif
endfunction
]])
|
local RunService = game:GetService("RunService")
local Stories = script.Parent.Parent.Parent.Parent.Parent.Parent
local Packages = Stories.Parent.Parent
local Roact = require(Packages.Roact)
local Gamepad = require(Packages.RoactGamepad)
local UIBloxConfig = require(Stories.UIBloxStorybookConfig)
local FocusContainer = require(Packages.StoryComponents.FocusContainer)
local InputManager = require(Packages.StoryComponents.InputManager)
local App = Packages.UIBlox.App
local SmallRadioButtonGroup = require(App.Cell.Small.SelectionGroup.SmallRadioButtonGroup)
local withStyle = require(Packages.UIBlox.Core.Style.withStyle)
local PADDING = 10
local ITEMS = {
{ text = "Selection 1", key = "1" },
{ text = "Selection 3", key = "3" },
{ text = "Selection 2", key = "2" },
{ text = "Disabled Cell", key = "4", isDisabled = true }
}
local SmallRadioButtonGroupStory = Roact.PureComponent:extend("SmallRadioButtonGroupStory")
function SmallRadioButtonGroupStory:init()
self.state = {
selectedValue = "1",
}
self.setSelectedValue = function(value)
if value == self.state.selectedValue then
return
end
self:setState({
selectedValue = value,
})
end
end
function SmallRadioButtonGroupStory:render()
local selectedText = ""
for _, item in ipairs(ITEMS) do
if item.key == self.state.selectedValue then
selectedText = item.text
end
end
return withStyle(function(stylePalette)
local theme = stylePalette.Theme
return Roact.createElement("Frame", {
Size = UDim2.fromOffset(250, 250),
BackgroundTransparency = 1,
}, {
UIListLayout = Roact.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Vertical,
Padding = UDim.new(0, PADDING),
}),
InputManager = UIBloxConfig.enableExperimentalGamepadSupport
and Gamepad.withFocusController(function(focusController)
return Roact.createElement(InputManager, {
focusController = focusController,
})
end),
Container = Roact.createElement(UIBloxConfig.enableExperimentalGamepadSupport and Gamepad.Focusable.Frame
or "Frame", {
Size = UDim2.new(1, 0, 0, 224),
BackgroundTransparency = 0,
BorderSizePixel = 0,
BackgroundColor3 = theme[self.props.backgroundTheme].Color,
NextSelectionDown = self.props.NextSelectionDown,
NextSelectionUp = self.props.NextSelectionUp,
[Roact.Ref] = self.props[Roact.Ref],
}, {
SmallRadioButtonGroup = Roact.createElement(SmallRadioButtonGroup, {
onActivated = self.setSelectedValue,
items = ITEMS,
selectedValue = self.state.selectedValue,
layoutOrder = 1,
NextSelectionDown = self.props.NextSelectionDown,
NextSelectionUp = self.props.NextSelectionUp,
}),
}),
SelectedText = Roact.createElement("TextLabel", {
Size = UDim2.new(1, 0, 0, 20),
Font = Enum.Font.Gotham,
TextSize = 24,
TextXAlignment = Enum.TextXAlignment.Left,
Text = selectedText .." is selected",
LayoutOrder = 2,
})
})
end)
end
local GamepadContainer = Roact.PureComponent:extend("GamepadContainer")
function GamepadContainer:init()
self.refs = Gamepad.createRefCache()
end
function GamepadContainer:render()
return Roact.createElement("ScrollingFrame", {
Size = UDim2.new(1, 0, 1, 0),
BorderSizePixel = 0,
CanvasSize = UDim2.new(1, 0, 0, 850),
BackgroundTransparency = 1,
}, {
UIListLayout = Roact.createElement("UIListLayout", {
SortOrder = Enum.SortOrder.LayoutOrder,
FillDirection = Enum.FillDirection.Vertical,
}),
Group1 = Roact.createElement("Frame", {
Size = UDim2.new(1, 0, 0, 400),
BorderSizePixel = 0,
LayoutOrder = 1,
BackgroundTransparency = 1,
} , {
BackgroundDefault = Roact.createElement(SmallRadioButtonGroupStory, {
backgroundTheme = "BackgroundDefault",
[Roact.Ref] = self.refs.group1,
NextSelectionDown = self.refs.group2,
}),
}),
Group2 = Roact.createElement("Frame", {
Size = UDim2.new(1, 0, 0, 400),
BorderSizePixel = 0,
LayoutOrder = 2,
BackgroundTransparency = 1,
} , {
BackgroundUITheme = Roact.createElement(SmallRadioButtonGroupStory, {
backgroundTheme = "BackgroundUIDefault",
[Roact.Ref] = self.refs.group2,
NextSelectionUp = self.refs.group1,
})
})
})
end
local function wrapStoryForGamepad(story)
if not UIBloxConfig.enableExperimentalGamepadSupport or not RunService:IsRunMode() then
return story
end
return Roact.createElement(FocusContainer, {}, {
GamepadStories = story,
})
end
return {
stories = {
{
name = "SmallRadioButtonGroup (BackgroundUITheme)",
summary = "Cell.Small.SelectionGroup.SmallRadioButtonGroup",
story = function(props)
return wrapStoryForGamepad(Roact.createElement(SmallRadioButtonGroupStory, {
backgroundTheme = "BackgroundUIDefault",
}))
end
},
{
name = "SmallRadioButtonGroup (BackgroundDefault theme)",
summary = "Cell.Small.SelectionGroup.SmallRadioButtonGroup",
story = wrapStoryForGamepad(Roact.createElement(SmallRadioButtonGroupStory, {
backgroundTheme = "BackgroundDefault",
})),
}
}
}
|
#!/usr/bin/env tjost
--[[
* Copyright (c) 2015 Hanspeter Portner ([email protected])
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the Artistic License 2.0 as published by
* The Perl Foundation.
*
* This source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Artistic License 2.0 for more details.
*
* You should have received a copy of the Artistic License 2.0
* along the source as a COPYING file. If not, obtain it from
* http://www.perlfoundation.org/artistic_license_2_0.
--]]
midi = require('midi_out')
map = require('map')
mfr14_dummy = require('mfr14_dummy')
mfr14_dummy({
name = 'mini',
scsynth = {
out_offset = 2,
gid_offset = 100,
sid_offset = 200,
inst = {'base1', 'lead1'}
},
midi = {
--effect = SOUND_EFFECT_5,
effect = VOLUME,
gid_offset = 0,
map = function(n) return map_linear:new({n=n, oct=2}) end
},
drum = false,
data = false
})
|
--SENSOR TYPE
local SENSOR_OPTICAL = 0
local SENSOR_RADAR = 1
local SENSOR_IRST = 2
local SENSOR_RWR = 3
--RADAR
local RADAR_AS = 0
local RADAR_SS = 1
local RADAR_MULTIROLE = 2
--
local ASPECT_HEAD_ON = 0
local ASPECT_TAIL_ON = 1
--
local HEMISPHERE_UPPER = 0
local HEMISPHERE_LOWER = 1
--IRST
local ENGINE_MODE_FORSAGE = 0
local ENGINE_MODE_MAXIMAL = 1
local ENGINE_MODE_MINIMAL = 2
--OPTIC
local OPTIC_SENSOR_TV = 0
local OPTIC_SENSOR_LLTV = 1
local OPTIC_SENSOR_IR = 2
-- Buk-M1-2 SENSORS
CHAIR_BACK =
{
Name = "SA-17 Buk TR",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 120000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 120000.0,
[ASPECT_TAIL_ON] = 120000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 120000.0,
[ASPECT_TAIL_ON] = 120000.0
}
},
lock_on_distance_coeff = 0.5,
velocity_limits =
{
radial_velocity_min = 10,
},
scan_period = 1.0,
}
declare_sensor(CHAIR_BACK)
-- S-300V SENSORS
GRILL_PAN =
{
Name = "S-300V 9S32 tr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 80.0}
},
max_measuring_distance = 240000,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 150000.0,
[ASPECT_TAIL_ON] = 150000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 150000.0,
[ASPECT_TAIL_ON] = 150000.0
}
},
lock_on_distance_coeff =0.8,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(GRILL_PAN)
HIGH_SCREEN =
{
Name = "S-300V 9S19 sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 70.0}
},
max_measuring_distance = 280000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 175000.0,
[ASPECT_TAIL_ON] = 175000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 175000.0,
[ASPECT_TAIL_ON] = 175000.0
}
},
lock_on_distance_coeff = 0.8,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(HIGH_SCREEN)
BILL_BOARD =
{
Name = "S-300V 9S15 sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 75.0}
},
max_measuring_distance = 385000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 240000.0,
[ASPECT_TAIL_ON] = 240000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 240000.0,
[ASPECT_TAIL_ON] = 240000.0
}
},
lock_on_distance_coeff = 0.8,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(BILL_BOARD)
-- S-300VM SENSORS
GRILL_PAN_M =
{
Name = "S-300VM 9S32ME tr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 80.0}
},
max_measuring_distance = 370000,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 230000.0,
[ASPECT_TAIL_ON] = 230000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 230000.0,
[ASPECT_TAIL_ON] = 230000.0
}
},
lock_on_distance_coeff =0.95,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(GRILL_PAN_M)
HIGH_SCREEN_M =
{
Name = "S-300VM 9S19M2 sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 70.0}
},
max_measuring_distance = 500000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 310000.0,
[ASPECT_TAIL_ON] = 310000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 310000.0,
[ASPECT_TAIL_ON] = 310000.0
}
},
lock_on_distance_coeff = 0.9,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(HIGH_SCREEN_M)
BILL_BOARD_M =
{
Name = "S-300VM 9S15M2 sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 75.0}
},
max_measuring_distance = 515000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 320000.0,
[ASPECT_TAIL_ON] = 320000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 320000.0,
[ASPECT_TAIL_ON] = 320000.0
}
},
lock_on_distance_coeff = 0.9,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(BILL_BOARD_M)
-- S-300PS/PMU1 SENSORS
BIG_BIRD =
{
Name = "S-300PS 64H6E TRAILER sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 200000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 200000.0,
[ASPECT_TAIL_ON] = 200000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 200000.0,
[ASPECT_TAIL_ON] = 200000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 15.0,
},
scan_period = 1.0,
}
declare_sensor(BIG_BIRD)
CLAM_SHELL =
{
Name = "S-300PS SA-10B 40B6MD MAST sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 260000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 120000.0,
[ASPECT_TAIL_ON] = 120000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 120000.0,
[ASPECT_TAIL_ON] = 120000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 15.0,
},
scan_period = 1.0,
}
declare_sensor(CLAM_SHELL)
FLAP_LID =
{
Name = "S-300PS 40B6M MAST tr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 260000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 160000.0,
[ASPECT_TAIL_ON] = 160000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 160000.0,
[ASPECT_TAIL_ON] = 160000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(FLAP_LID)
FLAP_LID_TRUCK =
{
Name = "S-300PS 30H6 TRAILER tr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 260000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 160000.0,
[ASPECT_TAIL_ON] = 160000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 160000.0,
[ASPECT_TAIL_ON] = 160000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(FLAP_LID_TRUCK)
-- S-300PMU2 SENSORS
BIG_BIRD_E =
{
Name = "S-300PMU2 64H6E2 sr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 330000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 330000.0,
[ASPECT_TAIL_ON] = 330000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 330000.0,
[ASPECT_TAIL_ON] = 330000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 15.0,
},
scan_period = 1.0,
}
declare_sensor(BIG_BIRD_E)
GRAVE_STONE =
{
Name = "S-300PMU2 92H6E tr",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 270000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 270000.0,
[ASPECT_TAIL_ON] = 270000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 270000.0,
[ASPECT_TAIL_ON] = 270000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 10.0,
},
scan_period = 1.0,
}
declare_sensor(GRAVE_STONE)
-- SAMPT/SAMPT NG SENSOR
ARABEL =
{
Name = "SAMP/T ARABEL str",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 220000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 100000.0,
[ASPECT_TAIL_ON] = 100000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 100000.0,
[ASPECT_TAIL_ON] = 100000.0
}
},
lock_on_distance_coeff = 0.9,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 15.0,
},
scan_period = 1.0,
}
declare_sensor(ARABEL)
GROUND_FIRE_300 =
{
Name = "SAMP/T NG GF300 str",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 90.0}
},
max_measuring_distance = 650000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 400000.0,
[ASPECT_TAIL_ON] = 400000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 400000.0,
[ASPECT_TAIL_ON] = 400000.0
}
},
lock_on_distance_coeff = 0.9,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 15.0,
},
scan_period = 1.0,
}
declare_sensor(GROUND_FIRE_300)
-- SOVIET & RUSSIAN ARM DECOYS
GAZETCHIK_DECOY =
{
Name = "34Ya6E Gazetchik E decoy",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {-15.0, 60.0}
},
max_measuring_distance = 20000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 20000.0,
[ASPECT_TAIL_ON] = 20000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 20000.0,
[ASPECT_TAIL_ON] = 20000.0
}
},
lock_on_distance_coeff = 0.01,
multiple_targets_tracking = true,
velocity_limits =
{
radial_velocity_min = 1.0,
},
scan_period = 0.2,
}
declare_sensor(GAZETCHIK_DECOY)
-- SON-9 FIRE CAN RADAR
FIRE_CAN =
{
Name = "SON-9 Fire Can TR",
category = SENSOR_RADAR,
type = RADAR_AS,
scan_volume =
{
azimuth = {-180.0, 180.0},
elevation = {0.0, 89.0}
},
max_measuring_distance = 50000.0,
detection_distance =
{
[HEMISPHERE_UPPER] =
{
[ASPECT_HEAD_ON] = 35000.0,
[ASPECT_TAIL_ON] = 35000.0
},
[HEMISPHERE_LOWER] =
{
[ASPECT_HEAD_ON] = 35000.0,
[ASPECT_TAIL_ON] = 35000.0
}
},
lock_on_distance_coeff = 0.85,
multiple_targets_tracking = false,
velocity_limits =
{
radial_velocity_min = 0.0,
},
scan_period = 1.0,
}
declare_sensor(FIRE_CAN)
|
vim.g.mapleader = ';'
local map = require("me.map_utils").map
local cmd_map = require("me.map_utils").cmd_map
local plug_map = require("me.map_utils").plug_map
--[[
_
__ _ ___ _ __ ___ _ __ __ _| |
/ _` |/ _ \ '_ \ / _ \ '__/ _` | |
| (_| | __/ | | | __/ | | (_| | |
\__, |\___|_| |_|\___|_| \__,_|_|
|___/
]]
-- Free up 'G' to be a generic prefix, and make gG do what G used to do
map{keys = "gG", to = "G"}
map{keys = "gG", to = "G", mode = "o"}
map{keys = "G", to = '', recurse = true}
-- change Y to only select the line starting from the cursor
map{keys = "Y", to = "y$"}
-- nop-out semicolon, it's my mapleader key
map{keys = ";", to = '', recurse = true}
-- but restore the functionality by using the comma key
map{keys = ",", to = ";"}
-- Easily (un)indent again in visual mode by immediately re-selecting
map{keys = "<", to = "<gv", mode = "v"}
map{keys = ">", to = ">gv", mode = "v"}
-- Sometimes you just need to move a character or two in insert mode. Don't
-- make these a habit, though!
map{keys = "<C-j>", to = "<Down>", mode = "i"}
map{keys = "<C-k>", to = "<Up>", mode = "i"}
map{keys = "<C-h>", to = "<Left>", mode = "i"}
map{keys = "<C-l>", to = "<Right>", mode = "i"}
-- Swap ` and ', making ' more precise (line & column) by default
map{keys = "`", to = "'"}
map{keys = "'", to = "`"}
-- Make interacting with the spell checking a little easier
map{keys = "zP", to = ":set spell!<CR>"} -- Toggle spell check quickly
map{keys = "zp", to = "1z="} -- Accept the first spell correction
-- Attempt to clear the screen of artifacts and clear search highlight
map{keys = "<C-l>", to = "<c-l>:nohlsearch<CR>:redraw<CR>", recurse = true}
-- Map H and L to jump to the beginning or end of the line. H is smarter, in
-- that it jumps between the first non-whitespace character or actual column 0.
map{keys = "H", to = "(col('.') == matchend(getline('.'), '^\\s*')+1 ? '0' : '^')", expression = true}
map{keys = "L", to = '$', recurse = true}
-- Easily get out of insert mode in the terminal
map{keys = "<C-s>", to = '<C-\\><C-n>', recurse = true, mode = "t"}
-- Fuzzy find a file to edit
cmd_map{keys = "ZE", command = 'Telescope find_files previewer=false prompt_prefix=🔍\\ '}
cmd_map{keys = "ZD", command = "BufferWipeout"}
-- Save the file only when the buffer has been modified.
cmd_map{keys = "ZW", command = "update"}
-- Create & edit a snippets file for this filetype
cmd_map{keys = "ZP", command = "COQsnips edit"}
-- Easily edit my vimrc file
-- TODO: integrate it with my workspace concept, editing a project-local lua file instead
cmd_map{keys = "ZL", command = "edit " .. vim.fn.stdpath("config") .. "/init.lua"}
-- Easily search the directory
cmd_map{keys = "ZG", command = "Grepper"}
plug_map{mode = "o", keys = "gs", command = "GrepperOperator"}
plug_map{mode = "x", keys = "gs", command = "GrepperOperator"}
-- Visualize the undo history of the file
cmd_map{keys = "ZU", command = "MundoToggle"}
-- Find all of the code tags (TODO, NOTE, FIXME, etc) in the project
cmd_map{keys = "ZT", command = "CodeTagSearch"}
cmd_map{keys = "ZR", command = "TroubleToggle"}
-- Tap - to jump into a file pane
cmd_map{keys = "-", command = "NvimTreeToggle"}
-- a much smarter <C-a> and <C-x> that know how to flip through enumerated lists
-- and manipulate additional number formats & dates
plug_map{keys = "<C-a>", command = 'dial-increment'}
plug_map{keys = "<C-x>", command = 'dial-decrement'}
plug_map{mode = 'v', keys = "<C-a>", command = 'dial-increment'}
plug_map{mode = 'v', keys = "<C-x>", command = 'dial-decrement'}
plug_map{mode = 'v', keys = "g<C-a>", command = 'dial-increment'}
plug_map{mode = 'v', keys = "g<C-x>", command = 'dial-decrement'}
-- Inspired by tpope's rsi.vim, buch much more constrained:
-- jump to the beginning of the line
map{mode = 'i', keys = "<C-a>", to = "<C-o>H", recurse = true}
map{mode = 'c', keys = "<C-a>", to = "<Home>"}
-- jump to the end of the line
-- (command mode already has this binding)
-- (insert mode is covered by compe falling back to <End> in the mapping above)
-- easy buffer switching, that's barbar-aware
if packer_exists then
cmd_map{keys = "<C-n>", command = "BufferNext"}
cmd_map{keys = "<C-p>", command = "BufferPrev"}
else
cmd_map{keys = "<C-n>", command = "bnext", plugins = false}
cmd_map{keys = "<C-p>", command = "bprev", plugins = false}
end
--[[
_ _
__ _(_) |_
/ _` | | __|
| (_| | | |_
\__, |_|\__|
|___/
]]
-- Git hunk jumps, that behave the same when diffing two files
map{keys = "]c", to = "&diff ? ']c' : '<cmd>lua require('gitsigns').next_hunk()<CR>'", expression = true}
map{keys = "[c", to = "&diff ? ']c' : '<cmd>lua require('gitsigns').prev_hunk()<CR>'", expression = true}
-- a motion to select the whole hunk
map{mode = "o", keys = "ih", to = "<cmd>lua require('gitsigns').select_hunk()<CR>"}
map{mode = "x", keys = "ih", to = "<cmd>lua require('gitsigns').select_hunk()<CR>"}
cmd_map{keys = "<leader>gb", command = "GitMessenger"}
map{keys = "<leader>gS", to = "<cmd>lua require('gitsigns').stage_hunk()<CR>"}
map{keys = "<leader>gU", to = "<cmd>lua require('gitsigns').undo_stage_hunk()<CR>"}
map{keys = "<leader>gp", to = "<cmd>lua require('gitsigns').preview_hunk()<CR>"}
--[[
_ _ _
___ ___ _ __ ___ _ __ | | ___| |_(_) ___ _ __
/ __/ _ \| '_ ` _ \| '_ \| |/ _ \ __| |/ _ \| '_ \
| (_| (_) | | | | | | |_) | | __/ |_| | (_) | | | |
\___\___/|_| |_| |_| .__/|_|\___|\__|_|\___/|_| |_|
|_|
]]
-- completion key bindings
map{mode = 'i', keys = "<ESC>", to = [[pumvisible() ? "<C-e><ESC>" : "<ESC>"]], expression = true}
map{mode = 'i', keys = "<C-c>", to = [[pumvisible() ? "<C-e><C-c>" : "<C-c>"]], expression = true}
-- TODO: integrate nvim-autopairs and replace these two bindings
map{mode = 'i', keys = "<CR>", to = [[pumvisible() ? (complete_info().selected == -1 ? "<C-e><CR>" : "<C-y>") : "<CR>"]], expression = true}
map{mode = 'i', keys = "<BS>", to = [[pumvisible() ? "<C-e><BS>" : "<BS>"]], expression = true}
local is_prior_char_whitespace = function()
local col = vim.fn.col('.') - 1
if col == 0 or vim.fn.getline('.'):sub(col, col):match('%s') then
return true
else
return false
end
end
-- Use (shift-)tab to:
--- move to prev/next item in completion menu
--- jump to the prev/next snippet placeholder (TOOD: how to activate this in coq?)
--- insert a simple tab
--- start the completion menu (TOOD: how to activate this in coq?)
_G.tab_completion = function()
if vim.fn.pumvisible() == 1 then
return vim.api.nvim_replace_termcodes("<C-n>", true, true, true)
elseif is_prior_char_whitespace() then
return vim.api.nvim_replace_termcodes("<Tab>", true, true, true)
end
end
_G.shift_tab_completion = function()
if vim.fn.pumvisible() == 1 then
return vim.api.nvim_replace_termcodes("<C-p>", true, true, true)
else
return vim.api.nvim_replace_termcodes("<S-Tab>", true, true, true)
end
end
map{mode = 'i', keys = "<Tab>", to = [[v:lua.tab_completion()]], expression = true, plugins = true}
map{mode = 's', keys = "<Tab>", to = [[v:lua.tab_completion()]], expression = true, plugins = true}
map{mode = 'i', keys = "<S-Tab>", to = [[v:lua.shift_tab_completion()]], expression = true, plugins = true}
map{mode = 's', keys = "<S-Tab>", to = [[v:lua.shift_tab_completion()]], expression = true, plugins = true}
--[[
_ _ _
| (_)_ __ | |_ ___ _ __
| | | '_ \| __/ _ \ '__|
| | | | | | || __/ |
|_|_|_| |_|\__\___|_|
]]
-- linter errors & LSP diagnostics management via ALE
cmd_map{keys = "[d", command = "ALEPreviousWrap"}
cmd_map{keys = "]d", command = "ALENextWrap"}
cmd_map{keys = "<leader>df", command = "ALEFix"}
cmd_map{keys = "<leader>dd", command = "ALEDetail"}
cmd_map{keys = "<leader>dl", command = "ALELint"}
cmd_map{keys = "<leader>dL", command = "ALEToggle"}
|
ITEM.name = "Sewing Kit"
ITEM.model = Model("models/zworld_health/healkit.mdl")
ITEM.description = "Various tools for cutting, stitching or tailoring fabrics and clothes."
ITEM.width = 2
ITEM.height = 2
ITEM.price = 150
ITEM.flag = "M"
ITEM.category = "Tools"
-- No stack Unique
|
require('kill')
-- Oracles get +5% experience if the killed creature had any statuses
-- in force.
local function oracle_kill_fn(att_cr_id, kill_cr_id)
local statuses = {get_creature_statuses(kill_cr_id)}
if table.getn(statuses) > 0 then
-- Take 5% of the xp value (or 1 XP, if the value is sufficiently
-- low), and add it to the attacking creature.
local xp_val = get_experience_value(kill_cr_id) * 0.05
xp_val = math.max(xp_val, 1)
gain_experience(att_cr_id, xp_val)
end
end
-- Set up the oracle kill function
local oracle_class_kill_fn = oracle_kill_fn
kill.set_class_kill_fn("oracle", oracle_class_kill_fn)
|
local lust = require 'test.lust'
local describe, it, expect = lust.describe, lust.it, lust.expect
local CharacterClass = require 'entities.CharacterClass'
describe('CharacterClass', function ()
it('instantiate', function ()
expect(CharacterClass()).to.be.a('table')
end)
local data = {
name = 'foobar',
shortname = 'foo',
alignments = { 'good' },
statrequirement = {
},
savingthrow = {
},
defaultspellbooks = {
},
spelllearnlevels = {
},
hpdice = 10,
attacktimelevel = {
},
nextlevel = {
}
}
local instance
it('instantiate from table', function ()
instance = CharacterClass(data)
expect(instance).to.be.a('table')
end)
end)
|
-- .vscode/settings.json <<
-- "Lua.workspace.library": {
-- "C:\\ProgramData\\chocolatey\\lib\\luarocks\\luarocks-2.4.4-win32\\systree\\share\\lua\\5.1": true
-- },
local busted = require 'busted'
local assert = require 'luassert'
local yaml = require 'tinyyaml'
busted.describe("map", function()
busted.it("map with colon for item", function()
assert.same(
{
value = {"a:1"}
},
yaml.parse([[
value:
- a:1
]])
)
assert.same(
{
value = {"a:1"}
},
yaml.parse([[
value:
- "a:1"
]])
)
assert.same(
{
value = {{a = 1}}
},
yaml.parse([[
value:
- a: 1
]])
)
assert.same(
{
a = {{b = {c = 1}}}
},
yaml.parse([[
a:
- b:
c: 1
]])
)
-- trailing whitespace after colon
assert.same(
{
a = {{b = {c = 1}}}
},
yaml.parse([[
a:
- b:
c: 1
]])
)
end)
busted.it("map with slash for item", function()
assert.same(
{
value = "/a"
},
yaml.parse([[
value: /a
]])
)
assert.same(
{
value = {"/a"}
},
yaml.parse([[
value:
- /a
]])
)
end)
busted.it("map with underscore for item", function()
assert.same(
{
value = "_a"
},
yaml.parse([[
value: _a
]])
)
assert.same(
{
value = {"_a"}
},
yaml.parse([[
value:
- _a
]])
)
end)
busted.it("map with dash for item", function()
assert.same(
{
value = "-a"
},
yaml.parse([[
value: -a
]])
)
assert.same(
{
value = {"-a"}
},
yaml.parse([[
value:
- -a
]])
)
end)
busted.it("map with space for item", function()
assert.same(
{
value = "a 1"
},
yaml.parse([[
value: a 1
]])
)
assert.same(
{
value = {"a 1"}
},
yaml.parse([[
value:
- a 1
]])
)
end)
end)
|
local modal = {}
local stateMachine = require "statemachine"
local utils = require "utils"
local windows = require "windows"
-- local log = hs.logger.new('modal-module','debug')
modal.setHotkey = function(array, key)
modal.hotkeyModifier = array
modal.hotkey = key
end
modal.displayModalText = function(txt)
hs.alert.closeAll()
alert(txt, 999999)
end
modal.exitAllModals = function()
hs.fnutils.each(modal.states, function(s)
if s.hotkeyModal then s.hotkeyModal:exit() end
end)
end
modal.addState = function(name,state)
modal.states[name] = state
end
local filterAllowedApps = function(w)
local allowedApps = {"Emacs", "iTerm2"}
if (not w:isStandard()) and (not hs.fnutils.contains(allowedApps, w:application():name())) then
return false;
end
return true;
end
modal.states = {
idle = {
from = "*", to = "idle",
callback = function(self, event, from, to)
hs.alert.closeAll()
modal.exitAllModals()
end
},
main = {
from = "*", to = "main",
init = function(self, fsm)
if self.hotkeyModal then
self.hotkeyModal:enter()
else
self.hotkeyModal = hs.hotkey.modal.new(modal.hotkeyModifier, modal.hotkey)
end
self.hotkeyModal:bind("","space", nil, function() fsm:toIdle(); windows.activateApp("Alfred 3") end)
self.hotkeyModal:bind("","w", nil, function() fsm:toWindows() end)
self.hotkeyModal:bind("","a", nil, function() fsm:toApps() end)
self.hotkeyModal:bind("", "m", nil, function() fsm:toMedia() end)
self.hotkeyModal:bind("", "x", nil, function() fsm:toEmacs() end)
self.hotkeyModal:bind("","j", nil, function()
local wns = hs.fnutils.filter(hs.window.allWindows(), filterAllowedApps)
hs.hints.windowHints(wns, nil, true)
fsm:toIdle() end)
self.hotkeyModal:bind("","escape", function() fsm:toIdle() end)
function self.hotkeyModal:entered()
-- modal.displayModalText "w \t- windows\na \t- apps\n j \t- jump\nm - media\nx\t- emacs"
fsm:toWindows()
end
end
}
}
-- -- each modal has: name, init function
modal.createMachine = function()
-- build events based on modals
local events = {}
local params = function(fsm)
local callbacks = {}
for k, s in pairs (modal.states) do
table.insert(events, { name = "to" .. utils.capitalize(k),
from = s.from or {"main", "idle"},
to = s.to or k})
if s.callback then
cFn = s.callback
else
cFn = function(self, event, from, to)
local st = modal.states[to]
st.init(st, self)
end
end
callbacks["on" .. k] = cFn
end
return callbacks
end
return stateMachine.create({ initial = "idle",
events = events,
callbacks = params(self)})
end
return modal
|
--- Pretty-printing Lua tables.
-- @class module
-- @name pl.pretty
local append = table.insert
local concat = table.concat
local utils = require 'pl.utils'
local lexer = require 'pl.lexer'
local assert_arg = utils.assert_arg
--[[
module('pl.pretty',utils._module)
]]
local pretty = {}
--- read a string representation of a Lua table.
-- Uses loadstring, but tries to be cautious about loading arbitrary code!
-- It is expecting a string of the form '{...}', with perhaps some whitespace
-- before or after the curly braces. An empty environment is used, and
-- any occurance of the keyword 'function' will be considered a problem.
-- @param s {string} string of the form '{...}', with perhaps some whitespace
-- before or after the curly braces.
function pretty.read(s)
assert_arg(1,s,'string')
if not s:find '^%s*%b{}%s*$' then return nil,"not a Lua table" end
if s:find '[^\'"%w_]function[^\'"%w_]' then
local tok = lexer.lua(s)
for t,v in tok do
if t == 'keyword' then
return nil,"cannot have Lua keywords in table definition"
end
end
end
local chunk,err = loadin({},'return '..s,'tbl')
if not chunk then return nil,err end
return chunk()
end
local function quote_if_necessary (v)
if not v then return ''
else
if v:find ' ' then v = '"'..v..'"' end
end
return v
end
local keywords
--- Create a string representation of a Lua table.
-- @param tbl {table} Table to serialize to a string.
-- @param space {string} (optional) The indent to use.
-- Defaults to two spaces.
-- @param not_clever {bool} (optional) Use for plain output, e.g {['key']=1}.
-- Defaults to false.
function pretty.write (tbl,space,not_clever)
assert_arg(1,tbl,'table')
if not keywords then
keywords = lexer.get_keywords()
end
space = space or ' '
local lines = {}
local line = ''
local tables = {}
local function is_identifier (s)
return (s:find('^[%a_][%w_]*$')) and not keywords[s]
end
local function put(s)
if #s > 0 then
line = line..s
end
end
local function putln (s)
if #line > 0 then
line = line..s
append(lines,line)
line = ''
else
append(lines,s)
end
end
local function eat_last_comma ()
local n,lastch = #lines
local lastch = lines[n]:sub(-1,-1)
if lastch == ',' then
lines[n] = lines[n]:sub(1,-2)
end
end
local function quote (s)
return ('%q'):format(tostring(s))
end
local function index (numkey,key)
if not numkey then key = quote(key) end
return '['..key..']'
end
local writeit
writeit = function (t,oldindent,indent)
local tp = type(t)
if tp ~= 'string' and tp ~= 'table' then
putln(quote_if_necessary(tostring(t))..',')
elseif tp == 'string' then
if t:find('\n') then
putln('[[\n'..t..']],')
else
putln(quote(t)..',')
end
elseif tp == 'table' then
if tables[t] then
putln('<cycle>,')
return
end
tables[t] = true
local newindent = indent..space
putln('{')
local max = 0
if not not_clever then
for i,val in ipairs(t) do
put(indent)
writeit(val,indent,newindent)
max = i
end
end
for key,val in pairs(t) do
local numkey = type(key) == 'number'
if not_clever then
key = tostring(key)
put(indent..index(numkey,key)..' = ')
writeit(val,indent,newindent)
else
if not numkey or key < 1 or key > max then -- non-array indices
if numkey or not is_identifier(key) then
key = index(numkey,key)
end
put(indent..key..' = ')
writeit(val,indent,newindent)
end
end
end
eat_last_comma()
putln(oldindent..'},')
else
putln(tostring(t)..',')
end
end
writeit(tbl,'',space)
eat_last_comma()
return concat(lines,#space > 0 and '\n' or '')
end
--- Dump a Lua table out to a file or stdout.
-- @param t {table} The table to write to a file or stdout.
-- @param ... {string} (optional) File name to write too. Defaults to writing
-- to stdout.
function pretty.dump (t,...)
if select('#',...) == 0 then
print(pretty.write(t))
return true
else
return utils.writefile((select(1,...)),pretty.write(t))
end
end
return pretty
|
local fs = require('diagnosticls-configs.fs')
return {
sourceName = 'isort',
command = fs.executable('isort'),
args = { '--quiet', '--stdout', '-' },
rootPatterns = { '.isort.cfg', 'pyproject.toml', '.git' },
}
|
local class = require('opus.class')
local UI = require('opus.ui')
UI.Menu = class(UI.Grid)
UI.Menu.defaults = {
UIElement = 'Menu',
disableHeader = true,
columns = { { heading = 'Prompt', key = 'prompt', width = 20 } },
menuItems = { },
}
function UI.Menu:postInit()
self.values = self.menuItems
self.pageSize = #self.menuItems
end
function UI.Menu:layout()
self.itemWidth = 1
for _,v in pairs(self.values) do
if #v.prompt > self.itemWidth then
self.itemWidth = #v.prompt
end
end
self.columns[1].width = self.itemWidth
if self.centered then
self:center()
else
self.width = self.itemWidth + 2
end
UI.Grid.layout(self)
end
function UI.Menu:center()
self.x = (self.width - self.itemWidth + 2) / 2
self.width = self.itemWidth + 2
end
function UI.Menu:eventHandler(event)
if event.type == 'key' then
if event.key == 'enter' then
local selected = self.menuItems[self.index]
self:emit({
type = selected.event or 'menu_select',
selected = selected
})
return true
end
elseif event.type == 'mouse_click' then
if event.y <= #self.menuItems then
UI.Grid.setIndex(self, event.y)
local selected = self.menuItems[self.index]
self:emit({
type = selected.event or 'menu_select',
selected = selected
})
return true
end
end
return UI.Grid.eventHandler(self, event)
end
function UI.Menu.example()
return UI.Menu {
x = 2, y = 2, height = 3,
menuItems = {
{ prompt = 'Start', event = 'start' },
{ prompt = 'Continue', event = 'continue' },
{ prompt = 'Quit', event = 'quit' }
}
}
end
|
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
pistol_dx2 = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/weapon/ranged/pistol/pistol_dx2.iff",
craftingValues = {
{"mindamage",35,71,0},
{"maxdamage",73,103,0},
{"attackspeed",5.2,3.8,1},
{"woundchance",6.8,14.7,0},
{"hitpoints",750,750,0},
{"attackhealthcost",32,17,0},
{"attackactioncost",51,29,0},
{"attackmindcost",22,12,0},
{"roundsused",15,60,0},
{"zerorangemod",18,33,0},
{"maxrangemod",-90,-90,0},
{"midrange",16,16,0},
{"midrangemod",14,30,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 625,
junkDealerTypeNeeded = JUNKARMS,
junkMinValue = 30,
junkMaxValue = 55
}
addLootItemTemplate("pistol_dx2", pistol_dx2)
|
-- Library by WD200019
-- SuperCall(func, arg1, arg2, ...)
-- !! Must be loaded in a script with a function to call from another script !! (see Examples)
-- Calls the function 'func' in the current script with the arguments 'arg1', 'arg2', ...
-- Can be called from another script without triggering an error.
-- func (function or string): Refers to the function in the target script to call.
-- Can be used in several ways:
--- (in another script)
-- targetScript.Call("SuperCall", function_in_the_target_script)
-- targetScript.Call("SuperCall", "function_in_the_target_script")
-- targetScript.Call("SuperCall", {"function_in_the_target_script", arg1, arg2, ...})
--
-- arg1, arg2, ... (any type): arguments to be passed to the target function.
--
-- Examples (from enemy or wave scripts):
--
-- -- calls the function 'func' of the table 'mytable' in the Encounter script
-- Encounter.Call("SuperCall", "mytable.func")
--
-- -- calls the function 'func2' of the table 'mytable' in the Encounter script, with arguments
-- Encounter.Call("SuperCall", {"mytable.func2", "one", "two"})
--
-- Examples (from the encounter script):
--
-- -- Resizes the Arena in the first active wave (ONLY DURING DEFENDING)
-- Wave[1].Call("SuperCall", {"Arena.ResizeImmediate", 400, 400})
--
-- -- Uses CHECK on the first enemy
-- enemies[1].Call("SuperCall", {"HandleCustomCommand", "CHECK"})
function _SuperCall(func, ...)
if type(func) == "string" then
local oldFunc = func
func = Recurse(func)
if type(func) == "string" then
error(func .. oldFunc .. "\" could not be found.")
elseif func == nil then
error("The function " .. oldFunc .. " could not be found.")
end
elseif type(func) ~= "function" then
error("Attempt to SuperCall a non-function value.")
end
return func(...)
end
function SuperCall(script, func, ...)
if tostring(script) ~= "ScriptWrapper" then
error("SuperCall's first parameter must be a script object.")
end
if type(func) ~= "string" then
error("SuperCall's second parameter must be a string.")
end
local tab = { func }
for k, v in pairs({ ... }) do
table.insert(tab, v)
end
return script.Call("_SuperCall", tab)
end
function Recurse(arg, obj)
obj = obj or _G
if arg:find("%.") then
local objectName = arg:sub(0, arg:find("%.") - 1)
obj = obj[objectName]
-- we couldn't find the object `objectName` in `obj`
if not obj then
return "The table item \"" .. objectName .. "\" of \""
end
return Recurse(arg:sub(arg:find("%.") + 1), obj)
else
return obj[arg]
end
end
|
Config = {}
Config.Price = 100
Config.DrawDistance = 100.0
Config.MarkerSize = vector3(1.5, 1.5, 1.0)
Config.MarkerColor = {r = 102, g = 102, b = 204}
Config.MarkerType = 1
Config.Locale = 'es'
Config.Shops = {
vector3(-814.3, -183.8, 36.6),
vector3(136.8, -1708.4, 28.3),
vector3(-1282.6, -1116.8, 6.0),
vector3(1931.5, 3729.7, 31.8),
vector3(1212.8, -472.9, 65.2),
vector3(-32.9, -152.3, 56.1),
vector3(-278.1, 6228.5, 30.7)
}
|
--------------------------------
-- @module RichItemNewLine
-- @extend RichItem
-- @parent_module ccui
--------------------------------
--
-- @function [parent=#RichItemNewLine] init
-- @param self
-- @param #int tag
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#RichItemNewLine] create
-- @param self
-- @param #int tag
-- @return RichItemNewLine#RichItemNewLine ret (return value: ccui.RichItemNewLine)
--------------------------------
--
-- @function [parent=#RichItemNewLine] lookupObject
-- @param self
-- @param #unsigned int id
-- @return void#void ret (return value: void)
--------------------------------
--
-- @function [parent=#RichItemNewLine] RichItemNewLine
-- @param self
-- @return RichItemNewLine#RichItemNewLine self (return value: ccui.RichItemNewLine)
return nil
|
local hex = bizstring.hex
console.clear()
--Credits: http://lua-users.org/wiki/SimpleStack
-- GLOBAL
Stack = {}
-- Create a Table with stack functions
function Stack:Create()
-- stack table
local t = {}
-- entry table
t._et = {}
-- push a value on to the stack
function t:push(...)
if ... then
local targs = {...}
-- add values
for _,v in ipairs(targs) do
table.insert(self._et, v)
end
end
end
-- pop a value from the stack
function t:pop(num)
-- get num values from stack
local num = num or 1
-- return table
local entries = {}
-- get values into entries
for i = 1, num do
-- get last entry
if #self._et ~= 0 then
table.insert(entries, self._et[#self._et])
-- remove last value
table.remove(self._et)
else
break
end
end
-- return unpacked entries
return unpack(entries)
end
-- get entries
function t:getn()
return #self._et
end
-- list values
function t:list()
for i,v in pairs(self._et) do
print(i, hex(v))
end
end
return t
end
function display_registers(registers)
for i = 0, 16 do
console.log("r["..i.."] = 0x"..hex(registers[i]))
end
console.log("r.CPSR = 0x"..hex(registers.CPSR))
console.log("PC: "..hex(registers[15]+1))
local N = bit.check(registers.CPSR, 31) and 1 or 0
local Z = bit.check(registers.CPSR, 30) and 1 or 0
local C = bit.check(registers.CPSR, 29) and 1 or 0
local V = bit.check(registers.CPSR, 28) and 1 or 0
local Q = bit.check(registers.CPSR, 27) and 1 or 0
console.log("N: "..N.." Z: "..Z.." C: "..C.." V: "..V.." Q: "..Q)
end
--since bizhawk hates the 0x8/0x3/0x4 part, remove it
function load_biz_addr(addr, size)
local destination
local read_memory = memory.read_u32_le --default
if size == 8 then
read_memory = memory.read_u8
elseif size == 16 then
read_memory = memory.read_u16_le
elseif size == 24 then
read_memory = memory.read_u24_le
end
if addr < 0x01000000 and addr > 0x00000000 then
destination = read_memory(addr, "BIOS")
elseif addr < 0x03000000 and addr > 0x02000000 then
destination = read_memory(addr - 0x02000000,"EWRAM")
elseif addr < 0x04000000 and addr > 0x03000000 then
destination = read_memory(addr - 0x03000000,"IWRAM")
elseif addr < 0x05000000 and addr > 0x04000000 then
destination = read_memory(addr - 0x04000000,"System Bus")
elseif addr < 0x09000000 and addr > 0x08000000 then
destination = read_memory(addr - 0x08000000,"ROM")
end
return destination
end
function asm_080109AF(registers, stack)
r = registers
--do these 2 separately; both are from 080109AF
stack:push(r[14])
stack:push(r[4])
r[4] = r[0] --080109B1
r[14] = 0x080109B5
r[15] = 0x0802C586
return r, stack
end
--0802C587
function next_rng(registers, stack, value)
--Only r0, r2, r3 changes
--r0 = bottom 8 bits of new rng (LDRB at the end)
--r2 = top 8 bits of new rng
--r3 = bottom 8 bits of old rng
--both pushes from 0802C587
stack:push(r[14])
stack:push(r[4])
local r = registers
r[0] = value
r[0] = value + bit.lshift(value, 1)
r[2] = bit.rshift(r[0],8)
r[3] = bit.band(value, 0xFF)
r[0] = bit.band(r[2] + r[3], 0xFF) + (r[2] * 256)
local new_value = bit.band(r[0], 0xFFFF)
r[0] = bit.band(new_value, 0xFF)
r[2] = bit.rshift(bit.band(new_value, 0xFF00),8)
r[3] = bit.band(value, 0xFF)
r[4] = stack:pop() --0802C5AD
r[1] = stack:pop() --0802C5AF
r[13] = 0x03007BEC --Stack changed
r[15] = r[1] + 1 --PC changed
return r, stack, new_value --0802C5B1 BX
end
function asm_080109B7(registers, stack)
local r = registers
-- r[0] = bit.lshift(r[0],24) --080109B7
-- r[0] = bit.rshift(r[0],24) --080109B9
r[0] = r[0] % 0xFF --Above should be same as this
r[1] = 100
r[14] = 0x080109BF --LR = PC + 1
r[15] = 0x08059B1E
--08059B1F
if r[1] == 0 then
console.log("080109B7 Hi")
return asm_08059BD5(r, stack)
else
console.log("080109B7 Hi 2")
return asm_08059B23(r, stack)
end
end
function asm_08059BD5(registers, stack)
local r = registers
stack:push(r[14]) --08059BD5
r[14] = 0x08059BD9
r[15] = 0x08059BDA --0805999F
r[0] = 0
r[15] = stack:pop()
end
function asm_08059B23(registers, stack)
local r = registers
r[3] = 1
--08059B25: technically, it's r0 >= r1, but since that being false makes it leave
-- CMP r0, r1
-- BCS #+0
if (r[0] < r[1]) then
console.log("08059B23 Hi")
--08059B29
r[15] = 0x080109C0
return r, stack --go to egg determination function
else
--08059B2B
console.log("08059B23 Hi 2")
stack:push(r[4])
r[4] = 1
r[4] = bit.lshift(r[4], 28) --08059B2F
--go to egg determination function after this function ends
return asm_08059B31(r, stack, 1)
end
end
function asm_08059B31(registers, stack, loop)
local r = registers
-- local cond = true
-- while true do --for the branch in 08059B3D
-- --08059B31: technically r[1] >= r[4], but since it seems to cascade from 08059B35 to 08059B3F r[1] < r[4]
-- -- CMP r[1], r[4]
-- -- BCS #+8 -> Branch if r[1] >= r[4]
-- if r[1] < r[4] then
-- --08059B35: technically r[1] >= r[0]
-- -- CMP r[1], r[0]
-- -- BCS #+4 -> Branch if r[1] >= r[0]
-- if r[1] < r[0] then
-- --08059B39
-- r[1] = bit.lshift(r[1], 4)
-- r[3] = bit.lshift(r[3], 4)
-- else
-- --08059B3F
-- r[4] = bit.lshift(r[4], 4)
-- cond = false
-- break
-- end
-- else
-- --08059B3F
-- r[4] = bit.lshift(r[4], 4)
-- cond = false
-- break
-- end
-- end
if loop < 2 then --don't do this again on 2nd loop+
while (r[1] < r[4]) and (r[1] < r[0]) do
--08059B39
r[1] = bit.lshift(r[1], 4)
r[3] = bit.lshift(r[3], 4)
end
--08059B3F
r[4] = bit.lshift(r[4], 3)
while (r[1] < r[4]) and (r[1] < r[0]) do
--08059B49
r[1] = bit.lshift(r[1], 1)
r[3] = bit.lshift(r[3], 1)
end
end
--08059B4F
r[2] = 0
--08059B53: technically r[0] < r[1], but since it seems to cascade from 08059B54 to 08059B56 r[0] >= r[1]
-- CMP r[0], r[1]
-- BCC #+0 -> Branch if r[0] < r[1]
if r[0] >= r[1] then
-- console.log("08059B53")
-- display(loop, r)
r[0] = r[0] - r[1]
end
-- 08059B56
r[4] = bit.rshift(r[1], 1)
-- 08059B5B: technically r[0] < r[4] but since it seems to cascade from 08059B5C to 08059B68 if r[0] >= r[4]
-- CMP r[0], r[4]
-- BCC #+10 -> Branch if r[0] < r[4]
if r[0] >= r[4] then
-- console.log("08059B5B")
-- display(loop, r)
r[0] = r[0] - r[4]
r[12] = r[3]
r[4] = 1
r[3] = bit.ror(r[3], r[4])
r[2] = bit.bor(r[2], r[3])
r[3] = r[12]
end
-- 08059B68
r[4] = bit.rshift(r[1], 2)
-- 08059B6D: technically r[0] < r[4], but since it seems to cascade from 08059B6E to 08059B7A if r[0] >= r[4]
-- CMP r[0], r[4]
-- BCC #+10 -> Branch if r[0] < r[4]
if r[0] >= r[4] then
-- console.log("08059B6D")
-- display(loop, r)
r[0] = r[0] - r[4]
r[12] = r[3]
r[4] = 2
r[3] = bit.ror(r[3], r[4])
r[2] = bit.bor(r[2], r[3])
r[3] = r[12]
end
-- 08059B7A
r[4] = bit.rshift(r[1], 3)
-- 08059B7F: technically r[0] < r[4], but since it seems to cascade from 08059B80 to 08059B8C if r[4] <= r[0]
-- CMP r[0], r[4]
-- BCC #+10 -> Branch if r[0] < r[4]
if r[0] >= r[4] then
-- console.log("08059B7F")
-- display(loop, r)
r[0] = r[0] - r[4]
r[12] = r[3]
r[4] = 3
r[3] = bit.ror(r[3], r[4])
r[2] = bit.bor(r[2], r[3])
r[3] = r[12]
end
-- 08059B8C
r[12] = r[3]
-- 08059B91: technically r[0] == 0, but since it seems to cascade from 08059B92 to 08059B9A if r[0] =/= 0
-- CMP r[0], #0
-- BEQ #+6 -> Branch if r[0] == 0
if r[0] ~= 0 then
-- console.log("08059B91")
-- display(loop, r)
r[3] = bit.rshift(r[3], 4)
-- 08059B95: technically r[3] == 0, but since it seems to cascade from 08059B96 to 08059B9A? if r[3] =/= 0
-- LSR r[3], r[3], #4
-- BEQ #+2
if r[3] ~= 0 then
-- 08059B97
-- console.log("08059B97")
-- display(loop, r)
r[1] = bit.rshift(r[1], 4)
return asm_08059B31(r, stack, loop+1)
end
end
--08059B9A
r[4] = 14
r[4] = bit.lshift(r[4], 28)
r[2] = bit.band(r[2], r[4])
-- 08059BA1: technically r[2] =/= 0, but since it seems to cascade from 08059BA2 to 08059BA6 if r[2] == 0
if r[2] == 0 then
-- console.log("08059BA1")
-- display(loop, r)
r[4] = stack:pop() --technically from stack
r[13] = r[13] + 4 --Stack popped
r[15] = 0x080109C0 --from link register
return r, stack, loop
end
-- 08059BA6
r[3] = r[12]
r[4] = 3
r[3] = bit.ror(r[3], r[4])
-- 08059BAF: technically r[2] AND r[3] == 0, but since it seems to cascade from 08059BB0 to 08059BB4 if r[2] AND r[3] =/= 0
if bit.band(r[2], r[3]) ~= 0 then
-- console.log("08059BAF")
-- display(loop, r)
r[4] = bit.lshift(r[1], 3)
r[0] = r[0] + r[4]
end
-- 08059BB4
r[3] = r[12]
r[4] = 2
r[3] = bit.ror(r[3], r[4])
-- 08059BBD: technically r[2] AND r[3] == 0, but since it seems to cascade from 08059BBE to 08059BC2 if r[2] AND r[3] =/= 0
if bit.band(r[2], r[3]) ~= 0 then
-- console.log("08059BBD")
-- display(loop, r)
r[4] = bit.rshift(r[1], 2)
r[0] = r[0] + r[4]
end
-- 08059BC2
r[3] = r[12]
r[4] = 1
r[3] = bit.ror(r[3], r[4])
-- 08059BCB: technically r[2] AND r[3] == 0, but since it seems to cascade from 08059BCC to 08059BD0 if r[2] AND r[3] =/= 0
if bit.band(r[2], r[3]) ~= 0 then
-- console.log("08059BCB")
-- display(loop, r)
r[4] = bit.rshift(r[1], 1)
r[0] = r[0] + r[4]
end
-- 08059BD0
-- console.log("08059BD0")
-- display(loop, r)
r[4] = stack:pop() --from stack, should be 60
r[13] = r[13] + 4 --Stack popped
r[15] = 0x080109C0
return r, stack, loop
end
function asm_080109C1(registers, stack, stuff)
local r = registers
r[0] = bit.lshift(r[0], 24)
r[0] = bit.arshift(r[0], 24)
r[0] = r[0] - r[4]
r[0] = bit.lshift(r[0], 24)
--080109C9
-- CMP r0, 0
-- BLT #+2 -> Branch if less than 0; check bit 31 in this case
-- if bit.check(r[0], 31) then
-- --080109D1
-- r[0] = 1
-- else
-- --080109CD
-- r[0] = 0
-- end
r[0] = bit.check(r[0], 31) and 1 or 0 --should be same as above
r[4] = stack:pop() --080109D3
r[1] = stack:pop() --080109D5
if r[1] == 0x080056CF then
console.log("080109C1 Hi")
--080056D1
r[0] = bit.lshift(r[0], 24)
--080056D3
if r[0] == 0 then
--080056DB
r[0] = 30
r[14] = 0x080056DF
r[15] = 0x080109AE
console.log("080109C1 Hi 2")
r, stack = asm_080109AF(r, stack)
--0802C587
r, stack, stuff.RNG = next_rng(r, stack, stuff.RNG)
r, stack = asm_080109B7(r, stack)
return asm_080109C1(r, stack, stuff)
else
r[4] = 0 --080056D7
end
else
--080056E1
r[0] = bit.lshift(r[0], 24)
-- r[4] = 2
-- --080056E5: technically it's r[0] == 0, but since failing makes it go from 080056E9 to 080056EB anyways
-- if r[0] ~= 0 then
-- r[4] = 1
-- end
r[4] = (r[0] == 0) and 2 or 1 --should be the same as above
end
--080056EB
r[0] = 0x030010B0 --from PC + 88; this + 0x2 is floor address
r[1] = stuff.floor_number --from 0x030010B2; 080056ED
r[1] = r[1] - 7 --080056EF
r[0] = bit.lshift(r[1], 1) --080056F1
r[0] = r[0] + r[1] --080056F3
r[3] = r[0] + r[4] --080056F5
--080056F9: technically it's r[3] <= 11, but since failing makes it go from 080056FB to 080056FD anyways
r[3] = r[3] <= 11 and r[3] or 11
r[2] = 0x02036BC4 -- from PC + 76; 080056FD
r[0] = 0x030019AC -- from PC + 76; 080056FF
r[0] = 0x03004470 -- from the address 0x030019AC
r[4] = r[7] --08005703
r[4] = r[4] + 118 --should end up as 0x02006056; 08005705
r[1] = stuff.dungeon == "A" and stuff.addr_44A0.A or stuff.addr_44A0.B --address from r[0] + 48
r[4] = stuff.type --08005709
r[0] = bit.lshift(r[4], 2)
-- console.log(hex(r[0]))
r[0] = r[0] + r[1] --0800570D
r[0] = load_biz_addr(r[0], 32) --0800570F; doing this for now until I figure out memory things
r[0] = r[0] + r[3] --08005713; egg address
stuff.egg_address = r[0] -- record it just in case
r[0] = load_biz_addr(r[0], 8) --08005715; egg id from ROM
stuff.egg_id = r[0] -- record it just in case
return r, stack, stuff
end
stack = Stack:Create()
local stuff = {} --placeholder for memory address values
function egg_predict(rng, dungeon, egg_type, dg_floor)
stuff = {}
stuff.floor_number = dg_floor --which floor?
stuff.RNG = rng --RNG value
stuff.dungeon = dungeon --A or B
stuff.addr_44A0 = {A = 0x0817636C, B = 0x0817210C}
stuff.type = egg_type
stuff.egg_address = 0
--r0:00000003 r1:02004B40 r2:000014BC r3:00000000 r4:02019690 r5:00000000 r6:00000000 r7:02005FE0 r8:00000000 r9:00000000 r10:00000000 r11:00000000 r12:02003B10 r13:03007BF4 r14:08004BA7 r15:080056CA r16:6000003F
r = {}
r[0] = 0x00000003
r[1] = 0x02004B40
r[2] = 0x000014BC
r[3] = 0
r[4] = 0x02019690
r[5] = 0
r[6] = 0
r[7] = 0x02005FE0
r[8] = 0
r[9] = 0
r[10] = 0
r[11] = 0
r[12] = 0x02003B10
r[13] = 0x03007BF4
r[14] = 0x08004BA7
r[15] = 0x080056CA
r[16] = 0x6000003F
r.CPSR = 0x6000003F
--080056CB
r[0] = 60
--080056CD, 080056CF
r[14] = 0x080056CF
r[15] = 0x080109AE
r, stack = asm_080109AF(r, stack)
r, stack, stuff.RNG = next_rng(r, stack, stuff.RNG)
r, stack = asm_080109B7(r, stack) --This should call either asm_08059BD5 or asm_08059B23; both end up with egg function
r, stack, stuff = asm_080109C1(r, stack, stuff)
-- display_registers(r)
-- console.log("Stack now")
-- stack:list()
return stuff.egg_id, stuff.egg_address
end
--[[
Types:
0 Electric
1 Water
2 Fire
3 Earth
4 Royal (doesn't appear in wild)
]]--
local egg_id, egg_address = egg_predict(0xCFD3, "A", 2, 7)
console.log("Egg ID: "..egg_id.." (0x"..hex(egg_id)..")")
console.log("Egg Address: 0x0"..hex(egg_address))
egg_id, egg_address = egg_predict(0x700B, "B", 0, 7)
console.log("Egg ID: "..egg_id.." (0x"..hex(egg_id)..")")
console.log("Egg Address: 0x0"..hex(egg_address))
|
object_draft_schematic_food_beastfood_stringy_meat_substitute = object_draft_schematic_food_shared_beastfood_stringy_meat_substitute:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_food_beastfood_stringy_meat_substitute, "object/draft_schematic/food/beastfood_stringy_meat_substitute.iff")
|
---
if table.get_length(baseObj.item_tbl) < 1 then return end
|
return {'opzadelen','opzagen','opzakken','opzeg','opzegbaar','opzeggen','opzegger','opzegging','opzeggingstermijn','opzeggingsvergoeding','opzegtermijn','opzenden','opzending','opzet','opzetheling','opzetje','opzetkarton','opzetstuk','opzettelijk','opzettelijkheid','opzetten','opzetter','opzetting','opzicht','opzichte','opzichter','opzichteres','opzichtig','opzichtigheid','opzichzelfstaand','opzien','opzienbarend','opziener','opzienersambt','opzienster','opzij','opzijleggen','opzijschuiven','opzijzetten','opzitten','opzoeken','opzoeking','opzoekingswerk','opzoeksnelheid','opzouten','opzuigen','opzuiging','opzuipen','opzuiveren','opzwaaiend','opzwellen','opzwelling','opzwepen','opzoekwerk','opzegbrief','opzegvergoeding','opzeggingsbrief','opzeggingsgrond','opzegperiode','opzegverbod','opzetsteek','opzullik','opzadel','opzadelde','opzadelden','opzadelt','opzag','opzak','opzat','opzegbare','opzegde','opzegden','opzeggingen','opzegt','opzegtermijnen','opzei','opzeiden','opzend','opzendt','opzetjes','opzetsteken','opzetstukken','opzette','opzettelijke','opzettelijker','opzetters','opzichten','opzichteressen','opzichters','opzichtige','opzichtiger','opzichtigst','opzichtigste','opzichzelfstaande','opzie','opzienbarende','opzienbarender','opzienbarends','opzienbarendst','opzienbarendste','opzieners','opziensters','opziet','opzijgeschoven','opzit','opzocht','opzoek','opzoekt','opzogen','opzond','opzoog','opzoop','opzopen','opzout','opzoutte','opzoutten','opzuig','opzuigt','opzuip','opzuipt','opzweep','opzweept','opzweepte','opzweepten','opzwel','opzwellingen','opzwelt','opzwepend','opzwepende','opzwol','opzwollen','opzaten','opzeggers','opzichtertje','opzijgelegd','opzijgezet','opzochten','opzoekingen','opzwaaiende','opzeggingstermijnen','opzeggingsgronden','opzegvergoedingen','opzetstukje','opzegverboden','opzetstukjes','opzegbriefje'}
|
MINIGAME.Base = "base"
MINIGAME.Unique = "obstacle"
MINIGAME.Name = "Obstacle Course"
MINIGAME.Description = "First team to make it to the end of the obstacle course wins."
MINIGAME.Author = "Chewgum"
|
AddEvent("OnKeyPress", function(key)
if key == "Tab" then
ExecuteWebJS(webui, "window.vm.showCharaCustom = !window.vm.showCharaCustom")
end
end)
--[[
Clothing0 => Cheveux
Clothing1 => Torse(Dessous)
Clothing2 => Torse(Dessus)
Clothing3 => Accessoires
Clothing4 => Jambes
Clothing5 => Pieds
]]
AddEvent("OnCharaCustom", function (clothing0, clothing1, clothing2, clothing3, clothing4, clothing5, body)
local SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Clothing0")
if clothing0 then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(clothing0))
else
SkeletalMeshComponent:SetSkeletalMesh(nil)
end
SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Clothing1")
if clothing1 then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(clothing1))
else
SkeletalMeshComponent:SetSkeletalMesh(nil)
end
SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Clothing2")
if clothing2 then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(clothing2))
else
SkeletalMeshComponent:SetSkeletalMesh(nil)
end
SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Clothing3")
if clothing3 then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(clothing3))
else
SkeletalMeshComponent:SetSkeletalMesh(nil)
end
SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Clothing4")
if clothing4 then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(clothing4))
else
SkeletalMeshComponent:SetSkeletalMesh(nil)
end
SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Clothing5")
if clothing5 then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(clothing5))
else
SkeletalMeshComponent:SetSkeletalMesh(nil)
end
SkeletalMeshComponent = GetPlayerSkeletalMeshComponent(GetPlayerId(), "Body")
if body then
SkeletalMeshComponent:SetSkeletalMesh(USkeletalMesh.LoadFromAsset(body))
end
end )
|
Weapon.PrettyName = "S&W Model 3 Russia"
Weapon.WeaponID = "m9k_model3russian"
Weapon.DamageMultiplier = 3.4
Weapon.WeaponType = WEAPON_SECONDARY
|
-- Functions for nvim 0.4 compatibility.
-- This module will be removed once nvim 0.5 becomes stable.
local fn = setmetatable({}, {
__index = function(_, key)
return function(...)
return vim.api.nvim_call_function(key, {...})
end
end}
)
local function tbl_map(func, t)
local rettab = {}
for k, v in pairs(t) do
rettab[k] = func(v)
end
return rettab
end
local function tbl_keys(t)
local rettab = {}
for k, _ in pairs(t) do
table.insert(rettab, k)
end
return rettab
end
local function tbl_filter(func, t)
local rettab = {}
for _, v in pairs(t) do
if func(v) then
table.insert(rettab, v)
end
end
return rettab
end
local function list_extend(dst, src, start, finish)
for i = start or 1, finish or #src do
table.insert(dst, src[i])
end
return dst
end
return setmetatable({
fn = fn,
cmd = vim.api.nvim_command,
tbl_map = tbl_map,
tbl_keys = tbl_keys,
tbl_filter = tbl_filter,
list_extend = list_extend,
}, {__index=function(self, key) return vim[key] or self[key] end})
|
-----------------------------------
-- Area: Western Adoulin
-- NPC: Hujette
-- Type: Quest NPC and Shop NPC
-- Involved with Quest: 'All the Way to the Bank'
-- !pos 35 0 -56 256
-----------------------------------
local ID = require("scripts/zones/Western_Adoulin/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
require("scripts/globals/shop")
function onTrade(player, npc, trade)
-- ALL THE WAY TO THE BANK
if (player:hasKeyItem(tpz.ki.TARUTARU_SAUCE_INVOICE)) then
local ATWTTB_Paid_Hujette = player:getMaskBit(player:getCharVar("ATWTTB_Payments"), 1)
if ((not ATWTTB_Paid_Hujette) and npcUtil.tradeHas( trade, {{"gil", 3000}} )) then
player:startEvent(5070)
end
end
end
function onTrigger(player, npc)
player:showText(npc, ID.text.HUJETTE_SHOP_TEXT)
local stock =
{
5941, 20, -- Campfire Choco
5940, 8, -- Trail Cookie
5942, 20, -- Cascade Candy
5775, 544, -- Chocolate Crepe
5147, 3000, -- Snoll Gelato
}
tpz.shop.general(player, stock)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
-- ALL THE WAY TO THE BANK
if (csid == 5070) then
player:confirmTrade()
player:setMaskBit("ATWTTB_Payments", 1, true)
if (player:isMaskFull(player:getCharVar("ATWTTB_Payments"), 5)) then
npcUtil.giveKeyItem(player, tpz.ki.TARUTARU_SAUCE_RECEIPT)
end
end
end
|
local helpers = require('test.functional.helpers')(after_each)
local Screen = require('test.functional.ui.screen')
local feed = helpers.feed
local eq = helpers.eq
local clear = helpers.clear
local function test_embed(ext_linegrid)
local screen
local function startup(...)
clear{headless=false, args={...}}
-- attach immediately after startup, for early UI
screen = Screen.new(60, 8)
screen:attach{ext_linegrid=ext_linegrid}
screen:set_default_attr_ids({
[1] = {foreground = Screen.colors.Grey100, background = Screen.colors.Red},
[2] = {bold = true, foreground = Screen.colors.SeaGreen4},
[3] = {bold = true, foreground = Screen.colors.Blue1},
[4] = {bold = true, foreground = Screen.colors.Green},
})
end
it('can display errors', function()
startup('--cmd', 'echoerr invalid+')
screen:expect([[
|
|
|
|
|
Error detected while processing pre-vimrc command line: |
E121: Undefined variable: invalid |
Press ENTER or type command to continue^ |
]])
feed('<cr>')
screen:expect([[
^ |
{3:~ }|
{3:~ }|
{3:~ }|
{3:~ }|
{3:~ }|
{3:~ }|
|
]])
end)
it("doesn't erase output when setting color scheme", function()
startup('--cmd', 'echoerr "foo"', '--cmd', 'color default', '--cmd', 'echoerr "bar"')
screen:expect([[
|
|
|
|
Error detected while processing pre-vimrc command line: |
foo |
{1:bar} |
{4:Press ENTER or type command to continue}^ |
]])
end)
it("doesn't erase output when setting Normal colors", function()
startup('--cmd', 'echoerr "foo"', '--cmd', 'hi Normal guibg=Green', '--cmd', 'echoerr "bar"')
screen:expect{grid=[[
|
|
|
|
Error detected while processing pre-vimrc command line: |
foo |
bar |
Press ENTER or type command to continue^ |
]], condition=function()
eq(Screen.colors.Green, screen.default_colors.rgb_bg)
end}
end)
end
describe('--embed UI on startup (ext_linegrid=true)', function() test_embed(true) end)
describe('--embed UI on startup (ext_linegrid=false)', function() test_embed(false) end)
|
n = io.read("*number", "*l")
hash = '#'
space = ' '
for i=1,n do
s = string.rep(space, n-i)
h = string.rep(hash, i)
print(s .. h)
end
|
--[[
* PSP Claw Explorer
* Copyright 2016 Carlos Monge.
* Licensed under MIT (https://github.com/carcmonge/pspclawexplorer/blob/master/LICENSE)
]]--
ibateria = {}
if batt.exists() then ibateria.exists = "Insertada" else ibateria.exists = "No hay bateria" end
if batt.charging() then ibateria.charging = "Si" else ibateria.charging = "No" end
if batt.islow() then ibateria.islow = "Bateria baja" else ibateria.islow = "Normal" end
ibateria.percent = batt.percent()
ibateria.time = batt.time()
ibateria.temp = batt.temp()
ibateria.volt = batt.volt()
inick = os.nick()
icpu = os.cpu()
ispace = {}
ispace.freespaceP = " ("..((math.ceil((files.freespace()/files.totalspace())*100*100)/100)-0.01).."%)"
ispace.freespace = files.sizeformat(files.freespace())..ispace.freespaceP
ispace.usespaceP = " ("..(math.ceil((((files.totalspace() - files.freespace())/files.totalspace())*100*100))/100).."%)"
ispace.usespace = files.sizeformat(files.totalspace() - files.freespace())..ispace.usespaceP
ispace.totalspace = files.sizeformat(files.totalspace())
ispace.getinitmemory = files.sizeformat(os.getinitmemory())
ispace.getfreememoryP = " ("..(math.ceil((os.getfreememory()/ os.getinitmemory())*100*100)/100).."%)"
ispace.getfreememory = files.sizeformat(os.getfreememory())..ispace.getfreememoryP
ispace.getusememoryP = " ("..((math.ceil((os.getinitmemory() - os.getfreememory())/ os.getinitmemory()*100*100)/100)-0.01).."%)"
ispace.getusememory = files.sizeformat(os.getinitmemory() - os.getfreememory())..ispace.getusememoryP
numFiles = 0
numCarpetas = 0
sizeDic = 0
indiceCur = 1
loading("Analizando...")
pesoDir(memoSelect)
icarpetas = numFiles
iarchivos = numCarpetas
while true do
elementosBases()
screen.print(10,45,"Bateria: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Bateria: "),45,ibateria.exists,0.7,blanco,negro)
screen.print(10,60,"Fuente de alimentacion: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Fuente de alimentacion: "),60,ibateria.charging,0.7,blanco,negro)
screen.print(10,75,"Porcentaje de carga: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Porcentaje de carga: "),75,ibateria.percent.."%",0.7,blanco,negro)
screen.print(10,90,"Estado de carga: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Estado de carga: "),90,ibateria.islow,0.7,blanco,negro)
screen.print(10,105,"Tiempo de carga: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Tiempo de carga: "),105,ibateria.time.." min",0.7,blanco,negro)
screen.print(10,120,"Temperatura: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Temperatura: "),120,ibateria.temp.." *C",0.7,blanco,negro)
screen.print(10,135,"Voltaje: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Voltaje: "),135,ibateria.volt.." V",0.7,blanco,negro)
screen.print(10,165,"Nick: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Nick: "),165,inick,0.7,blanco,negro)
screen.print(10,180,"Velocidad de CPU: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("Velocidad de CPU: "),180,icpu,0.7,blanco,negro)
screen.print(10,195,"RAM Total: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("RAM Total: "),195,ispace.getinitmemory,0.7,blanco,negro)
screen.print(10,210,"RAM Usada: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("RAM usada: "),210,ispace.getusememory,0.7,blanco,negro)
screen.print(10,225,"RAM Libre: ",0.7,blanco,colorTXT[valorFonte])
screen.print(10+screen.textwidth("RAM Libre: "),225,ispace.getfreememory,0.7,blanco,negro)
draw.fillrect(10,240,100,10,blanco)
draw.gradrect(10,240,((os.getinitmemory()-os.getfreememory())/os.getinitmemory())*100,10,colorAlpha[valorFondo],negro,colorAlpha[valorFondo],blanco)
draw.rect(10,240,((os.getinitmemory()-os.getfreememory())/os.getinitmemory())*100,10,negro)
draw.rect(10,240,100,10,negro)
screen.print(115,240,ispace.getusememoryP ,0.7,blanco,colorTXT[valorFonte])
screen.print(240,45,"Espacio Total: ",0.7,blanco,colorTXT[valorFonte])
screen.print(240+screen.textwidth("Espacio Total: "),45,ispace.totalspace,0.7,blanco,negro)
screen.print(240,60,"Espacio Usada: ",0.7,blanco,colorTXT[valorFonte])
screen.print(240+screen.textwidth("Espacio usada: "),60,ispace.usespace,0.6,blanco,negro)
screen.print(240,75,"Espacio Libre: ",0.7,blanco,colorTXT[valorFonte])
screen.print(240+screen.textwidth("Espacio Libre: "),75,ispace.freespace,0.6,blanco,negro)
screen.print(240,90,"Numero de Carpetas: ",0.7,blanco,colorTXT[valorFonte])
screen.print(240+screen.textwidth("Numero de Carpetas: "),90,icarpetas,0.7,blanco,negro)
screen.print(240,105,"Numero de Archivos: ",0.7,blanco,colorTXT[valorFonte])
screen.print(240+screen.textwidth("Numero de Archivos: "),105,iarchivos,0.7,blanco,negro)
draw.fillrect(240,120,100,10,blanco)
draw.gradrect(240,120,((files.totalspace()-files.freespace())/files.totalspace())*100,10,colorAlpha[valorFondo],negro,colorAlpha[valorFondo],blanco)
draw.rect(240,120,((files.totalspace()-files.freespace())/files.totalspace())*100,10,negro)
draw.rect(240,120,100,10,negro)
screen.print(355,120,ispace.usespaceP,0.7,blanco,colorTXT[valorFonte])
screen.print(240,260,"Presiona el boton R para obtener un grafico de esta carpeta",0.6,blanco,negro,"center",480)
if controls.press("circle") then
break
end
if controls.press("r") then
curDicT = files.list(memoSelect)
curAux = ""
table.sort(curDicT, sp)
shell = false
slideShellBool = false
slideShell = 0
infoGraf(memoSelect)
bool_fondoTrans = false
in_explorer = true
break
end
screen.flip()
end
|
local UV = require('uv')
local function set_timeout(duration, callback, ...)
local args = {...}
local timer = UV.new_timer()
timer:start(duration, 0, function (status)
timer:close()
callback(unpack(args))
end)
return timer
end
local function set_interval(period, callback, ...)
local args = {...}
local timer = UV.new_timer()
timer:start(period, period, function (status)
callback(unpack(args))
end)
return timer
end
local function clear_timer(timer)
timer:stop()
timer:close()
end
return {
new = UV.new_timer,
set_timeout = set_timeout,
set_interval = set_interval,
clear_timer = clear_timer,
}
|
style = {["off_color"] = "fff",
["on_color"] = "fff",
["line_color"] = "000",
["line_width"] = "2"};
result = {8,16,6,3,8,4}
test = {3,4,6,8,10,16}
answ = lib.math.random_shuffle(test)
ind = math.random(6)
for i = 1,6 do
if(answ[i] == result[ind]) then
index = i-1
end
end
w = 5
ow = 20
v = 70
mycanvas = function( )
lib.start_canvas(300, 250, "center")
lib.add_triangle (2*v, v+ow, 3*v, 2*v, style, false, false)
if (ind == 1) then
lib.add_straight_path (v/2, ow+2*v, {{(5*v-ow)/2-w, -v}}, style, false, false)
lib.add_straight_path (3*v+2*ow-w, ow+2*v, {{w-(5*v-ow)/2, -v}}, style, false, false)
end
if (ind == 2) then
lib.add_straight_path (v/2, ow+2*v, {{(5*v-ow)/2-w, -v}}, style, false, false)
lib.add_straight_path (3*v+2*ow-w, ow+2*v, {{w-(5*v-ow)/2, -v}}, style, false, false)
lib.add_straight_path (2*v, ow, {{0, 2*v}}, style, false, false)
end
if (ind == 3) then
lib.add_straight_path (v, v+2*ow, {{2*v, 0}}, style, false, false)
lib.add_straight_path (2*v, ow, {{0, 2*v}}, style, false, false)
end
if (ind == 4) then
lib.add_straight_path (2*v, ow, {{0, 2*v}}, style, false, false)
end
if (ind == 5) then
lib.add_straight_path (v/2, ow+2*v, {{2*(v-ow)+w, v}, {2*(v-ow)+w, -v} }, style, false, false)
lib.add_straight_path (2*v, ow, {{0, 3*v}}, style, false, false)
end
if (ind == 6) then
lib.add_straight_path (v/2, ow+2*v, {{v+2*ow-w, -v+ow}}, style, false, false)
lib.add_straight_path (7*v/2, ow+2*v, {{-v-2*ow+w, -v+ow}}, style, false, false)
lib.add_straight_path (2*v, ow, {{0, (3*v-5*w)/2}}, style, false, false)
end
lib.end_canvas()
end
|
-- Load support for intllib.
local MP = minetest.get_modpath(minetest.get_current_modname())
local S = minetest.get_translator and minetest.get_translator("mobs_redo") or
dofile(MP .. "/intllib.lua")
-- CMI support check
local use_cmi = minetest.global_exists("cmi")
mobs = {
mod = "redo",
version = "20210418",
intllib = S,
invis = minetest.global_exists("invisibility") and invisibility or {}
}
-- localize common functions
local pi = math.pi
local square = math.sqrt
local sin = math.sin
local cos = math.cos
local abs = math.abs
local min = math.min
local max = math.max
local random = math.random
local floor = math.floor
local ceil = math.ceil
local rad = math.rad
local atann = math.atan
local atan = function(x)
if not x or x ~= x then
--error("atan bassed NaN")
return 0
else
return atann(x)
end
end
local table_copy = table.copy
local table_remove = table.remove
local vadd = vector.add
local vdirection = vector.direction
local vmultiply = vector.multiply
local vsubtract = vector.subtract
local settings = minetest.settings
-- creative check
local creative_cache = minetest.settings:get_bool("creative_mode")
function mobs.is_creative(name)
return creative_cache or minetest.check_player_privs(name,
{creative = true})
end
-- Load settings
local damage_enabled = settings:get_bool("enable_damage")
local mobs_spawn = settings:get_bool("mobs_spawn") ~= false
local peaceful_only = settings:get_bool("only_peaceful_mobs")
local disable_blood = settings:get_bool("mobs_disable_blood")
local mobs_drop_items = settings:get_bool("mobs_drop_items") ~= false
local mobs_griefing = settings:get_bool("mobs_griefing") ~= false
local spawn_protected = settings:get_bool("mobs_spawn_protected") ~= false
local remove_far = settings:get_bool("remove_far_mobs") ~= false
local mob_area_spawn = settings:get_bool("mob_area_spawn")
local difficulty = tonumber(settings:get("mob_difficulty")) or 1.0
local show_health = settings:get_bool("mob_show_health") ~= false
local max_per_block = tonumber(settings:get("max_objects_per_block") or 99)
local mob_nospawn_range = tonumber(settings:get("mob_nospawn_range") or 12)
local active_limit = tonumber(settings:get("mob_active_limit") or 0)
local mob_chance_multiplier = tonumber(settings:get("mob_chance_multiplier") or 1)
local peaceful_player_enabled = settings:get_bool("enable_peaceful_player")
local active_mobs = 0
-- Peaceful mode message so players will know there are no monsters
if peaceful_only then
minetest.register_on_joinplayer(function(player)
minetest.chat_send_player(player:get_player_name(),
S("** Peaceful Mode Active - No Monsters Will Spawn"))
end)
end
-- calculate aoc range for mob count
local aoc_range = tonumber(settings:get("active_block_range")) * 16
-- pathfinding settings
local enable_pathfinding = true
local stuck_timeout = 3 -- how long before stuck mod starts searching
local stuck_path_timeout = 10 -- how long will mob follow path before giving up
-- default nodes
local node_fire = "fire:basic_flame"
local node_permanent_flame = "fire:permanent_flame"
local node_ice = "default:ice"
local node_snowblock = "default:snowblock"
local node_snow = "default:snow"
mobs.fallback_node = minetest.registered_aliases["mapgen_dirt"] or "default:dirt"
local mob_class = {
stepheight = 1.1,
fly_in = "air",
owner = "",
order = "",
jump_height = 4,
lifetimer = 180, -- 3 minutes
physical = true,
collisionbox = {-0.25, -0.25, -0.25, 0.25, 0.25, 0.25},
visual_size = {x = 1, y = 1},
texture_mods = "",
makes_footstep_sound = false,
view_range = 5,
walk_velocity = 1,
run_velocity = 2,
light_damage = 0,
light_damage_min = 14,
light_damage_max = 15,
water_damage = 0,
lava_damage = 4,
fire_damage = 4,
air_damage = 0,
suffocation = 2,
fall_damage = 1,
fall_speed = -10, -- must be lower than -2 (default: -10)
drops = {},
armor = 100,
sounds = {},
jump = true,
knock_back = true,
walk_chance = 50,
stand_chance = 30,
attack_chance = 5,
passive = false,
blood_amount = 5,
blood_texture = "mobs_blood.png",
shoot_offset = 0,
floats = 1, -- floats in water by default
replace_offset = 0,
timer = 0,
metadata3 = 0,
env_damage_timer = 0, -- only used when state = "attack"
tamed = false,
pause_timer = 0,
horny = false,
hornytimer = 0,
child = false,
gotten = false,
health = 0,
reach = 3,
htimer = 0,
docile_by_day = false,
time_of_day = 0.5,
fear_height = 0,
runaway_timer = 0,
immune_to = {},
explosion_timer = 3,
allow_fuse_reset = true,
stop_to_explode = true,
dogshoot_count = 0,
dogshoot_count_max = 5,
dogshoot_count2_max = 5,
group_attack = false,
attack_monsters = false,
attack_animals = false,
attack_players = true,
attack_npcs = true,
facing_fence = false,
_cmi_is_mob = true
}
local mob_class_meta = {__index = mob_class}
-- play sound
function mob_class:mob_sound(sound)
local pitch = 1.0
-- higher pitch for a child
if self.child then pitch = pitch * 1.5 end
-- a little random pitch to be different
pitch = pitch + random(-10, 10) * 0.005
if sound then
minetest.sound_play(sound, {
object = self.object,
gain = 1.0,
max_hear_distance = self.sounds.distance,
pitch = pitch
}, true)
end
end
-- attack player/mob
function mob_class:do_attack(player)
if self.state == "attack" then
return
end
self.attack = player
self.state = "attack"
if random(0, 100) < 90 then
self:mob_sound(self.sounds.war_cry)
end
end
-- calculate distance
local get_distance = function(a, b)
if not a or not b then return 50 end -- nil check
local x, y, z = a.x - b.x, a.y - b.y, a.z - b.z
return square(x * x + y * y + z * z)
end
-- collision function based on jordan4ibanez' open_ai mod
function mob_class:collision()
local pos = self.object:get_pos()
local x, z = 0, 0
local width = -self.collisionbox[1] + self.collisionbox[4] + 0.5
for _,object in ipairs(minetest.get_objects_inside_radius(pos, width)) do
if object:is_player() then
-- or (object:get_luaentity()
-- and object:get_luaentity()._cmi_is_mob == true
-- and object ~= self.object) then
local pos2 = object:get_pos()
local vec = {x = pos.x - pos2.x, z = pos.z - pos2.z}
x = x + vec.x
z = z + vec.z
end
end
return({x, z})
end
-- check if string exists in another string or table
local check_for = function(look_for, look_inside)
if type(look_inside) == "string" and look_inside == look_for then
return true
elseif type(look_inside) == "table" then
for _, str in pairs(look_inside) do
if str == look_for then
return true
end
if str:find("group:") then
local group = str:split(":")[2]
if minetest.get_item_group(look_for, group) ~= 0 then
return true
end
end
end
end
return false
end
-- move mob in facing direction
function mob_class:set_velocity(v)
-- halt mob if it has been ordered to stay
if self.order == "stand" then
self.object:set_velocity({x = 0, y = 0, z = 0})
return
end
local c_x, c_y = 0, 0
-- can mob be pushed, if so calculate direction
if self.pushable then
c_x, c_y = unpack(self:collision())
end
local yaw = (self.object:get_yaw() or 0) + (self.rotate or 0)
-- nil check for velocity
v = v or 0.01
-- check if standing in liquid with max viscosity of 7
local visc = min(minetest.registered_nodes[self.standing_in].liquid_viscosity, 7)
-- only slow mob trying to move while inside a viscous fluid that
-- they aren't meant to be in (fish in water, spiders in cobweb etc)
if v > 0 and visc and visc > 0
and not check_for(self.standing_in, self.fly_in) then
v = v / (visc + 1)
end
-- set velocity
local vel = self.object:get_velocity() or 0
local new_vel = {
x = (sin(yaw) * -v) + c_x,
y = vel.y,
z = (cos(yaw) * v) + c_y}
self.object:set_velocity(new_vel)
end
-- global version of above function
function mobs:set_velocity(entity, v)
mob_class.set_velocity(entity, v)
end
-- calculate mob velocity
function mob_class:get_velocity()
local v = self.object:get_velocity()
if not v then return 0 end
return (v.x * v.x + v.z * v.z) ^ 0.5
end
-- set and return valid yaw
function mob_class:set_yaw(yaw, delay)
if not yaw or yaw ~= yaw then
yaw = 0
end
delay = delay or 0
if delay == 0 then
self.object:set_yaw(yaw)
return yaw
end
self.target_yaw = yaw
self.delay = delay
return self.target_yaw
end
-- global function to set mob yaw
function mobs:yaw(entity, yaw, delay)
mob_class.set_yaw(entity, yaw, delay)
end
-- set defined animation
function mob_class:set_animation(anim, force)
if not self.animation or not anim then return end
self.animation.current = self.animation.current or ""
-- only use different animation for attacks when using same set
if force ~= true and anim ~= "punch" and anim ~= "shoot"
and string.find(self.animation.current, anim) then
return
end
local num = 0
-- check for more than one animation (max 4)
for n = 1, 4 do
if self.animation[anim .. n .. "_start"]
and self.animation[anim .. n .. "_end"] then
num = n
end
end
-- choose random animation from set
if num > 0 then
num = random(0, num)
anim = anim .. (num ~= 0 and num or "")
end
if anim == self.animation.current
or not self.animation[anim .. "_start"]
or not self.animation[anim .. "_end"] then
return
end
self.animation.current = anim
self.object:set_animation({
x = self.animation[anim .. "_start"],
y = self.animation[anim .. "_end"]},
self.animation[anim .. "_speed"] or
self.animation.speed_normal or 15,
0, self.animation[anim .. "_loop"] ~= false)
end
-- above function exported for mount.lua
function mobs:set_animation(entity, anim)
entity.set_animation(entity, anim)
end
-- check line of sight (BrunoMine)
local line_of_sight = function(self, pos1, pos2, stepsize)
stepsize = stepsize or 1
local s, pos = minetest.line_of_sight(pos1, pos2, stepsize)
-- normal walking and flying mobs can see you through air
if s == true then
return true
end
-- New pos1 to be analyzed
local npos1 = {x = pos1.x, y = pos1.y, z = pos1.z}
local r, pos = minetest.line_of_sight(npos1, pos2, stepsize)
-- Checks the return
if r == true then return true end
-- Nodename found
local nn = minetest.get_node(pos).name
-- Target Distance (td) to travel
local td = get_distance(pos1, pos2)
-- Actual Distance (ad) traveled
local ad = 0
-- It continues to advance in the line of sight in search of a real
-- obstruction which counts as 'walkable' nodebox.
while minetest.registered_nodes[nn]
and (minetest.registered_nodes[nn].walkable == false) do
-- Check if you can still move forward
if td < ad + stepsize then
return true -- Reached the target
end
-- Moves the analyzed pos
local d = get_distance(pos1, pos2)
npos1.x = ((pos2.x - pos1.x) / d * stepsize) + pos1.x
npos1.y = ((pos2.y - pos1.y) / d * stepsize) + pos1.y
npos1.z = ((pos2.z - pos1.z) / d * stepsize) + pos1.z
-- NaN checks
if d == 0
or npos1.x ~= npos1.x
or npos1.y ~= npos1.y
or npos1.z ~= npos1.z then
return false
end
ad = ad + stepsize
-- scan again
r, pos = minetest.line_of_sight(npos1, pos2, stepsize)
if r == true then return true end
-- New Nodename found
nn = minetest.get_node(pos).name
end
return false
end
-- check line of sight (by BrunoMine, tweaked by Astrobe)
local new_line_of_sight = function(self, pos1, pos2, stepsize)
if not pos1 or not pos2 then return end
stepsize = stepsize or 1
local stepv = vmultiply(vdirection(pos1, pos2), stepsize)
local s, pos = minetest.line_of_sight(pos1, pos2, stepsize)
-- normal walking and flying mobs can see you through air
if s == true then return true end
-- New pos1 to be analyzed
local npos1 = {x = pos1.x, y = pos1.y, z = pos1.z}
local r, pos = minetest.line_of_sight(npos1, pos2, stepsize)
-- Checks the return
if r == true then return true end
-- Nodename found
local nn = minetest.get_node(pos).name
-- It continues to advance in the line of sight in search of a real
-- obstruction which counts as 'walkable' nodebox.
while minetest.registered_nodes[nn]
and (minetest.registered_nodes[nn].walkable == false) do
npos1 = vadd(npos1, stepv)
if get_distance(npos1, pos2) < stepsize then return true end
-- scan again
r, pos = minetest.line_of_sight(npos1, pos2, stepsize)
if r == true then return true end
-- New Nodename found
nn = minetest.get_node(pos).name
end
return false
end
-- check line of sight using raycasting (thanks Astrobe)
local ray_line_of_sight = function(self, pos1, pos2)
local ray = minetest.raycast(pos1, pos2, true, false)
local thing = ray:next()
while thing do -- thing.type, thing.ref
if thing.type == "node" then
local name = minetest.get_node(thing.under).name
if minetest.registered_items[name]
and minetest.registered_items[name].walkable then
return false
end
end
thing = ray:next()
end
return true
end
function mob_class:line_of_sight(pos1, pos2, stepsize)
if minetest.raycast then -- only use if minetest 5.0 is detected
return ray_line_of_sight(self, pos1, pos2)
end
return line_of_sight(self, pos1, pos2, stepsize)
end
-- global function
function mobs:line_of_sight(entity, pos1, pos2, stepsize)
return entity:line_of_sight(pos1, pos2, stepsize)
end
function mob_class:attempt_flight_correction(override)
if self:flight_check() and override ~= true then return true end
-- We are not flying in what we are supposed to.
-- See if we can find intended flight medium and return to it
local pos = self.object:get_pos() ; if not pos then return true end
local searchnodes = self.fly_in
if type(searchnodes) == "string" then
searchnodes = {self.fly_in}
end
local flyable_nodes = minetest.find_nodes_in_area(
{x = pos.x - 1, y = pos.y - 1, z = pos.z - 1},
{x = pos.x + 1, y = pos.y + 0, z = pos.z + 1}, searchnodes)
-- pos.y + 0 hopefully fixes floating swimmers
if #flyable_nodes < 1 then
return false
end
local escape_target = flyable_nodes[random(#flyable_nodes)]
local escape_direction = vdirection(pos, escape_target)
self.object:set_velocity(
vmultiply(escape_direction, 1)) --self.run_velocity))
return true
end
-- are we flying in what we are suppose to? (taikedz)
function mob_class:flight_check()
local def = minetest.registered_nodes[self.standing_in]
if not def then return false end
-- are we standing inside what we should be to fly/swim ?
if check_for(self.standing_in, self.fly_in) then
return true
end
-- stops mobs getting stuck inside stairs and plantlike nodes
if def.drawtype ~= "airlike"
and def.drawtype ~= "liquid"
and def.drawtype ~= "flowingliquid" then
return true
end
return false
end
-- turn mob to face position
local yaw_to_pos = function(self, target, rot)
rot = rot or 0
local pos = self.object:get_pos()
local vec = {x = target.x - pos.x, z = target.z - pos.z}
local yaw = (atan(vec.z / vec.x) + rot + pi / 2) - self.rotate
if target.x > pos.x then
yaw = yaw + pi
end
yaw = self:set_yaw(yaw, rot)
return yaw
end
function mobs:yaw_to_pos(self, target, rot)
return yaw_to_pos(self, target, rot)
end
-- if stay near set then check periodically for nodes and turn towards them
function mob_class:do_stay_near()
if not self.stay_near then return false end
local pos = self.object:get_pos()
local searchnodes = self.stay_near[1]
local chance = self.stay_near[2] or 10
if not pos or random(chance) > 1 then
return false
end
if type(searchnodes) == "string" then
searchnodes = {self.stay_near[1]}
end
local r = self.view_range
local nearby_nodes = minetest.find_nodes_in_area(
{x = pos.x - r, y = pos.y - 1, z = pos.z - r},
{x = pos.x + r, y = pos.y + 1, z = pos.z + r}, searchnodes)
if #nearby_nodes < 1 then
return false
end
yaw_to_pos(self, nearby_nodes[random(#nearby_nodes)])
self:set_animation("walk")
self:set_velocity(self.walk_velocity)
return true
end
-- custom particle effects
local effect = function(pos, amount, texture, min_size, max_size,
radius, gravity, glow, fall)
radius = radius or 2
min_size = min_size or 0.5
max_size = max_size or 1
gravity = gravity or -10
glow = glow or 0
if fall == true then
fall = 0
elseif fall == false then
fall = radius
else
fall = -radius
end
minetest.add_particlespawner({
amount = amount,
time = 0.25,
minpos = pos,
maxpos = pos,
minvel = {x = -radius, y = fall, z = -radius},
maxvel = {x = radius, y = radius, z = radius},
minacc = {x = 0, y = gravity, z = 0},
maxacc = {x = 0, y = gravity, z = 0},
minexptime = 0.1,
maxexptime = 1,
minsize = min_size,
maxsize = max_size,
texture = texture,
glow = glow
})
end
function mobs:effect(pos, amount, texture, min_size, max_size,
radius, gravity, glow, fall)
effect(pos, amount, texture, min_size, max_size, radius, gravity, glow, fall)
end
-- update nametag colour
function mob_class:update_tag()
local col = "#00FF00"
local qua = self.hp_max / 4
if self.health <= floor(qua * 3) then
col = "#FFFF00"
end
if self.health <= floor(qua * 2) then
col = "#FF6600"
end
if self.health <= floor(qua) then
col = "#FF0000"
end
self.object:set_properties({
nametag = self.nametag,
nametag_color = col
})
end
-- drop items
function mob_class:item_drop()
-- no drops if disabled by setting or mob is child
if not mobs_drop_items or self.child then return end
local pos = self.object:get_pos()
-- check for drops function
self.drops = type(self.drops) == "function"
and self.drops(pos) or self.drops
-- check for nil or no drops
if not self.drops or #self.drops == 0 then
return
end
-- was mob killed by player?
local death_by_player = self.cause_of_death
and self.cause_of_death.puncher
and self.cause_of_death.puncher:is_player()
local obj, item, num
for n = 1, #self.drops do
if random(self.drops[n].chance) == 1 then
num = random(self.drops[n].min or 0, self.drops[n].max or 1)
item = self.drops[n].name
-- cook items on a hot death
if self.cause_of_death.hot then
local output = minetest.get_craft_result({
method = "cooking", width = 1, items = {item}})
if output and output.item and not output.item:is_empty() then
item = output.item:get_name()
end
end
-- only drop rare items (drops.min = 0) if killed by player
if death_by_player then
obj = minetest.add_item(pos, ItemStack(item .. " " .. num))
elseif self.drops[n].min ~= 0 then
obj = minetest.add_item(pos, ItemStack(item .. " " .. num))
end
if obj and obj:get_luaentity() then
obj:set_velocity({
x = random(-10, 10) / 9,
y = 6,
z = random(-10, 10) / 9
})
elseif obj then
obj:remove() -- item does not exist
end
end
end
self.drops = {}
end
-- remove mob and descrease counter
local remove_mob = function(self, decrease)
self.object:remove()
if decrease and active_limit > 0 then
active_mobs = active_mobs - 1
if active_mobs < 0 then
active_mobs = 0
end
end
--print("-- active mobs: " .. active_mobs .. " / " .. active_limit)
end
-- global function for removing mobs
function mobs:remove(self, decrease)
remove_mob(self, decrease)
end
-- check if mob is dead or only hurt
function mob_class:check_for_death(cmi_cause)
-- We dead already
if self.state == "die" then
return true
end
-- has health actually changed?
if self.health == self.old_health and self.health > 0 then
return false
end
local damaged = self.health < self.old_health
self.old_health = self.health
-- still got some health? play hurt sound
if self.health > 0 then
-- only play hurt sound if damaged
if damaged then
self:mob_sound(self.sounds.damage)
end
-- make sure health isn't higher than max
if self.health > self.hp_max then
self.health = self.hp_max
end
-- backup nametag so we can show health stats
if not self.nametag2 then
self.nametag2 = self.nametag or ""
end
if show_health
and (cmi_cause and cmi_cause.type == "punch") then
self.htimer = 2
self.nametag = "♥ " .. self.health .. " / " .. self.hp_max
self:update_tag()
end
return false
end
self.cause_of_death = cmi_cause
-- drop items
self:item_drop()
self:mob_sound(self.sounds.death)
local pos = self.object:get_pos()
-- execute custom death function
if pos and self.on_die then
self:on_die(pos)
if use_cmi then
cmi.notify_die(self.object, cmi_cause)
end
remove_mob(self, true)
return true
end
-- check for custom death function and die animation
if self.animation
and self.animation.die_start
and self.animation.die_end then
local frames = self.animation.die_end - self.animation.die_start
local speed = self.animation.die_speed or 15
local length = max((frames / speed), 0)
local rot = self.animation.die_rotate and 5
self.attack = nil
self.following = nil
self.v_start = false
self.timer = 0
self.blinktimer = 0
self.passive = true
self.state = "die"
self.object:set_properties({
pointable = false, collide_with_objects = false,
automatic_rotate = rot, static_save = false
})
self:set_velocity(0)
self:set_animation("die")
minetest.after(length, function(self)
if self.object:get_luaentity() then
if use_cmi then
cmi.notify_die(self.object, cmi_cause)
end
remove_mob(self, true)
end
end, self)
return true
elseif pos then -- otherwise remove mod and show particle effect
if use_cmi then
cmi.notify_die(self.object, cmi_cause)
end
remove_mob(self, true)
effect(pos, 20, "tnt_smoke.png")
end
return true
end
-- get node but use fallback for nil or unknown
local node_ok = function(pos, fallback)
fallback = fallback or mobs.fallback_node
local node = minetest.get_node_or_nil(pos)
if node and minetest.registered_nodes[node.name] then
return node
end
return minetest.registered_nodes[fallback]
end
-- Returns true is node can deal damage to self
local is_node_dangerous = function(self, nodename)
if self.water_damage > 0
and minetest.get_item_group(nodename, "water") ~= 0 then
return true
end
if self.lava_damage > 0
and minetest.get_item_group(nodename, "lava") ~= 0 then
return true
end
if self.fire_damage > 0
and minetest.get_item_group(nodename, "fire") ~= 0 then
return true
end
if minetest.registered_nodes[nodename].damage_per_second > 0 then
return true
end
return false
end
-- is mob facing a cliff
function mob_class:is_at_cliff()
if self.fear_height == 0 then -- 0 for no falling protection!
return false
end
-- get yaw but if nil returned object no longer exists
local yaw = self.object:get_yaw()
if not yaw then return false end
local dir_x = -sin(yaw) * (self.collisionbox[4] + 0.5)
local dir_z = cos(yaw) * (self.collisionbox[4] + 0.5)
local pos = self.object:get_pos()
local ypos = pos.y + self.collisionbox[2] -- just above floor
local free_fall, blocker = minetest.line_of_sight(
{x = pos.x + dir_x, y = ypos, z = pos.z + dir_z},
{x = pos.x + dir_x, y = ypos - self.fear_height, z = pos.z + dir_z})
-- check for straight drop
if free_fall then
return true
end
local bnode = node_ok(blocker)
-- will we drop onto dangerous node?
if is_node_dangerous(self, bnode.name) then
return true
end
local def = minetest.registered_nodes[bnode.name]
return (not def and def.walkable)
end
-- environmental damage (water, lava, fire, light etc.)
function mob_class:do_env_damage()
-- feed/tame text timer (so mob 'full' messages dont spam chat)
if self.htimer > 0 then
self.htimer = self.htimer - 1
end
-- reset nametag after showing health stats
if self.htimer < 1 and self.nametag2 then
self.nametag = self.nametag2
self.nametag2 = nil
self:update_tag()
end
local pos = self.object:get_pos() ; if not pos then return end
self.time_of_day = minetest.get_timeofday()
-- halt mob if standing inside ignore node
if self.standing_in == "ignore" then
self.object:set_velocity({x = 0, y = 0, z = 0})
return true
end
-- particle appears at random mob height
local py = {
x = pos.x,
y = pos.y + random(self.collisionbox[2], self.collisionbox[5]),
z = pos.z
}
local nodef = minetest.registered_nodes[self.standing_in]
-- water
if self.water_damage ~= 0
and nodef.groups.water then
self.health = self.health - self.water_damage
effect(py, 5, "bubble.png", nil, nil, 1, nil)
if self:check_for_death({type = "environment",
pos = pos, node = self.standing_in}) then
return true
end
-- lava damage
elseif self.lava_damage ~= 0
and nodef.groups.lava then
self.health = self.health - self.lava_damage
effect(py, 15, "fire_basic_flame.png", 1, 5, 1, 0.2, 15, true)
if self:check_for_death({type = "environment", pos = pos,
node = self.standing_in, hot = true}) then
return true
end
-- fire damage
elseif self.fire_damage ~= 0
and nodef.groups.fire then
self.health = self.health - self.fire_damage
effect(py, 15, "fire_basic_flame.png", 1, 5, 1, 0.2, 15, true)
if self:check_for_death({type = "environment", pos = pos,
node = self.standing_in, hot = true}) then
return true
end
-- damage_per_second node check (not fire and lava)
elseif nodef.damage_per_second ~= 0
and nodef.groups.lava == nil and nodef.groups.fire == nil then
if self.name == "mobs:dog" or self.name == "mobs:cat" or self.name == "mobs:sheep" or self.name == "mobs:dragon" or self.name == "mobs:knight_1248" or self.name == "mobs:fox" or self.name == "mobs:tortoise" then
else
self.health = self.health - nodef.damage_per_second
effect(py, 5, "tnt_smoke.png")
if self:check_for_death({type = "environment",
pos = pos, node = self.standing_in}) then
return true
end
end
end
-- air damage
if self.air_damage ~= 0 and self.standing_in == "air" then
self.health = self.health - self.air_damage
effect(py, 3, "bubble.png", 1, 1, 1, 0.2)
if self:check_for_death({type = "environment",
pos = pos, node = self.standing_in}) then
return true
end
end
-- is mob light sensative, or scared of the dark :P
if self.light_damage ~= 0 then
local light = minetest.get_node_light(pos) or 0
if light >= self.light_damage_min
and light <= self.light_damage_max then
self.health = self.health - self.light_damage
effect(py, 5, "tnt_smoke.png")
if self:check_for_death({type = "light"}) then
return true
end
end
end
--- suffocation inside solid node
if (self.suffocation and self.suffocation ~= 0)
and (nodef.walkable == nil or nodef.walkable == true)
and (nodef.collision_box == nil or nodef.collision_box.type == "regular")
and (nodef.node_box == nil or nodef.node_box.type == "regular")
and (nodef.groups.disable_suffocation ~= 1) then
local damage
if self.suffocation == true then
damage = 2
else
damage = (self.suffocation or 2)
end
self.health = self.health - damage
if self:check_for_death({type = "suffocation",
pos = pos, node = self.standing_in}) then
return true
end
end
return self:check_for_death({type = "unknown"})
end
-- jump if facing a solid node (not fences or gates)
function mob_class:do_jump()
if not self.jump
or self.jump_height == 0
or self.fly
or self.child
or self.order == "stand" then
return false
end
self.facing_fence = false
-- something stopping us while moving?
if self.state ~= "stand"
and self:get_velocity() > 0.5
and self.object:get_velocity().y ~= 0 then
return false
end
local pos = self.object:get_pos()
local yaw = self.object:get_yaw()
-- sanity check
if not yaw then return false end
-- we can only jump if standing on solid node
if minetest.registered_nodes[self.standing_on].walkable == false then
return false
end
-- where is front
local dir_x = -sin(yaw) * (self.collisionbox[4] + 0.5)
local dir_z = cos(yaw) * (self.collisionbox[4] + 0.5)
-- set y_pos to base of mob
pos.y = pos.y + self.collisionbox[2]
-- what is in front of mob?
local nod = node_ok({
x = pos.x + dir_x, y = pos.y + 0.5, z = pos.z + dir_z
})
-- what is above and in front?
local nodt = node_ok({
x = pos.x + dir_x, y = pos.y + 1.5, z = pos.z + dir_z
})
local blocked = minetest.registered_nodes[nodt.name].walkable
--print("standing on:", self.standing_on, pos.y - 0.25)
--print("in front:", nod.name, pos.y + 0.5)
--print("in front above:", nodt.name, pos.y + 1.5)
-- jump if standing on solid node (not snow) and not blocked above
if (self.walk_chance == 0
or minetest.registered_items[nod.name].walkable)
and not blocked
and nod.name ~= node_snow then
if not nod.name:find("fence")
and not nod.name:find("gate")
and not nod.name:find("wall") then
local v = self.object:get_velocity()
v.y = self.jump_height
self:set_animation("jump") -- only when defined
self.object:set_velocity(v)
-- when in air move forward
minetest.after(0.3, function(self, v)
if self.object:get_luaentity() then
self.object:set_acceleration({
x = v.x * 2,
y = 0,
z = v.z * 2
})
end
end, self, v)
if self:get_velocity() > 0 then
self:mob_sound(self.sounds.jump)
end
return true
else
self.facing_fence = true
end
end
-- if blocked against a block/wall for 5 counts then turn
if not self.following
and (self.facing_fence or blocked) then
self.jump_count = (self.jump_count or 0) + 1
if self.jump_count > 4 then
local yaw = self.object:get_yaw() or 0
local turn = random(0, 2) + 1.35
yaw = self:set_yaw(yaw + turn, 12)
self.jump_count = 0
end
end
return false
end
-- blast damage to entities nearby (modified from TNT mod)
local entity_physics = function(pos, radius)
radius = radius * 2
local objs = minetest.get_objects_inside_radius(pos, radius)
local obj_pos, dist
for n = 1, #objs do
obj_pos = objs[n]:get_pos()
dist = get_distance(pos, obj_pos)
if dist < 1 then dist = 1 end
local damage = floor((4 / dist) * radius)
local ent = objs[n]:get_luaentity()
-- punches work on entities AND players
objs[n]:punch(objs[n], 1.0, {
full_punch_interval = 1.0,
damage_groups = {fleshy = damage},
}, pos)
end
end
-- can mob see player
local is_invisible = function(self, player_name)
if mobs.invis[player_name] and not self.ignore_invisibility then
return true
end
end
-- should mob follow what I'm holding ?
function mob_class:follow_holding(clicker)
if is_invisible(self, clicker:get_player_name()) then
return false
end
local item = clicker:get_wielded_item()
-- are we holding an item mob can follow ?
if check_for(item:get_name(), self.follow) then
return true
end
return false
end
-- Thanks Wuzzy for the following editable settings
local HORNY_TIME = 30
local HORNY_AGAIN_TIME = 300
local CHILD_GROW_TIME = 60 * 20 -- 20 minutes
-- find two animals of same type and breed if nearby and horny
function mob_class:breed()
-- child takes a long time before growing into adult
if self.child == true then
self.hornytimer = self.hornytimer + 1
if self.hornytimer > CHILD_GROW_TIME then
self.child = false
self.hornytimer = 0
self.object:set_properties({
textures = self.base_texture,
mesh = self.base_mesh,
visual_size = self.base_size,
collisionbox = self.base_colbox,
selectionbox = self.base_selbox
})
-- custom function when child grows up
if self.on_grown then
self.on_grown(self)
else
-- jump when fully grown so as not to fall into ground
-- self.object:set_velocity({
-- x = 0,
-- y = self.jump_height,
-- z = 0
-- })
local pos = self.object:get_pos() ; if not pos then return end
local ent = self.object:get_luaentity()
pos.y = pos.y + (ent.collisionbox[2] * -1) - 0.4
self.object:set_pos(pos)
end
end
return
end
-- horny animal can mate for HORNY_TIME seconds,
-- afterwards horny animal cannot mate again for HORNY_AGAIN_TIME seconds
if self.horny == true
and self.hornytimer < HORNY_TIME + HORNY_AGAIN_TIME then
self.hornytimer = self.hornytimer + 1
if self.hornytimer >= HORNY_TIME + HORNY_AGAIN_TIME then
self.hornytimer = 0
self.horny = false
end
end
-- find another same animal who is also horny and mate if nearby
if self.horny == true
and self.hornytimer <= HORNY_TIME then
local pos = self.object:get_pos()
effect({x = pos.x, y = pos.y + 1, z = pos.z}, 8,
"heart.png", 3, 4, 1, 0.1)
local objs = minetest.get_objects_inside_radius(pos, 3)
local ent
for n = 1, #objs do
ent = objs[n]:get_luaentity()
-- check for same animal with different colour
local canmate = false
if ent then
if ent.name == self.name then
canmate = true
else
local entname = ent.name:split(":")
local selfname = self.name:split(":")
if entname[1] == selfname[1] then
entname = entname[2]:split("_")
selfname = selfname[2]:split("_")
if entname[1] == selfname[1] then
canmate = true
end
end
end
end
-- found another similar horny animal that isn't self?
if ent and ent.object ~= self.object
and canmate == true
and ent.horny == true
and ent.hornytimer <= HORNY_TIME then
local pos2 = ent.object:get_pos()
-- Have mobs face one another
yaw_to_pos(self, pos2)
yaw_to_pos(ent, self.object:get_pos())
self.hornytimer = HORNY_TIME + 1
ent.hornytimer = HORNY_TIME + 1
-- have we reached active mob limit
if active_limit > 0 and active_mobs >= active_limit then
minetest.chat_send_player(self.owner,
S("Active Mob Limit Reached!")
.. " (" .. active_mobs
.. " / " .. active_limit .. ")")
return
end
-- spawn baby
minetest.after(5, function(self, ent)
if not self.object:get_luaentity() then
return
end
-- custom breed function
if self.on_breed then
-- when false skip going any further
if self:on_breed(ent) == false then
return
end
else
effect(pos, 15, "tnt_smoke.png", 1, 2, 2, 15, 5)
end
pos.y = pos.y + 0.5 -- spawn child a little higher
local mob = minetest.add_entity(pos, self.name)
local ent2 = mob:get_luaentity()
local textures = self.base_texture
-- using specific child texture (if found)
if self.child_texture then
textures = self.child_texture[1]
end
-- and resize to half height
mob:set_properties({
textures = textures,
visual_size = {
x = self.base_size.x * .5,
y = self.base_size.y * .5
},
collisionbox = {
self.base_colbox[1] * .5,
self.base_colbox[2] * .5,
self.base_colbox[3] * .5,
self.base_colbox[4] * .5,
self.base_colbox[5] * .5,
self.base_colbox[6] * .5
},
selectionbox = {
self.base_selbox[1] * .5,
self.base_selbox[2] * .5,
self.base_selbox[3] * .5,
self.base_selbox[4] * .5,
self.base_selbox[5] * .5,
self.base_selbox[6] * .5
},
})
-- tamed and owned by parents' owner
ent2.child = true
ent2.tamed = true
ent2.owner = self.owner
end, self, ent)
break
end
end
end
end
-- find and replace what mob is looking for (grass, wheat etc.)
function mob_class:replace(pos)
local vel = self.object:get_velocity()
if not vel then return end
if not mobs_griefing
or not self.replace_rate
or not self.replace_what
or self.child == true
or vel.y ~= 0
or random(self.replace_rate) > 1 then
return
end
local what, with, y_offset
if type(self.replace_what[1]) == "table" then
local num = random(#self.replace_what)
what = self.replace_what[num][1] or ""
with = self.replace_what[num][2] or ""
y_offset = self.replace_what[num][3] or 0
else
what = self.replace_what
with = self.replace_with or ""
y_offset = self.replace_offset or 0
end
pos.y = pos.y + y_offset
if #minetest.find_nodes_in_area(pos, pos, what) > 0 then
-- print("replace node = ".. minetest.get_node(pos).name, pos.y)
if self.on_replace then
local oldnode = what or ""
local newnode = with
-- pass actual node name when using table or groups
if type(oldnode) == "table"
or oldnode:find("group:") then
oldnode = minetest.get_node(pos).name
end
if self:on_replace(pos, oldnode, newnode) == false then
return
end
end
minetest.set_node(pos, {name = with})
end
end
-- check if daytime and also if mob is docile during daylight hours
function mob_class:day_docile()
if self.docile_by_day == false then
return false
elseif self.docile_by_day == true
and self.time_of_day > 0.2
and self.time_of_day < 0.8 then
return true
end
end
local los_switcher = false
local height_switcher = false
-- path finding and smart mob routine by rnd,
-- line_of_sight and other edits by Elkien3
function mob_class:smart_mobs(s, p, dist, dtime)
local s1 = self.path.lastpos
local target_pos = p
-- is it becoming stuck?
if abs(s1.x - s.x) + abs(s1.z - s.z) < .5 then
self.path.stuck_timer = self.path.stuck_timer + dtime
else
self.path.stuck_timer = 0
end
self.path.lastpos = {x = s.x, y = s.y, z = s.z}
local use_pathfind = false
local has_lineofsight = minetest.line_of_sight(
{x = s.x, y = (s.y) + .5, z = s.z},
{x = target_pos.x, y = (target_pos.y) + 1.5, z = target_pos.z}, .2)
-- im stuck, search for path
if not has_lineofsight then
if los_switcher == true then
use_pathfind = true
los_switcher = false
end -- cannot see target!
else
if los_switcher == false then
los_switcher = true
use_pathfind = false
minetest.after(1, function(self)
if self.object:get_luaentity() then
if has_lineofsight then
self.path.following = false
end
end
end, self)
end -- can see target!
end
if (self.path.stuck_timer > stuck_timeout and not self.path.following) then
use_pathfind = true
self.path.stuck_timer = 0
minetest.after(1, function(self)
if self.object:get_luaentity() then
if has_lineofsight then
self.path.following = false
end
end
end, self)
end
if (self.path.stuck_timer > stuck_path_timeout and self.path.following) then
use_pathfind = true
self.path.stuck_timer = 0
minetest.after(1, function(self)
if self.object:get_luaentity() then
if has_lineofsight then
self.path.following = false
end
end
end, self)
end
if abs(vsubtract(s,target_pos).y) > self.stepheight then
if height_switcher then
use_pathfind = true
height_switcher = false
end
else
if not height_switcher then
use_pathfind = false
height_switcher = true
end
end
-- lets try find a path, first take care of positions
-- since pathfinder is very sensitive
if use_pathfind then
-- round position to center of node to avoid stuck in walls
-- also adjust height for player models!
s.x = floor(s.x + 0.5)
s.z = floor(s.z + 0.5)
local ssight, sground = minetest.line_of_sight(s, {
x = s.x, y = s.y - 4, z = s.z}, 1)
-- determine node above ground
if not ssight then
s.y = sground.y + 1
end
local p1 = self.attack:get_pos()
p1.x = floor(p1.x + 0.5)
p1.y = floor(p1.y + 0.5)
p1.z = floor(p1.z + 0.5)
local dropheight = 6
if self.fear_height ~= 0 then dropheight = self.fear_height end
local jumpheight = 0
if self.jump and self.jump_height >= 4 then
jumpheight = min(ceil(self.jump_height / 4), 4)
elseif self.stepheight > 0.5 then
jumpheight = 1
end
self.path.way = minetest.find_path(s, p1, 16, jumpheight,
dropheight, "Dijkstra")
--[[
-- show path using particles
if self.path.way and #self.path.way > 0 then
print("-- path length:" .. tonumber(#self.path.way))
for _,pos in pairs(self.path.way) do
minetest.add_particle({
pos = pos,
velocity = {x=0, y=0, z=0},
acceleration = {x=0, y=0, z=0},
expirationtime = 1,
size = 4,
collisiondetection = false,
vertical = false,
texture = "heart.png",
})
end
end
]]
self.state = ""
if self.attack then
self:do_attack(self.attack)
end
-- no path found, try something else
if not self.path.way then
self.path.following = false
-- lets make way by digging/building if not accessible
if self.pathfinding == 2 and mobs_griefing then
-- is player higher than mob?
if s.y < p1.y then
-- build upwards
if not minetest.is_protected(s, "") then
local ndef1 = minetest.registered_nodes[self.standing_in]
if ndef1 and (ndef1.buildable_to or ndef1.groups.liquid) then
minetest.set_node(s, {name = mobs.fallback_node})
end
end
local sheight = ceil(self.collisionbox[5]) + 1
-- assume mob is 2 blocks high so it digs above its head
s.y = s.y + sheight
-- remove one block above to make room to jump
if not minetest.is_protected(s, "") then
local node1 = node_ok(s, "air").name
local ndef1 = minetest.registered_nodes[node1]
if node1 ~= "air"
and node1 ~= "ignore"
and ndef1
and not ndef1.groups.level
and not ndef1.groups.unbreakable
and not ndef1.groups.liquid then
minetest.set_node(s, {name = "air"})
minetest.add_item(s, ItemStack(node1))
end
end
s.y = s.y - sheight
self.object:set_pos({x = s.x, y = s.y + 2, z = s.z})
else -- dig 2 blocks to make door toward player direction
local yaw1 = self.object:get_yaw() + pi / 2
local p1 = {
x = s.x + cos(yaw1),
y = s.y,
z = s.z + sin(yaw1)
}
if not minetest.is_protected(p1, "") then
local node1 = node_ok(p1, "air").name
local ndef1 = minetest.registered_nodes[node1]
if node1 ~= "air"
and node1 ~= "ignore"
and ndef1
and not ndef1.groups.level
and not ndef1.groups.unbreakable
and not ndef1.groups.liquid then
minetest.add_item(p1, ItemStack(node1))
minetest.set_node(p1, {name = "air"})
end
p1.y = p1.y + 1
node1 = node_ok(p1, "air").name
ndef1 = minetest.registered_nodes[node1]
if node1 ~= "air"
and node1 ~= "ignore"
and ndef1
and not ndef1.groups.level
and not ndef1.groups.unbreakable
and not ndef1.groups.liquid then
minetest.add_item(p1, ItemStack(node1))
minetest.set_node(p1, {name = "air"})
end
end
end
end
-- will try again in 2 second
self.path.stuck_timer = stuck_timeout - 2
elseif s.y < p1.y and (not self.fly) then
self:do_jump() --add jump to pathfinding
self.path.following = true
else
-- yay i found path
if self.attack then
self:mob_sound(self.sounds.war_cry)
else
self:mob_sound(self.sounds.random)
end
self:set_velocity(self.walk_velocity)
-- follow path now that it has it
self.path.following = true
end
end
end
-- peaceful player privilege support
local function is_peaceful_player(player)
if peaceful_player_enabled then
local player_name = player:get_player_name()
if player_name
and minetest.check_player_privs(player_name, "peaceful_player") then
return true
end
end
return false
end
-- general attack function for all mobs
function mob_class:general_attack()
-- return if already attacking, passive or docile during day
if self.passive
or self.state == "runaway"
or self.state == "attack"
or self:day_docile() then
return
end
local s = self.object:get_pos() ; if not s then return end
local objs = minetest.get_objects_inside_radius(s, self.view_range)
-- remove entities we aren't interested in
for n = 1, #objs do
local ent = objs[n]:get_luaentity()
-- are we a player?
if objs[n]:is_player() then
-- if player invisible or mob cannot attack then remove from list
if not damage_enabled
or self.attack_players == false
or (self.owner and self.type ~= "monster")
or is_invisible(self, objs[n]:get_player_name())
or (self.specific_attack
and not check_for("player", self.specific_attack)) then
objs[n] = nil
--print("- pla", n)
end
-- or are we a mob?
elseif ent and ent._cmi_is_mob then
-- remove mobs not to attack
if self.name == ent.name
or (not self.attack_animals and ent.type == "animal")
or (not self.attack_monsters and ent.type == "monster")
or (not self.attack_npcs and ent.type == "npc")
or (self.specific_attack
and not check_for(ent.name, self.specific_attack)) then
objs[n] = nil
--print("- mob", n, self.name, ent.name)
end
-- remove all other entities
else
--print(" -obj", n)
objs[n] = nil
end
end
local p, sp, dist, min_player
local min_dist = self.view_range + 1
-- go through remaining entities and select closest
for _,player in pairs(objs) do
p = player:get_pos()
sp = s
dist = get_distance(p, s)
-- aim higher to make looking up hills more realistic
p.y = p.y + 1
sp.y = sp.y + 1
-- choose closest player to attack that isnt self
if dist ~= 0
and dist < min_dist
and self:line_of_sight(sp, p, 2) == true
and not is_peaceful_player(player) then
min_dist = dist
min_player = player
end
end
-- attack closest player or mob
if min_player and random(100) > self.attack_chance then
self:do_attack(min_player)
end
end
-- find someone to runaway from
function mob_class:do_runaway_from()
if not self.runaway_from then
return
end
local s = self.object:get_pos() ; if not s then return end
local p, sp, dist, pname
local player, obj, min_player, name
local min_dist = self.view_range + 1
local objs = minetest.get_objects_inside_radius(s, self.view_range)
for n = 1, #objs do
if objs[n]:is_player() then
pname = objs[n]:get_player_name()
if is_invisible(self, pname)
or self.owner == pname then
name = ""
else
player = objs[n]
name = "player"
end
else
obj = objs[n]:get_luaentity()
if obj then
player = obj.object
name = obj.name or ""
end
end
-- find specific mob to runaway from
if name ~= "" and name ~= self.name
and (self.runaway_from and check_for(name, self.runaway_from)) then
sp = s
p = player and player:get_pos() or s
-- aim higher to make looking up hills more realistic
p.y = p.y + 1
sp.y = sp.y + 1
dist = get_distance(p, s)
-- choose closest player/mob to runaway from
if dist < min_dist
and self:line_of_sight(sp, p, 2) == true then
min_dist = dist
min_player = player
end
end
end
if min_player then
yaw_to_pos(self, min_player:get_pos(), 3)
self.state = "runaway"
self.runaway_timer = 3
self.following = nil
end
end
-- follow player if owner or holding item, if fish outta water then flop
function mob_class:follow_flop()
-- find player to follow
if (self.follow ~= "" or self.order == "follow")
and not self.following
and self.state ~= "attack"
and self.state ~= "runaway" then
local s = self.object:get_pos() ; if not s then return end
local players = minetest.get_connected_players()
for n = 1, #players do
if get_distance(players[n]:get_pos(), s) < self.view_range
and not is_invisible(self, players[n]:get_player_name()) then
self.following = players[n]
break
end
end
end
if self.type == "npc"
and self.order == "follow"
and self.state ~= "attack"
and self.owner ~= "" then
-- npc stop following player if not owner
if self.following
and self.owner
and self.owner ~= self.following:get_player_name() then
self.following = nil
end
else
-- stop following player if not holding specific item or mob is horny
if self.following
and self.following:is_player()
and (self:follow_holding(self.following) == false
or self.horny) then
self.following = nil
end
end
-- follow that thing
if self.following then
local s = self.object:get_pos()
local p
if self.following:is_player() then
p = self.following:get_pos()
elseif self.following.object then
p = self.following.object:get_pos()
end
if p then
local dist = get_distance(p, s)
-- dont follow if out of range
if dist > self.view_range then
self.following = nil
else
yaw_to_pos(self, p)
-- anyone but standing npc's can move along
if dist > self.reach
and self.order ~= "stand" then
self:set_velocity(self.walk_velocity)
if self.walk_chance ~= 0 then
self:set_animation("walk")
end
else
self:set_velocity(0)
self:set_animation("stand")
end
return
end
end
end
-- swimmers flop when out of their element, and swim again when back in
if self.fly then
if not self:attempt_flight_correction() then
self.state = "flop"
-- do we have a custom on_flop function?
if self.on_flop then
if self:on_flop(self) then
return
end
end
self.object:set_velocity({x = 0, y = -5, z = 0})
self:set_animation("stand")
return
elseif self.state == "flop" then
self.state = "stand"
end
end
end
-- dogshoot attack switch and counter function
function mob_class:dogswitch(dtime)
-- switch mode not activated
if not self.dogshoot_switch
or not dtime then
return 0
end
self.dogshoot_count = self.dogshoot_count + dtime
if (self.dogshoot_switch == 1
and self.dogshoot_count > self.dogshoot_count_max)
or (self.dogshoot_switch == 2
and self.dogshoot_count > self.dogshoot_count2_max) then
self.dogshoot_count = 0
if self.dogshoot_switch == 1 then
self.dogshoot_switch = 2
else
self.dogshoot_switch = 1
end
end
return self.dogshoot_switch
end
-- execute current state (stand, walk, run, attacks)
function mob_class:do_states(dtime)
local yaw = self.object:get_yaw() ; if not yaw then return end
if self.state == "stand" then
if self.randomly_turn and random(4) == 1 then
local lp
local s = self.object:get_pos()
local objs = minetest.get_objects_inside_radius(s, 3)
for n = 1, #objs do
if objs[n]:is_player() then
lp = objs[n]:get_pos()
break
end
end
-- look at any players nearby, otherwise turn randomly
if lp then
yaw = yaw_to_pos(self, lp)
else
yaw = yaw + random(-0.5, 0.5)
end
yaw = self:set_yaw(yaw, 8)
end
self:set_velocity(0)
self:set_animation("stand")
-- mobs ordered to stand stay standing
if self.order ~= "stand"
and self.walk_chance ~= 0
and self.facing_fence ~= true
and random(100) <= self.walk_chance
and self.at_cliff == false then
self:set_velocity(self.walk_velocity)
self.state = "walk"
self:set_animation("walk")
end
elseif self.state == "walk" then
local s = self.object:get_pos()
local lp
-- is there something I need to avoid?
if self.water_damage > 0
and self.lava_damage > 0 then
lp = minetest.find_node_near(s, 1, {"group:water", "group:igniter"})
elseif self.water_damage > 0 then
lp = minetest.find_node_near(s, 1, {"group:water"})
elseif self.lava_damage > 0 then
lp = minetest.find_node_near(s, 1, {"group:igniter"})
end
if lp then
-- if mob in dangerous node then look for land
if not is_node_dangerous(self, self.standing_in) then
lp = minetest.find_nodes_in_area_under_air(
{s.x - 5, s.y - 1, s.z - 5},
{s.x + 5, s.y + 2, s.z + 5},
{"group:soil", "group:stone", "group:sand",
node_ice, node_snowblock})
-- select position of random block to climb onto
lp = #lp > 0 and lp[random(#lp)]
-- did we find land?
if lp then
yaw = yaw_to_pos(self, lp)
self:do_jump()
self:set_velocity(self.walk_velocity)
else
yaw = yaw + random(-0.5, 0.5)
end
end
yaw = self:set_yaw(yaw, 8)
-- otherwise randomly turn
elseif self.randomly_turn and random(100) <= 30 then
yaw = yaw + random(-0.5, 0.5)
yaw = self:set_yaw(yaw, 8)
-- for flying/swimming mobs randomly move up and down also
if self.fly_in
and not self.following then
self:attempt_flight_correction(true)
end
end
-- stand for great fall in front
if self.facing_fence == true
or self.at_cliff
or random(100) <= self.stand_chance then
-- don't stand if mob flies and keep_flying set
if (self.fly and not self.keep_flying)
or not self.fly then
self:set_velocity(0)
self.state = "stand"
self:set_animation("stand", true)
end
else
self:set_velocity(self.walk_velocity)
if self:flight_check()
and self.animation
and self.animation.fly_start
and self.animation.fly_end then
self:set_animation("fly")
else
self:set_animation("walk")
end
end
-- runaway when punched
elseif self.state == "runaway" then
self.runaway_timer = self.runaway_timer + 1
-- stop after 5 seconds or when at cliff
if self.runaway_timer > 5
or self.at_cliff
or self.order == "stand" then
self.runaway_timer = 0
self:set_velocity(0)
self.state = "stand"
self:set_animation("stand")
else
self:set_velocity(self.run_velocity)
self:set_animation("walk")
end
-- attack routines (explode, dogfight, shoot, dogshoot)
elseif self.state == "attack" then
-- get mob and enemy positions and distance between
local s = self.object:get_pos()
local p = self.attack and self.attack:get_pos()
local dist = p and get_distance(p, s) or 500
-- stop attacking if player out of range or invisible
if dist > self.view_range
or not self.attack
or not self.attack:get_pos()
or self.attack:get_hp() <= 0
or (self.attack:is_player()
and is_invisible(self, self.attack:get_player_name())) then
--print(" ** stop attacking **", dist, self.view_range)
self.state = "stand"
self:set_velocity(0)
self:set_animation("stand")
self.attack = nil
self.v_start = false
self.timer = 0
self.blinktimer = 0
self.path.way = nil
return
end
if self.attack_type == "explode" then
yaw = yaw_to_pos(self, p)
local node_break_radius = self.explosion_radius or 1
local entity_damage_radius = self.explosion_damage_radius
or (node_break_radius * 2)
-- look a little higher to fix raycast
s.y = s.y + 0.5 ; p.y = p.y + 0.5
-- start timer when in reach and line of sight
if not self.v_start
and dist <= self.reach
and self:line_of_sight(s, p, 2) then
self.v_start = true
self.timer = 0
self.blinktimer = 0
self:mob_sound(self.sounds.fuse)
--print("=== explosion timer started", self.explosion_timer)
-- stop timer if out of reach or direct line of sight
elseif self.allow_fuse_reset
and self.v_start
and (dist > self.reach or not self:line_of_sight(s, p, 2)) then
--print("=== explosion timer stopped")
self.v_start = false
self.timer = 0
self.blinktimer = 0
self.blinkstatus = false
self.object:set_texture_mod("")
end
-- walk right up to player unless the timer is active
if self.v_start and (self.stop_to_explode or dist < 1.5) then
self:set_velocity(0)
else
self:set_velocity(self.run_velocity)
end
if self.animation and self.animation.run_start then
self:set_animation("run")
else
self:set_animation("walk")
end
if self.v_start then
self.timer = self.timer + dtime
self.blinktimer = (self.blinktimer or 0) + dtime
if self.blinktimer > 0.2 then
self.blinktimer = 0
if self.blinkstatus then
self.object:set_texture_mod(self.texture_mods)
else
self.object:set_texture_mod(self.texture_mods
.. "^[brighten")
end
self.blinkstatus = not self.blinkstatus
end
--print("=== explosion timer", self.timer)
if self.timer > self.explosion_timer then
local pos = self.object:get_pos()
-- dont damage anything if area protected or next to water
if minetest.find_node_near(pos, 1, {"group:water"})
or minetest.is_protected(pos, "") then
node_break_radius = 1
end
remove_mob(self, true)
if minetest.get_modpath("tnt") and tnt and tnt.boom
and not minetest.is_protected(pos, "") then
tnt.boom(pos, {
radius = node_break_radius,
damage_radius = entity_damage_radius,
sound = self.sounds.explode
})
else
minetest.sound_play(self.sounds.explode, {
pos = pos,
gain = 1.0,
max_hear_distance = self.sounds.distance or 32
})
entity_physics(pos, entity_damage_radius)
effect(pos, 32, "tnt_smoke.png", nil, nil,
node_break_radius, 1, 0)
end
return true
end
end
elseif self.attack_type == "dogfight"
or (self.attack_type == "dogshoot" and self:dogswitch(dtime) == 2)
or (self.attack_type == "dogshoot" and dist <= self.reach
and self:dogswitch() == 0) then
if self.fly
and dist > self.reach then
local p1 = s
local me_y = floor(p1.y)
local p2 = p
local p_y = floor(p2.y + 1)
local v = self.object:get_velocity()
if self:flight_check() then
if me_y < p_y then
self.object:set_velocity({
x = v.x,
y = 1 * self.walk_velocity,
z = v.z
})
elseif me_y > p_y then
self.object:set_velocity({
x = v.x,
y = -1 * self.walk_velocity,
z = v.z
})
end
else
if me_y < p_y then
self.object:set_velocity({
x = v.x,
y = 0.01,
z = v.z
})
elseif me_y > p_y then
self.object:set_velocity({
x = v.x,
y = -0.01,
z = v.z
})
end
end
end
-- rnd: new movement direction
if self.path.following
and self.path.way
and self.attack_type ~= "dogshoot" then
-- no paths longer than 50
if #self.path.way > 50
or dist < self.reach then
self.path.following = false
return
end
local p1 = self.path.way[1]
if not p1 then
self.path.following = false
return
end
if abs(p1.x - s.x) + abs(p1.z - s.z) < 0.6 then
-- reached waypoint, remove it from queue
table_remove(self.path.way, 1)
end
-- set new temporary target
p = {x = p1.x, y = p1.y, z = p1.z}
end
yaw = yaw_to_pos(self, p)
-- move towards enemy if beyond mob reach
if dist > self.reach then
-- path finding by rnd
if self.pathfinding -- only if mob has pathfinding enabled
and enable_pathfinding then
self:smart_mobs(s, p, dist, dtime)
end
if self.at_cliff then
self:set_velocity(0)
self:set_animation("stand")
else
if self.path.stuck then
self:set_velocity(self.walk_velocity)
else
self:set_velocity(self.run_velocity)
end
if self.animation and self.animation.run_start then
self:set_animation("run")
else
self:set_animation("walk")
end
end
else -- rnd: if inside reach range
self.path.stuck = false
self.path.stuck_timer = 0
self.path.following = false -- not stuck anymore
self:set_velocity(0)
if self.timer > 1 then
-- no custom attack or custom attack returns true to continue
if not self.custom_attack
or self:custom_attack(self, p) == true then
self.timer = 0
self:set_animation("punch")
local p2 = p
local s2 = s
p2.y = p2.y + .5
s2.y = s2.y + .5
if self:line_of_sight(p2, s2) == true then
-- play attack sound
self:mob_sound(self.sounds.attack)
-- punch player (or what player is attached to)
local attached = self.attack:get_attach()
if attached then
self.attack = attached
end
self.attack:punch(self.object, 1.0, {
full_punch_interval = 1.0,
damage_groups = {fleshy = self.damage}
}, nil)
end
end
end
end
elseif self.attack_type == "shoot"
or (self.attack_type == "dogshoot" and self:dogswitch(dtime) == 1)
or (self.attack_type == "dogshoot" and dist > self.reach and
self:dogswitch() == 0) then
p.y = p.y - .5
s.y = s.y + .5
local vec = {x = p.x - s.x, y = p.y - s.y, z = p.z - s.z}
yaw = yaw_to_pos(self, p)
self:set_velocity(0)
if self.shoot_interval
and self.timer > self.shoot_interval
and random(100) <= 60 then
self.timer = 0
self:set_animation("shoot")
-- play shoot attack sound
self:mob_sound(self.sounds.shoot_attack)
local p = self.object:get_pos()
p.y = p.y + (self.collisionbox[2] + self.collisionbox[5]) / 2
if minetest.registered_entities[self.arrow] then
local obj = minetest.add_entity(p, self.arrow)
local ent = obj:get_luaentity()
local amount = (vec.x * vec.x + vec.y * vec.y + vec.z * vec.z) ^ 0.5
local v = ent.velocity or 1 -- or set to default
ent.switch = 1
ent.owner_id = tostring(self.object) -- add unique owner id to arrow
-- offset makes shoot aim accurate
vec.y = vec.y + self.shoot_offset
vec.x = vec.x * (v / amount)
vec.y = vec.y * (v / amount)
vec.z = vec.z * (v / amount)
obj:set_velocity(vec)
end
end
end
end
end
-- falling and fall damage
function mob_class:falling(pos)
if self.fly or self.disable_falling then
return
end
-- floating in water (or falling)
local v = self.object:get_velocity()
-- sanity check
if not v then return end
local fall_speed = self.fall_speed
-- in water then use liquid viscosity for float/sink speed
if self.floats == 1 and self.standing_in
and minetest.registered_nodes[self.standing_in].groups.liquid then
local visc = min(
minetest.registered_nodes[self.standing_in].liquid_viscosity, 7) + 1
self.object:set_velocity({x = v.x, y = 0.6, z = v.z})
fall_speed = -1.2 / visc
else
-- fall damage onto solid ground
if self.fall_damage == 1
and self.object:get_velocity().y == 0 then
local d = (self.old_y or 0) - self.object:get_pos().y
if d > 5 then
self.health = self.health - floor(d - 5)
effect(pos, 5, "tnt_smoke.png", 1, 2, 2, nil)
if self:check_for_death({type = "fall"}) then
return true
end
end
self.old_y = self.object:get_pos().y
end
end
-- fall at set speed
self.object:set_acceleration({
x = 0,
y = fall_speed,
z = 0
})
end
-- is Took Ranks mod active?
local tr = minetest.get_modpath("toolranks")
-- deal damage and effects when mob punched
function mob_class:on_punch(hitter, tflp, tool_capabilities, dir, damage)
--mob health check
if self.health <= 0 then
return true
end
-- custom punch function
if self.do_punch
and self:do_punch(hitter, tflp, tool_capabilities, dir) == false then
return true
end
-- error checking when mod profiling is enabled
if not tool_capabilities then
minetest.log("warning",
"[mobs] Mod profiling enabled, damage not enabled")
return true
end
-- is mob protected
if self.protected then
-- did player hit mob and if so is it in protected area
if hitter:is_player() then
local player_name = hitter:get_player_name()
if player_name ~= self.owner
and minetest.is_protected(self.object:get_pos(), player_name) then
minetest.chat_send_player(hitter:get_player_name(),
S("Mob has been protected!"))
return true
end
-- if protection is on level 2 then dont let arrows harm mobs
elseif self.protected == 2 then
local ent = hitter and hitter:get_luaentity()
if ent and ent._is_arrow then
return true -- arrow entity
elseif not ent then
return true -- non entity
end
end
end
local weapon = hitter:get_wielded_item()
local weapon_def = weapon:get_definition() or {}
local punch_interval = 1.4
-- calculate mob damage
local damage = 0
local armor = self.object:get_armor_groups() or {}
local tmp
-- quick error check incase it ends up 0 (serialize.h check test)
if tflp == 0 then
tflp = 0.2
end
if use_cmi then
damage = cmi.calculate_damage(self.object, hitter, tflp, tool_capabilities, dir)
else
for group,_ in pairs( (tool_capabilities.damage_groups or {}) ) do
tmp = tflp / (tool_capabilities.full_punch_interval or 1.4)
if tmp < 0 then
tmp = 0.0
elseif tmp > 1 then
tmp = 1.0
end
damage = damage + (tool_capabilities.damage_groups[group] or 0)
* tmp * ((armor[group] or 0) / 100.0)
end
end
-- check for tool immunity or special damage
for n = 1, #self.immune_to do
if self.immune_to[n][1] == weapon_def.name then
damage = self.immune_to[n][2] or 0
break
-- if "all" then no tools deal damage unless it's specified in list
elseif self.immune_to[n][1] == "all" then
damage = self.immune_to[n][2] or 0
end
end
--print("Mob Damage is", damage)
-- healing
if damage <= -1 then
self.health = self.health - floor(damage)
return true
end
if use_cmi
and cmi.notify_punch(
self.object, hitter, tflp, tool_capabilities, dir, damage) then
return true
end
-- add weapon wear
--punch_interval = tool_capabilities.full_punch_interval or 1.4
-- toolrank support
local wear = floor((punch_interval / 75) * 9000)
if mobs.is_creative(hitter:get_player_name()) then
if tr then
wear = 1
else
wear = 0
end
end
if tr then
if weapon_def.original_description then
toolranks.new_afteruse(weapon, hitter, nil, {wear = wear})
end
else
weapon:add_wear(wear)
end
--hitter:set_wielded_item(weapon)
-- only play hit sound and show blood effects if damage is 1 or over
if damage >= 1 then
-- weapon sounds
if weapon_def.sounds then
local s = random(0, #weapon_def.sounds)
minetest.sound_play(weapon_def.sounds[s], {
object = self.object,
max_hear_distance = 8
}, true)
else
minetest.sound_play("default_punch", {
object = self.object,
max_hear_distance = 5
}, true)
end
-- blood_particles
if not disable_blood and self.blood_amount > 0 then
local pos = self.object:get_pos()
local blood = self.blood_texture
local amount = self.blood_amount
pos.y = pos.y + (-self.collisionbox[2]
+ self.collisionbox[5]) * .5
-- lots of damage = more blood :)
if damage > 10 then
amount = self.blood_amount * 2
end
-- do we have a single blood texture or multiple?
if type(self.blood_texture) == "table" then
blood = self.blood_texture[random(#self.blood_texture)]
end
effect(pos, amount, blood, 1, 2, 1.75, nil, nil, true)
end
-- do damage
if self.name == "mobs:dog" or self.name == "mobs:cat" or self.name == "mobs:sheep" or self.name == "mobs:dragon" or self.name == "mobs:knight_1248" or self.name == "mobs:fox" or self.name == "mobs:tortoise" then
else
self.health = self.health - floor(damage)
end
-- exit here if dead, check for tools with fire damage
local hot = tool_capabilities and tool_capabilities.damage_groups
and tool_capabilities.damage_groups.fire
if self:check_for_death({type = "punch",
puncher = hitter, hot = hot}) then
return true
end
--[[ add healthy afterglow when hit (causes lag with large textures)
minetest.after(0.1, function()
if not self.object:get_luaentity() then return end
self.object:set_texture_mod("^[colorize:#c9900070")
minetest.after(0.3, function()
if not self.object:get_luaentity() then return end
self.object:set_texture_mod(self.texture_mods)
end)
end) ]]
end -- END if damage
-- knock back effect (only on full punch)
if self.knock_back
and tflp >= punch_interval then
local v = self.object:get_velocity()
-- sanity check
if not v then return true end
local kb = damage or 1
local up = 2
-- if already in air then dont go up anymore when hit
if v.y > 0
or self.fly then
up = 0
end
-- direction error check
dir = dir or {x = 0, y = 0, z = 0}
-- use tool knockback value or default
kb = tool_capabilities.damage_groups["knockback"] or kb
self.object:set_velocity({
x = dir.x * kb,
y = up,
z = dir.z * kb
})
self.pause_timer = 0.25
end
-- if skittish then run away
if self.runaway == true
and self.order ~= "stand" then
local lp = hitter:get_pos()
local yaw = yaw_to_pos(self, lp, 3)
self.state = "runaway"
self.runaway_timer = 0
self.following = nil
end
local name = hitter:get_player_name() or ""
-- attack puncher and call other mobs for help
if self.passive == false
and self.state ~= "flop"
and self.child == false
and self.attack_players == true
and hitter:get_player_name() ~= self.owner
and not is_invisible(self, name)
and self.object ~= hitter then
-- attack whoever punched mob
self.state = ""
self:do_attack(hitter)
-- alert others to the attack
local objs = minetest.get_objects_inside_radius(
hitter:get_pos(), self.view_range)
local obj
for n = 1, #objs do
obj = objs[n]:get_luaentity()
if obj and obj._cmi_is_mob then
-- only alert members of same mob and assigned helper
if obj.group_attack == true
and obj.state ~= "attack"
and obj.owner ~= name
and (obj.name == self.name
or obj.name == self.group_helper) then
obj:do_attack(hitter)
end
-- have owned mobs attack player threat
if obj.owner == name and obj.owner_loyal then
obj:do_attack(self.object)
end
end
end
end
end
-- get entity staticdata
function mob_class:mob_staticdata()
-- this handles mob count for mobs activated, unloaded, reloaded
if active_limit > 0 and self.active_toggle then
active_mobs = active_mobs + self.active_toggle
self.active_toggle = -self.active_toggle
--print("-- staticdata", active_mobs, active_limit, self.active_toggle)
end
-- remove mob when out of range unless tamed
if remove_far
and self.remove_ok
and self.type ~= "npc"
and self.state ~= "attack"
and not self.tamed
and self.lifetimer < 20000 then
--print("REMOVED " .. self.name)
remove_mob(self, true)
return minetest.serialize({remove_ok = true, static_save = true})
end
self.remove_ok = true
self.attack = nil
self.following = nil
self.state = "stand"
-- used to rotate older mobs
if self.drawtype and self.drawtype == "side" then
self.rotate = rad(90)
end
if use_cmi then
self.serialized_cmi_components = cmi.serialize_components(
self._cmi_components)
end
local tmp, t = {}
for _,stat in pairs(self) do
t = type(stat)
if t ~= "function"
and t ~= "nil"
and t ~= "userdata"
and _ ~= "object"
and _ ~= "_cmi_components" then
tmp[_] = self[_]
end
end
--print('===== '..self.name..'\n'.. dump(tmp)..'\n=====\n')
return minetest.serialize(tmp)
end
-- activate mob and reload settings
function mob_class:mob_activate(staticdata, def, dtime)
-- if dtime == 0 then entity has just been created
-- anything higher means it is respawning (thanks SorceryKid)
if dtime == 0 and active_limit > 0 then
self.active_toggle = 1
end
-- remove mob if not tamed and mob total reached
if active_limit > 0 and active_mobs >= active_limit and not self.tamed then
remove_mob(self)
--print("-- mob limit reached, removing " .. self.name)
return
end
-- remove monsters in peaceful mode
if self.type == "monster" and peaceful_only then
remove_mob(self, true)
return
end
-- load entity variables
local tmp = minetest.deserialize(staticdata)
if tmp then
local t
for _,stat in pairs(tmp) do
t = type(stat)
if t ~= "function"
and t ~= "nil"
and t ~= "userdata" then
self[_] = stat
end
end
end
-- force current model into mob
self.mesh = def.mesh
self.base_mesh = def.mesh
self.collisionbox = def.collisionbox
self.selectionbox = def.selectionbox
-- select random texture, set model and size
if not self.base_texture then
-- compatiblity with old simple mobs textures
if def.textures and type(def.textures[1]) == "string" then
def.textures = {def.textures}
end
self.base_texture = def.textures and def.textures[random(#def.textures)]
self.base_mesh = def.mesh
self.base_size = self.visual_size
self.base_colbox = self.collisionbox
self.base_selbox = self.selectionbox
end
-- for current mobs that dont have this set
if not self.base_selbox then
self.base_selbox = self.selectionbox or self.base_colbox
end
-- set texture, model and size
local textures = self.base_texture
local mesh = self.base_mesh
local vis_size = self.base_size
local colbox = self.base_colbox
local selbox = self.base_selbox
-- specific texture if gotten
if self.gotten == true and def.gotten_texture then
textures = def.gotten_texture
end
-- specific mesh if gotten
if self.gotten == true and def.gotten_mesh then
mesh = def.gotten_mesh
end
-- set child objects to half size
if self.child == true then
vis_size = {x = self.base_size.x * .5, y = self.base_size.y * .5}
if def.child_texture then
textures = def.child_texture[1]
end
colbox = {
self.base_colbox[1] * .5, self.base_colbox[2] * .5,
self.base_colbox[3] * .5, self.base_colbox[4] * .5,
self.base_colbox[5] * .5, self.base_colbox[6] * .5}
selbox = {
self.base_selbox[1] * .5, self.base_selbox[2] * .5,
self.base_selbox[3] * .5, self.base_selbox[4] * .5,
self.base_selbox[5] * .5, self.base_selbox[6] * .5}
end
if self.health == 0 then
self.health = random(self.hp_min, self.hp_max)
end
-- pathfinding init
self.path = {}
self.path.way = {} -- path to follow, table of positions
self.path.lastpos = {x = 0, y = 0, z = 0}
self.path.stuck = false
self.path.following = false -- currently following path?
self.path.stuck_timer = 0 -- if stuck for too long search for path
-- Armor groups (immortal = 1 for custom damage handling)
local armor
if type(self.armor) == "table" then
armor = table_copy(self.armor)
armor.immortal = 1
else
armor = {immortal = 1, fleshy = self.armor}
--armor = {fleshy = self.armor}
end
self.object:set_armor_groups(armor)
-- mob defaults
self.old_y = self.object:get_pos().y
self.old_health = self.health
self.sounds.distance = self.sounds.distance or 10
self.textures = textures
self.mesh = mesh
self.collisionbox = colbox
self.selectionbox = selbox
self.visual_size = vis_size
self.standing_in = "air"
self.standing_on = "air"
-- check existing nametag
if not self.nametag then
self.nametag = def.nametag
end
-- set anything changed above
self.object:set_properties(self)
first_activate(self)
self:set_yaw((random(0, 360) - 180) / 180 * pi, 6)
self:update_tag()
self:set_animation("stand")
-- apply any texture mods
self.object:set_texture_mod(self.texture_mods)
-- set 5.x flag to remove monsters when map area unloaded
if remove_far and self.type == "monster" then
self.static_save = false
end
-- run on_spawn function if found
if self.on_spawn and not self.on_spawn_run then
if self.on_spawn(self) then
self.on_spawn_run = true -- if true, set flag to run once only
end
end
-- run after_activate
if def.after_activate then
def.after_activate(self, staticdata, def, dtime)
end
if use_cmi then
self._cmi_components = cmi.activate_components(
self.serialized_cmi_components)
cmi.notify_activate(self.object, dtime)
end
end
-- handle mob lifetimer and expiration
function mob_class:mob_expire(pos, dtime)
-- when lifetimer expires remove mob (except npc and tamed)
if self.type ~= "npc"
and not self.tamed
and self.state ~= "attack"
and remove_far ~= true
and self.lifetimer < 20000 then
self.lifetimer = self.lifetimer - dtime
if self.lifetimer <= 0 then
-- only despawn away from player
local objs = minetest.get_objects_inside_radius(pos, 15)
for n = 1, #objs do
if objs[n]:is_player() then
self.lifetimer = 20
return
end
end
-- minetest.log("action",
-- S("lifetimer expired, removed @1", self.name))
effect(pos, 15, "tnt_smoke.png", 2, 4, 2, 0)
remove_mob(self, true)
return
end
end
end
-- main mob function
function mob_class:on_step(dtime, moveresult)
first_step(self,dtime)
--[[ moveresult contains this for physical mobs
{
touching_ground = boolean,
collides = boolean,
standing_on_object = boolean,
collisions = {
{
type = string, -- "node" or "object",
axis = string, -- "x", "y" or "z"
node_pos = vector, -- if type is "node"
object = ObjectRef, -- if type is "object"
old_velocity = vector,
new_velocity = vector,
}}
}]]
if self.state == "die" then return end ----------------
if use_cmi then
cmi.notify_step(self.object, dtime)
end
local pos = self.object:get_pos()
local yaw = self.object:get_yaw()
-- early warning check, if no yaw then no entity, skip rest of function
if not yaw then return end
-- get node at foot level every quarter second
self.node_timer = (self.node_timer or 0) + dtime
if self.node_timer > 0.25 then
self.node_timer = 0
local y_level = self.collisionbox[2]
if self.child then
y_level = self.collisionbox[2] * 0.5
end
-- what is mob standing in?
self.standing_in = node_ok({
x = pos.x, y = pos.y + y_level + 0.25, z = pos.z}, "air").name
self.standing_on = node_ok({
x = pos.x, y = pos.y + y_level - 0.25, z = pos.z}, "air").name
--print("standing in " .. self.standing_in)
-- if standing inside solid block then jump to escape
if minetest.registered_nodes[self.standing_in].walkable
and minetest.registered_nodes[self.standing_in].drawtype
== "normal" then
self.object:set_velocity({
x = 0,
y = self.jump_height,
z = 0
})
end
-- check and stop if standing at cliff and fear of heights
self.at_cliff = self:is_at_cliff()
if self.at_cliff then
self:set_velocity(0)
end
-- has mob expired (0.25 instead of dtime since were in a timer)
self:mob_expire(pos, 0.25)
end
-- check if falling, flying, floating and return if player died
if self:falling(pos) then
return
end
-- smooth rotation by ThomasMonroe314
if self.delay and self.delay > 0 then
if self.delay == 1 then
yaw = self.target_yaw
else
local dif = abs(yaw - self.target_yaw)
if yaw > self.target_yaw then
if dif > pi then
dif = 2 * pi - dif -- need to add
yaw = yaw + dif / self.delay
else
yaw = yaw - dif / self.delay -- need to subtract
end
elseif yaw < self.target_yaw then
if dif > pi then
dif = 2 * pi - dif
yaw = yaw - dif / self.delay -- need to subtract
else
yaw = yaw + dif / self.delay -- need to add
end
end
if yaw > (pi * 2) then yaw = yaw - (pi * 2) end
if yaw < 0 then yaw = yaw + (pi * 2) end
end
self.delay = self.delay - 1
self.object:set_yaw(yaw)
end
-- knockback timer
if self.pause_timer > 0 then
self.pause_timer = self.pause_timer - dtime
return
end
-- run custom function (defined in mob lua file)
if self.do_custom then
-- when false skip going any further
if self:do_custom(dtime) == false then
return
end
end
-- attack timer
self.timer = self.timer + dtime
if self.state ~= "attack" then
if self.timer < 1 then
return
end
self.timer = 0
end
-- never go over 100
if self.timer > 100 then
self.timer = 1
end
-- mob plays random sound at times
if random(100) == 1 then
self:mob_sound(self.sounds.random)
end
-- environmental damage timer (every 1 second)
self.env_damage_timer = self.env_damage_timer + dtime
if (self.state == "attack" and self.env_damage_timer > 1)
or self.state ~= "attack" then
self.env_damage_timer = 0
-- check for environmental damage (water, fire, lava etc.)
if self:do_env_damage() then return end
-- node replace check (cow eats grass etc.)
self:replace(pos)
end
self:general_attack()
self:breed()
self:follow_flop()
if self:do_states(dtime) then return end
self:do_jump()
self:do_runaway_from(self)
self:do_stay_near()
end
-- default function when mobs are blown up with TNT
function mob_class:on_blast(damage)
--print("-- blast damage", damage)
self.object:punch(self.object, 1.0, {
full_punch_interval = 1.0,
damage_groups = {fleshy = damage},
}, nil)
-- return no damage, no knockback, no item drops, mob api handles all
return false, false, {}
end
mobs.spawning_mobs = {}
-- register mob entity
function mobs:register_mob(name, def)
mobs.spawning_mobs[name] = {}
minetest.register_entity(name, setmetatable({
stepheight = def.stepheight,
name = name,
type = def.type,
attack_type = def.attack_type,
fly = def.fly,
fly_in = def.fly_in,
keep_flying = def.keep_flying,
owner = def.owner,
order = def.order,
on_die = def.on_die,
on_flop = def.on_flop,
do_custom = def.do_custom,
jump_height = def.jump_height,
drawtype = def.drawtype, -- DEPRECATED, use rotate instead
rotate = rad(def.rotate or 0), -- 0=front 90=side 180=back 270=side2
glow = def.glow,
lifetimer = def.lifetimer,
hp_min = max(1, (def.hp_min or 5) * difficulty),
hp_max = max(1, (def.hp_max or 10) * difficulty),
collisionbox = def.collisionbox,
selectionbox = def.selectionbox or def.collisionbox,
visual = def.visual,
visual_size = def.visual_size,
mesh = def.mesh,
makes_footstep_sound = def.makes_footstep_sound,
view_range = def.view_range,
walk_velocity = def.walk_velocity,
run_velocity = def.run_velocity,
damage = max(0, (def.damage or 0) * difficulty),
light_damage = def.light_damage,
light_damage_min = def.light_damage_min,
light_damage_max = def.light_damage_max,
water_damage = def.water_damage,
lava_damage = def.lava_damage,
fire_damage = def.fire_damage,
air_damage = def.air_damage,
suffocation = def.suffocation,
fall_damage = def.fall_damage,
fall_speed = def.fall_speed,
drops = def.drops,
armor = def.armor,
on_rightclick = def.on_rightclick,
arrow = def.arrow,
shoot_interval = def.shoot_interval,
sounds = def.sounds,
animation = def.animation,
follow = def.follow,
jump = def.jump,
walk_chance = def.walk_chance,
stand_chance = def.stand_chance,
attack_chance = def.attack_chance,
passive = def.passive,
knock_back = def.knock_back,
blood_amount = def.blood_amount,
blood_texture = def.blood_texture,
shoot_offset = def.shoot_offset,
floats = def.floats,
replace_rate = def.replace_rate,
replace_what = def.replace_what,
replace_with = def.replace_with,
replace_offset = def.replace_offset,
on_replace = def.on_replace,
reach = def.reach,
texture_list = def.textures,
texture_mods = def.texture_mods or "",
child_texture = def.child_texture,
docile_by_day = def.docile_by_day,
fear_height = def.fear_height,
runaway = def.runaway,
pathfinding = def.pathfinding,
immune_to = def.immune_to,
explosion_radius = def.explosion_radius,
explosion_damage_radius = def.explosion_damage_radius,
explosion_timer = def.explosion_timer,
allow_fuse_reset = def.allow_fuse_reset,
stop_to_explode = def.stop_to_explode,
custom_attack = def.custom_attack,
double_melee_attack = def.double_melee_attack,
dogshoot_switch = def.dogshoot_switch,
dogshoot_count_max = def.dogshoot_count_max,
dogshoot_count2_max = def.dogshoot_count2_max or def.dogshoot_count_max,
group_attack = def.group_attack,
group_helper = def.group_helper,
attack_monsters = def.attacks_monsters or def.attack_monsters,
attack_animals = def.attack_animals,
attack_players = def.attack_players,
attack_npcs = def.attack_npcs,
specific_attack = def.specific_attack,
runaway_from = def.runaway_from,
owner_loyal = def.owner_loyal,
pushable = def.pushable,
stay_near = def.stay_near,
randomly_turn = def.randomly_turn ~= false,
ignore_invisibility = def.ignore_invisibility,
metadata = def.metadata,
metadata2 = def.metadata2,
on_spawn = def.on_spawn,
on_blast = def.on_blast, -- class redifinition
do_punch = def.do_punch,
on_breed = def.on_breed,
on_grown = def.on_grown,
on_rightclick = function(self, clicker)
update(self, clicker)
end,
on_receive_fields = function(self, fields, sender)
receive_fields(self, fields, sender)
end,
on_activate = function(self, staticdata, dtime)
return self:mob_activate(staticdata, def, dtime)
end,
get_staticdata = function(self)
return self:mob_staticdata(self)
end,
}, mob_class_meta))
end -- END mobs:register_mob function
-- count how many mobs of one type are inside an area
-- will also return true for second value if player is inside area
local count_mobs = function(pos, type)
local total = 0
local objs = minetest.get_objects_inside_radius(pos, aoc_range * 2)
local ent
local players
for n = 1, #objs do
if not objs[n]:is_player() then
ent = objs[n]:get_luaentity()
-- count mob type and add to total also
if ent and ent.name and ent.name == type then
total = total + 1
end
else
players = true
end
end
return total, players
end
-- do we have enough space to spawn mob? (thanks wuzzy)
local can_spawn = function(pos, name)
local ent = minetest.registered_entities[name]
local width_x = max(1, ceil(ent.collisionbox[4] - ent.collisionbox[1]))
local min_x, max_x
if width_x % 2 == 0 then
max_x = floor(width_x / 2)
min_x = -(max_x - 1)
else
max_x = floor(width_x / 2)
min_x = -max_x
end
local width_z = max(1, ceil(ent.collisionbox[6] - ent.collisionbox[3]))
local min_z, max_z
if width_z % 2 == 0 then
max_z = floor(width_z / 2)
min_z = -(max_z - 1)
else
max_z = floor(width_z / 2)
min_z = -max_z
end
local max_y = max(0, ceil(ent.collisionbox[5] - ent.collisionbox[2]) - 1)
local pos2
for y = 0, max_y do
for x = min_x, max_x do
for z = min_z, max_z do
pos2 = {x = pos.x + x, y = pos.y + y, z = pos.z + z}
if minetest.registered_nodes[node_ok(pos2).name].walkable == true then
return nil
end
end
end
end
-- tweak X/Z spawn pos
if width_x % 2 == 0 then
pos.x = pos.x + 0.5
end
if width_z % 2 == 0 then
pos.z = pos.z + 0.5
end
return pos
end
function mobs:can_spawn(pos, name)
return can_spawn(pos, name)
end
-- global functions
function mobs:add_mob(pos, def)
-- is mob actually registered?
if not mobs.spawning_mobs[def.name]
or not minetest.registered_entities[def.name] then
--print("--- mob doesn't exist", def.name)
return
end
-- are we over active mob limit
if active_limit > 0 and active_mobs >= active_limit then
--print("--- active mob limit reached", active_mobs, active_limit)
return
end
-- get total number of this mob in area
local num_mob, is_pla = count_mobs(pos, def.name)
if not is_pla then
--print("--- no players within active area, will not spawn " .. def.name)
return
end
local aoc = mobs.spawning_mobs[def.name]
and mobs.spawning_mobs[def.name].aoc or 1
if def.ignore_count ~= true and num_mob >= aoc then
--print("--- too many " .. def.name .. " in area", num_mob .. "/" .. aoc)
return
end
local mob = minetest.add_entity(pos, def.name)
--print("[mobs] Spawned " .. def.name .. " at " .. minetest.pos_to_string(pos))
local ent = mob:get_luaentity()
if not ent then
--print("[mobs] entity not found " .. def.name)
return false
end
if def.child then
local textures = ent.base_texture
-- using specific child texture (if found)
if ent.child_texture then
textures = ent.child_texture[1]
end
-- and resize to half height
mob:set_properties({
textures = textures,
visual_size = {
x = ent.base_size.x * .5,
y = ent.base_size.y * .5
},
collisionbox = {
ent.base_colbox[1] * .5,
ent.base_colbox[2] * .5,
ent.base_colbox[3] * .5,
ent.base_colbox[4] * .5,
ent.base_colbox[5] * .5,
ent.base_colbox[6] * .5
},
selectionbox = {
ent.base_selbox[1] * .5,
ent.base_selbox[2] * .5,
ent.base_selbox[3] * .5,
ent.base_selbox[4] * .5,
ent.base_selbox[5] * .5,
ent.base_selbox[6] * .5
},
})
ent.child = true
end
if def.owner then
ent.tamed = true
ent.owner = def.owner
end
if def.nametag then
-- limit name entered to 64 characters long
if def.nametag:len() > 64 then
def.nametag = def.nametag:sub(1, 64)
end
ent.nametag = def.nametag
ent:update_tag()
end
return ent
end
function mobs:spawn_abm_check(pos, node, name)
-- global function to add additional spawn checks
-- return true to stop spawning mob
end
function mobs:spawn_specific(name, nodes, neighbors, min_light, max_light, interval,
chance, aoc, min_height, max_height, day_toggle, on_spawn, map_load)
-- Do mobs spawn at all?
if not mobs_spawn or not mobs.spawning_mobs[name] then
--print ("--- spawning not registered for " .. name)
return
end
-- chance/spawn number override in minetest.conf for registered mob
local numbers = settings:get(name)
if numbers then
numbers = numbers:split(",")
chance = tonumber(numbers[1]) or chance
aoc = tonumber(numbers[2]) or aoc
if chance == 0 then
minetest.log("warning",
string.format("[mobs] %s has spawning disabled", name))
return
end
minetest.log("action", string.format(
"[mobs] Chance setting for %s changed to %s (total: %s)",
name, chance, aoc))
end
mobs.spawning_mobs[name].aoc = aoc
local spawn_action = function(pos, node, active_object_count,
active_object_count_wider)
-- use instead of abm's chance setting when using lbm
if map_load and random(max(1, (chance * mob_chance_multiplier))) > 1 then
return
end
-- use instead of abm's neighbor setting when using lbm
if map_load and not minetest.find_node_near(pos, 1, neighbors) then
--print("--- lbm neighbors not found")
return
end
-- is mob actually registered?
if not mobs.spawning_mobs[name]
or not minetest.registered_entities[name] then
--print("--- mob doesn't exist", name)
return
end
-- are we over active mob limit
if active_limit > 0 and active_mobs >= active_limit then
--print("--- active mob limit reached", active_mobs, active_limit)
return
end
-- additional custom checks for spawning mob
if mobs:spawn_abm_check(pos, node, name) == true then
return
end
-- do not spawn if too many entities in area
if active_object_count_wider
and active_object_count_wider >= max_per_block then
--print("--- too many entities in area", active_object_count_wider)
return
end
-- get total number of this mob in area
local num_mob, is_pla = count_mobs(pos, name)
if not is_pla then
--print("--- no players within active area, will not spawn " .. name)
return
end
if num_mob >= aoc then
--print("--- too many " .. name .. " in area", num_mob .. "/" .. aoc)
return
end
-- if toggle set to nil then ignore day/night check
if day_toggle ~= nil then
local tod = (minetest.get_timeofday() or 0) * 24000
if tod > 4500 and tod < 19500 then
-- daylight, but mob wants night
if day_toggle == false then
--print("--- mob needs night", name)
return
end
else
-- night time but mob wants day
if day_toggle == true then
--print("--- mob needs day", name)
return
end
end
end
-- spawn above node
pos.y = pos.y + 1
-- are we spawning within height limits?
if pos.y > max_height
or pos.y < min_height then
--print("--- height limits not met", name, pos.y)
return
end
-- are light levels ok?
local light = minetest.get_node_light(pos)
if not light
or light > max_light
or light < min_light then
--print("--- light limits not met", name, light)
return
end
-- mobs cannot spawn in protected areas when enabled
if not spawn_protected
and minetest.is_protected(pos, "") then
--print("--- inside protected area", name)
return
end
-- only spawn a set distance away from player
local objs = minetest.get_objects_inside_radius(pos, mob_nospawn_range)
for n = 1, #objs do
if objs[n]:is_player() then
--print("--- player too close", name)
return
end
end
local ent = minetest.registered_entities[name]
-- should we check mob area for obstructions ?
if mob_area_spawn ~= true then
-- do we have enough height clearance to spawn mob?
local height = max(0, ent.collisionbox[5] - ent.collisionbox[2])
for n = 0, floor(height) do
local pos2 = {x = pos.x, y = pos.y + n, z = pos.z}
if minetest.registered_nodes[node_ok(pos2).name].walkable == true then
--print ("--- inside block", name, node_ok(pos2).name)
return
end
end
else
-- returns position if we have enough space to spawn mob
pos = can_spawn(pos, name)
end
if pos then
-- adjust for mob collision box
pos.y = pos.y + (ent.collisionbox[2] * -1) - 0.4
local mob = minetest.add_entity(pos, name)
-- print("[mobs] Spawned " .. name .. " at "
-- .. minetest.pos_to_string(pos) .. " on "
-- .. node.name .. " near " .. neighbors[1])
if on_spawn then
on_spawn(mob:get_luaentity(), pos)
end
else
--print("--- not enough space to spawn", name)
end
end
-- are we registering an abm or lbm?
if map_load == true then
minetest.register_lbm({
name = name .. "_spawning",
label = name .. " spawning",
nodenames = nodes,
run_at_every_load = false,
action = function(pos, node)
spawn_action(pos, node)
end
})
else
minetest.register_abm({
label = name .. " spawning",
nodenames = nodes,
neighbors = neighbors,
interval = interval,
chance = max(1, (chance * mob_chance_multiplier)),
catch_up = false,
action = function(pos, node, active_object_count, active_object_count_wider)
spawn_action(pos, node, active_object_count, active_object_count_wider)
end
})
end
end
-- compatibility with older mob registration
function mobs:register_spawn(name, nodes, max_light, min_light, chance,
active_object_count, max_height, day_toggle)
mobs:spawn_specific(name, nodes, {"air"}, min_light, max_light, 30,
chance, active_object_count, -31000, max_height, day_toggle)
end
-- MarkBu's spawn function (USE this one please)
function mobs:spawn(def)
mobs:spawn_specific(
def.name,
def.nodes or {"group:soil", "group:stone"},
def.neighbors or {"air"},
def.min_light or 0,
def.max_light or 15,
def.interval or 30,
def.chance or 5000,
def.active_object_count or 1,
def.min_height or -31000,
def.max_height or 31000,
def.day_toggle,
def.on_spawn,
def.on_map_load)
end
-- register arrow for shoot attack
function mobs:register_arrow(name, def)
if not name or not def then return end -- errorcheck
minetest.register_entity(name, {
physical = false,
visual = def.visual,
visual_size = def.visual_size,
textures = def.textures,
velocity = def.velocity,
hit_player = def.hit_player,
hit_node = def.hit_node,
hit_mob = def.hit_mob,
hit_object = def.hit_object,
drop = def.drop or false, -- drops arrow as registered item when true
collisionbox = def.collisionbox or {-.1, -.1, -.1, .1, .1, .1},
timer = 0,
lifetime = def.lifetime or 4.5,
switch = 0,
owner_id = def.owner_id,
rotate = def.rotate,
automatic_face_movement_dir = def.rotate
and (def.rotate - (pi / 180)) or false,
on_activate = def.on_activate,
on_punch = def.on_punch or function(
self, hitter, tflp, tool_capabilities, dir)
end,
on_step = def.on_step or function(self, dtime)
self.timer = self.timer + dtime
local pos = self.object:get_pos()
if self.switch == 0 or self.timer > self.lifetime then
self.object:remove() ; -- print("removed arrow")
return
end
-- does arrow have a tail (fireball)
if def.tail and def.tail == 1 and def.tail_texture then
minetest.add_particle({
pos = pos,
velocity = {x = 0, y = 0, z = 0},
acceleration = {x = 0, y = 0, z = 0},
expirationtime = def.expire or 0.25,
collisiondetection = false,
texture = def.tail_texture,
size = def.tail_size or 5,
glow = def.glow or 0
})
end
if self.hit_node then
local node = node_ok(pos).name
if minetest.registered_nodes[node].walkable then
self:hit_node(pos, node)
if self.drop == true then
pos.y = pos.y + 1
self.lastpos = (self.lastpos or pos)
minetest.add_item(self.lastpos,
self.object:get_luaentity().name)
end
self.object:remove() ; -- print("hit node")
return
end
end
if self.hit_player or self.hit_mob or self.hit_object then
for _,player in pairs(
minetest.get_objects_inside_radius(pos, 1.0)) do
if self.hit_player and player:is_player() then
self:hit_player(player)
self.object:remove() ; -- print("hit player")
return
end
local entity = player:get_luaentity()
if entity
and self.hit_mob
and entity._cmi_is_mob == true
and tostring(player) ~= self.owner_id
and entity.name ~= self.object:get_luaentity().name then
self:hit_mob(player)
self.object:remove() ; --print("hit mob")
return
end
if entity
and self.hit_object
and (not entity._cmi_is_mob)
and tostring(player) ~= self.owner_id
and entity.name ~= self.object:get_luaentity().name then
self:hit_object(player)
self.object:remove() ; -- print("hit object")
return
end
end
end
self.lastpos = pos
end
})
end
-- compatibility function
function mobs:explosion(pos, radius)
mobs:boom({sounds = {explode = "tnt_explode"}}, pos, radius)
end
-- no damage to nodes explosion
function mobs:safe_boom(self, pos, radius)
minetest.sound_play(self.sounds and self.sounds.explode or "tnt_explode", {
pos = pos,
gain = 1.0,
max_hear_distance = self.sounds and self.sounds.distance or 32
}, true)
entity_physics(pos, radius)
effect(pos, 32, "tnt_smoke.png", radius * 3, radius * 5, radius, 1, 0)
end
-- make explosion with protection and tnt mod check
function mobs:boom(self, pos, radius)
if mobs_griefing
and minetest.get_modpath("tnt") and tnt and tnt.boom
and not minetest.is_protected(pos, "") then
tnt.boom(pos, {
radius = radius,
damage_radius = radius,
sound = self.sounds and self.sounds.explode,
explode_center = true,
})
else
mobs:safe_boom(self, pos, radius)
end
end
-- Register spawn eggs
-- Note: This also introduces the “spawn_egg” group:
-- * spawn_egg=1: Spawn egg (generic mob, no metadata)
-- * spawn_egg=2: Spawn egg (captured/tamed mob, metadata)
function mobs:register_egg(mob, desc, background, addegg, no_creative)
local grp = {spawn_egg = 1}
-- do NOT add this egg to creative inventory (e.g. dungeon master)
if no_creative == true then
grp.not_in_creative_inventory = 1
end
local invimg = background
if addegg == 1 then
invimg = "mobs_chicken_egg.png^(" .. invimg ..
"^[mask:mobs_chicken_egg_overlay.png)"
end
-- register new spawn egg containing mob information
minetest.register_craftitem(mob .. "_set", {
description = S("@1 (Tamed)", desc),
inventory_image = invimg,
groups = {spawn_egg = 2, not_in_creative_inventory = 1},
stack_max = 1,
on_place = function(itemstack, placer, pointed_thing)
local pos = pointed_thing.above
-- does existing on_rightclick function exist?
local under = minetest.get_node(pointed_thing.under)
local def = minetest.registered_nodes[under.name]
if def and def.on_rightclick then
return def.on_rightclick(
pointed_thing.under, under, placer, itemstack)
end
if pos
and not minetest.is_protected(pos, placer:get_player_name()) then
if not minetest.registered_entities[mob] then
return
end
pos.y = pos.y + 1
local data = itemstack:get_metadata()
local smob = minetest.add_entity(pos, mob, data)
local ent = smob and smob:get_luaentity()
if not ent then return end -- sanity check
-- set owner if not a monster
if ent.type ~= "monster" then
ent.owner = placer:get_player_name()
ent.tamed = true
end
-- since mob is unique we remove egg once spawned
itemstack:take_item()
end
return itemstack
end,
})
-- register old stackable mob egg
minetest.register_craftitem(mob, {
description = desc,
inventory_image = invimg,
groups = grp,
on_place = function(itemstack, placer, pointed_thing)
local pos = pointed_thing.above
-- does existing on_rightclick function exist?
local under = minetest.get_node(pointed_thing.under)
local def = minetest.registered_nodes[under.name]
if def and def.on_rightclick then
return def.on_rightclick(
pointed_thing.under, under, placer, itemstack)
end
if pos
and not minetest.is_protected(pos, placer:get_player_name()) then
if not minetest.registered_entities[mob] then
return
end
-- have we reached active mob limit
if active_limit > 0 and active_mobs >= active_limit then
minetest.chat_send_player(placer:get_player_name(),
S("Active Mob Limit Reached!")
.. " (" .. active_mobs
.. " / " .. active_limit .. ")")
return
end
pos.y = pos.y + 1
local smob = minetest.add_entity(pos, mob)
local ent = smob and smob:get_luaentity()
if not ent then return end -- sanity check
-- don't set owner if monster or sneak pressed
if ent.type ~= "monster"
and not placer:get_player_control().sneak then
ent.owner = placer:get_player_name()
ent.tamed = true
end
-- if not in creative then take item
if not mobs.is_creative(placer:get_player_name()) then
itemstack:take_item()
end
end
return itemstack
end,
})
end
-- force capture a mob if space available in inventory, or drop as spawn egg
function mobs:force_capture(self, clicker)
-- add special mob egg with all mob information
local new_stack = ItemStack(self.name .. "_set")
local tmp, t = {}
for _,stat in pairs(self) do
t = type(stat)
if t ~= "function"
and t ~= "nil"
and t ~= "userdata" then
tmp[_] = self[_]
end
end
local data_str = minetest.serialize(tmp)
new_stack:set_metadata(data_str)
local inv = clicker:get_inventory()
if inv:room_for_item("main", new_stack) then
inv:add_item("main", new_stack)
else
minetest.add_item(clicker:get_pos(), new_stack)
end
self:mob_sound("default_place_node_hard")
remove_mob(self, true)
end
-- capture critter (thanks to blert2112 for idea)
function mobs:capture_mob(self, clicker, chance_hand, chance_net,
chance_lasso, force_take, replacewith)
if self.child
or not clicker:is_player()
or not clicker:get_inventory() then
return false
end
-- get name of clicked mob
local mobname = self.name
-- if not nil change what will be added to inventory
if replacewith then
mobname = replacewith
end
local name = clicker:get_player_name()
local tool = clicker:get_wielded_item()
-- are we using hand, net or lasso to pick up mob?
if tool:get_name() ~= ""
and tool:get_name() ~= "mobs:net"
and tool:get_name() ~= "mobs:lasso" then
return false
end
-- is mob tamed?
if self.tamed == false and force_take == false then
minetest.chat_send_player(name, S("Not tamed!"))
return false
end
-- cannot pick up if not owner (unless player has protection_bypass priv)
if not minetest.check_player_privs(name, "protection_bypass")
and self.owner ~= name and force_take == false then
minetest.chat_send_player(name, S("@1 is owner!", self.owner))
return false
end
if clicker:get_inventory():room_for_item("main", mobname) then
-- was mob clicked with hand, net, or lasso?
local chance = 0
if tool:get_name() == "" then
chance = chance_hand
elseif tool:get_name() == "mobs:net" then
chance = chance_net
tool:add_wear(4000) -- 17 uses
clicker:set_wielded_item(tool)
elseif tool:get_name() == "mobs:lasso" then
chance = chance_lasso
tool:add_wear(650) -- 100 uses
clicker:set_wielded_item(tool)
end
-- calculate chance.. add to inventory if successful?
if chance and chance > 0 and random(100) <= chance then
-- default mob egg
local new_stack = ItemStack(mobname)
-- add special mob egg with all mob information
-- unless 'replacewith' contains new item to use
if not replacewith then
new_stack = ItemStack(mobname .. "_set")
local tmp, t = {}
for _,stat in pairs(self) do
t = type(stat)
if t ~= "function"
and t ~= "nil"
and t ~= "userdata" then
tmp[_] = self[_]
end
end
local data_str = minetest.serialize(tmp)
new_stack:set_metadata(data_str)
end
local inv = clicker:get_inventory()
if inv:room_for_item("main", new_stack) then
inv:add_item("main", new_stack)
else
minetest.add_item(clicker:get_pos(), new_stack)
end
self:mob_sound("default_place_node_hard")
remove_mob(self, true)
return new_stack
-- when chance above fails or set to 0, miss!
elseif chance and chance ~= 0 then
minetest.chat_send_player(name, S("Missed!"))
self:mob_sound("mobs_swing")
return false
-- when chance is nil always return a miss (used for npc walk/follow)
elseif not chance then
return false
end
end
return true
end
-- protect tamed mob with rune item
function mobs:protect(self, clicker)
local name = clicker:get_player_name()
local tool = clicker:get_wielded_item()
local tool_name = tool:get_name()
if tool_name ~= "mobs:protector"
and tool_name ~= "mobs:protector2" then
return false
end
if not self.tamed then
minetest.chat_send_player(name, S("Not tamed!"))
return true
end
if (self.protected and tool_name == "mobs:protector")
or (self.protected == 2 and tool_name == "mobs:protector2") then
minetest.chat_send_player(name, S("Already protected!"))
return true
end
if not mobs.is_creative(clicker:get_player_name()) then
tool:take_item() -- take 1 protection rune
clicker:set_wielded_item(tool)
end
-- set protection level
if tool_name == "mobs:protector" then
self.protected = true
else
self.protected = 2 ; self.fire_damage = 0
end
local pos = self.object:get_pos()
pos.y = pos.y + self.collisionbox[2] + 0.5
effect(self.object:get_pos(), 25, "mobs_protect_particle.png",
0.5, 4, 2, 15)
self:mob_sound("mobs_spell")
return true
end
local mob_obj = {}
local mob_sta = {}
-- feeding, taming and breeding (thanks blert2112)
function mobs:feed_tame(self, clicker, feed_count, breed, tame)
-- can eat/tame with item in hand
if self.follow
and self:follow_holding(clicker) then
-- if not in creative then take item
if not mobs.is_creative(clicker:get_player_name()) then
local item = clicker:get_wielded_item()
item:take_item()
clicker:set_wielded_item(item)
end
-- increase health
self.health = self.health + 4
if self.health >= self.hp_max then
self.health = self.hp_max
if self.htimer < 1 then
minetest.chat_send_player(clicker:get_player_name(),
S("@1 at full health (@2)",
self.name:split(":")[2], tostring(self.health)))
self.htimer = 5
end
end
self.object:set_hp(self.health)
self:update_tag()
-- make children grow quicker
if self.child == true then
-- self.hornytimer = self.hornytimer + 20
-- deduct 10% of the time to adulthood
self.hornytimer = self.hornytimer + (
(CHILD_GROW_TIME - self.hornytimer) * 0.1)
--print ("====", self.hornytimer)
return true
end
-- feed and tame
self.food = (self.food or 0) + 1
if self.food >= feed_count then
self.food = 0
if breed and self.hornytimer == 0 then
self.horny = true
end
if tame then
if self.tamed == false then
minetest.chat_send_player(clicker:get_player_name(),
S("@1 has been tamed!",
self.name:split(":")[2]))
end
self.tamed = true
if not self.owner or self.owner == "" then
self.owner = clicker:get_player_name()
end
end
-- make sound when fed so many times
self:mob_sound(self.sounds.random)
end
return true
end
local item = clicker:get_wielded_item()
local name = clicker:get_player_name()
-- if mob has been tamed you can name it with a nametag
if item:get_name() == "mobs:nametag"
and (name == self.owner
or minetest.check_player_privs(name, "protection_bypass")) then
-- store mob and nametag stack in external variables
mob_obj[name] = self
mob_sta[name] = item
local tag = self.nametag or ""
local esc = minetest.formspec_escape
minetest.show_formspec(name, "mobs_nametag",
"size[8,4]" ..
"field[0.5,1;7.5,0;name;" ..
esc(S("Enter name:")) ..
";" .. tag .. "]" ..
"button_exit[2.5,3.5;3,1;mob_rename;" ..
esc(S("Rename")) .. "]")
return true
end
return false
end
-- inspired by blockmen's nametag mod
minetest.register_on_player_receive_fields(function(player, formname, fields)
-- right-clicked with nametag and name entered?
if formname == "mobs_nametag"
and fields.name
and fields.name ~= "" then
local name = player:get_player_name()
if not mob_obj[name]
or not mob_obj[name].object then
return
end
-- make sure nametag is being used to name mob
local item = player:get_wielded_item()
if item:get_name() ~= "mobs:nametag" then
return
end
-- limit name entered to 64 characters long
if fields.name:len() > 64 then
fields.name = fields.name:sub(1, 64)
end
-- update nametag
mob_obj[name].nametag = fields.name
mob_obj[name]:update_tag()
-- if not in creative then take item
if not mobs.is_creative(name) then
mob_sta[name]:take_item()
player:set_wielded_item(mob_sta[name])
end
-- reset external variables
mob_obj[name] = nil
mob_sta[name] = nil
end
end)
-- compatibility function for old entities to new modpack entities
function mobs:alias_mob(old_name, new_name)
-- check old_name entity doesnt already exist
if minetest.registered_entities[old_name] then
return
end
-- spawn egg
minetest.register_alias(old_name, new_name)
-- entity
minetest.register_entity(":" .. old_name, {
physical = false,
on_activate = function(self, staticdata)
if minetest.registered_entities[new_name] then
minetest.add_entity(self.object:get_pos(),
new_name, staticdata)
end
remove_mob(self)
end,
get_staticdata = function(self)
return self
end
})
end
|
local u = require("null-ls.utils")
local methods = require("null-ls.methods")
local config = require("null-ls.config").get()
local M = {}
M.handler = function(method, original_params, handler)
local params = u.make_params(original_params, methods.map[method])
if method == methods.lsp.COMPLETION then
require("null-ls.generators").run_registered({
filetype = params.ft,
method = methods.map[method],
params = params,
callback = function(results)
u.debug_log("received completion results from generators")
u.debug_log(results)
if #results == 0 then
handler({})
else
local items = {}
local isIncomplete = false
for _, result in ipairs(results) do
isIncomplete = isIncomplete or result.isIncomplete
if config.debug then
vim.validate({
items = { result.items, "table" },
isIncomplete = { result.isIncomplete, "boolean" },
})
vim.validate({
item = { result.items[1], "table" },
})
end
vim.list_extend(items, result.items)
end
handler({ isIncomplete = isIncomplete, items = items })
end
end,
})
original_params._null_ls_handled = true
end
end
return M
|
for line in io.lines(arg[1]) do
local a = {}
for i in line:gmatch("%d+") do
a[#a + 1] = i
end
for i = 1, #a/2 do
if i > 1 then io.write " " end
io.write(a[i] * a[#a/2 + i])
end
print()
end
|
SWEP.Sounds = {
base_draw = {
{time = 0/30, sound = "INS2SHARED_DRAW"},
},
base_firelast = {
{time = 0/60, sound = "DOIC96_BOLTRELEASE"},
},
iron_firelast = {
{time = 0/60, sound = "DOIC96_BOLTRELEASE"},
},
base_reload = {
{time = 19/31.8, sound = "DOIC96_MAGRELEASE"},
{time = 25/31.8, sound = "DOIC96_MAGOUT"},
{time = 32/31.8, sound = "DOIC96_FETCHMAG"},
{time = 64/31.8, sound = "DOIC96_MAGFIDDLE"},
{time = 71/31.8, sound = "DOIC96_MAGIN"},
{time = 89/31.8, sound = "DOIC96_RATTLE"},
},
base_reloadempty = {
{time = 19/31.8, sound = "DOIC96_MAGRELEASE"},
{time = 25/31.8, sound = "DOIC96_MAGOUT"},
{time = 32/31.8, sound = "DOIC96_FETCHMAG"},
{time = 64/31.8, sound = "DOIC96_MAGFIDDLE"},
{time = 71/31.8, sound = "DOIC96_MAGIN"},
{time = 106/31.8, sound = "DOIC96_BOLTRELEASE"},
{time = 124/31.8, sound = "DOIC96_RATTLE"},
},
base_reload_ext = {
{time = 19/31.8, sound = "DOIC96_MAGRELEASE"},
{time = 25/31.8, sound = "DOIC96_MAGOUT"},
{time = 32/31.8, sound = "DOIC96_FETCHMAG"},
{time = 64/31.8, sound = "DOIC96_MAGFIDDLE"},
{time = 71/31.8, sound = "DOIC96_MAGIN"},
{time = 89/31.8, sound = "DOIC96_RATTLE"},
},
base_reloadempty_ext = {
{time = 19/31.8, sound = "DOIC96_MAGRELEASE"},
{time = 25/31.8, sound = "DOIC96_MAGOUT"},
{time = 32/31.8, sound = "DOIC96_FETCHMAG"},
{time = 64/31.8, sound = "DOIC96_MAGFIDDLE"},
{time = 71/31.8, sound = "DOIC96_MAGIN"},
{time = 106/31.8, sound = "DOIC96_BOLTRELEASE"},
{time = 124/31.8, sound = "DOIC96_RATTLE"},
},
iron_dryfire = {
{time = 0/30, sound = "DOIC96_EMPTY"},
},
}
|
gpay.c.db = gpay.c.db or {}
gpay.c.db.host = ""
gpay.c.db.login = ""
gpay.c.db.password = ""
gpay.c.db.database = ""
gpay.c.token = "ASD654f6544fFFF121101" -- ТОКЕН СЕРВЕРА И PHP!!!!!
gpay.c.oplata_ru_id = "" -- ID ТОВАРА
gpay.c.await = 3 -- Задержка перед запросом
gpay.c.debug = false -- Дебаг мод
gpay.c.db.serverid = "" -- Id сервера
gpay.c.rights = {
["STEAM_0:0:9"] = true -- STEAMID СВОЙ
}
|
local panel = {}
panel.Name = "search"
function panel:Init()
self:BaseInit({
DontResize = {
Width = true,
Height = true
},
Declare = {
VideoID = "",
URL = ""
}
})
self:SetPaintBackgroundEnabled(false)
//will hold the buttons and stuff
self.Navbar = vgui.Create("DPanel", self)
self.Navbar:SetTall(32)
self:SetDockPadding(self.Navbar)
self.Navbar:Dock(TOP)
self.Navbar.Paint = function(w,h ) end
self.Browser = vgui.Create("DHTML", self )
self.Browser:SetSize(self:GetWidth() - 25, self:GetHeight() - 70)
self.Browser:DockPadding(5,5,5,5)
self.Browser:Dock(FILL)
self.Browser:SetAllowLua(true)
self.Browser:AddFunction("console", "seturl", function(str)
self.Submit:SetDisabled(true)
if (!string.find(str, "https://")) then
if (!string.find(str, "http://")) then
return
end
str = string.Replace(str, "http://", "https://")
end
self.URL = str
self.TextEntry:SetValue(self.URL)
str = LydsPlayer.ParseYoutubeURL(str)
if (str != nil ) then
self.Submit:SetDisabled(false)
return
end
end)
self.Browser.OnChangeTitle = function(this)
this:QueueJavascript("console.seturl(document.location.href)")
end
self.TextEntry = vgui.Create("DTextEntry", self.Navbar)
self.TextEntry:Dock(LEFT)
self.TextEntry:SetWide(( self:GetWidth() * 0.70 ) - 12)
self.TextEntry:SetDisabled(true)
self.Submit = vgui.Create("DButton", self.Navbar)
self.Submit:Dock(RIGHT)
self.Submit:SetIcon("icon16/arrow_up.png")
self.Submit:SetWide(( self:GetWidth() * 0.30 ) - 12)
self.Submit:SetText("Submit")
self.Submit:SetDisabled(true)
self.Submit.DoClick = function(this)
local str = LydsPlayer.ParseYoutubeURL(self.URL)
if (str == nil) then
self.Submit:SetDisabled(true)
LydsPlayer.CreateWarningBox("Invalid","Invalid Youtube URL", 2)
return
end
RunConsoleCommand("media_play", LydsPlayer.MediaType.YOUTUBE, str)
self.Submit:SetDisabled(true)
self.Browser:OpenURL("https://youtube.com")
LydsPlayer.HidePanel("SearchPanel") //hide the search panel
end
self.Browser:OpenURL("https://youtube.com")
end
vgui.Register("LydsPlayer.SearchBrowserContainer", panel, "LydsPlayer.BasePanel")
|
return {
id = "material_pastelgreen",
type = "material",
name = "Pastel Green",
description = "A nice green color for your eg!",
rarity = 4,
hidden = false,
metadata = {
color = Color3.fromRGB(115, 255, 99),
material = Enum.Material.SmoothPlastic,
}
}
|
---@param params nil|any[]
---@return Array
function Array(params)
---@class Array
local this = {
---@private
__NAME__ = "Array",
---@private
__PROPERTIES__ = {
keys = {},
values = {},
}
}
if (type(params) == "table") then
if (instanceof(params, "Array")) then
params.forEach(function(k, v)
table.insert(this.__PROPERTIES__.keys, k)
this.__PROPERTIES__.values[k] = v
end)
elseif (#params > 0) then
for k, v in ipairs(params) do
table.insert(this.__PROPERTIES__.keys, k)
this.__PROPERTIES__.values[k] = v
end
end
end
--- 返回数组中元素的数目
---@return number integer
this.count = function()
return #this.__PROPERTIES__.keys
end
--- 返回数组中key索引的顺序;没有该key则返回-1
this.index = function(key)
local idx = -1
for ki, k in ipairs(this.__PROPERTIES__.keys) do
if (k == key) then
idx = ki
break
end
end
return idx
end
--- 强行设置数组元素
this.set = function(key, value)
if (this.__PROPERTIES__.values[key] == nil) then
table.insert(this.__PROPERTIES__.keys, key)
end
this.__PROPERTIES__.values[key] = value
end
--- 根据key获取数组value
this.get = function(key)
return this.__PROPERTIES__.values[key]
end
--- 返回数组中所有的键名
this.keys = function()
return this.__PROPERTIES__.keys
end
--- 返回数组中所有的值
this.values = function()
local values = {}
for _, key in ipairs(this.__PROPERTIES__.keys) do
table.insert(values, this.__PROPERTIES__.values[key])
end
return values
end
--- 检查指定的键名是否存在于数组中
this.keyExists = function(key)
return key ~= nil and table.includes(this.keys(), key)
end
--- 检查指定的值是否存在于数组中
this.valueExists = function(value)
return value ~= nil and table.includes(this.values(), value)
end
--- 遍历
---@alias noteArrayEach fun(key: "key", value: "value"):void
---@param action noteArrayEach | "function(key,value) end"
this.forEach = function(action)
if (type(action) == "function") then
local keys = table.clone(this.__PROPERTIES__.keys)
for _, key in ipairs(keys) do
if (this.__PROPERTIES__.values[key] ~= nil) then
if (false == action(key, this.__PROPERTIES__.values[key])) then
break
end
end
end
keys = nil
end
end
--- 反向遍历
---@param action noteArrayEach | "function(key,value) end"
this.backEach = function(action)
if (type(action) == "function") then
local keys = {}
for i = #this.__PROPERTIES__.keys, 1, -1 do
table.insert(keys, this.__PROPERTIES__.keys[i])
end
for _, key in ipairs(keys) do
if (this.__PROPERTIES__.values[key] ~= nil) then
if (false == action(key, this.__PROPERTIES__.values[key])) then
break
end
end
end
keys = nil
end
end
--- 将一个元素插入数组的末尾(入栈)
this.push = function(value, key)
key = key or ("Ar:" .. (htime.inc or 0) .. string.random(5))
if (this.__PROPERTIES__.values[key] == nil) then
table.insert(this.__PROPERTIES__.keys, key)
end
this.__PROPERTIES__.values[key] = value
end
--- 删除数组的最后一个元素(出栈)
this.pop = function()
local value
local last = this.count()
if (last > 0) then
local key = this.__PROPERTIES__.keys[last]
value = this.__PROPERTIES__.values[key]
this.__PROPERTIES__.values[key] = nil
table.remove(this.__PROPERTIES__.keys, last)
end
return value
end
--- 删除数组中首个元素,并返回被删除元素的值
this.shift = function()
local value
if (this.__PROPERTIES__.keys[1]) then
local key = this.__PROPERTIES__.keys[1]
value = this.__PROPERTIES__.values[key]
this.__PROPERTIES__.values[key] = nil
table.remove(this.__PROPERTIES__.keys, 1)
end
return value
end
--- 在数组开头插入一个元素
this.unshift = function(value, key)
local count = this.count()
if (count <= 0) then
this.push(value, key)
else
for i, k in ipairs(this.__PROPERTIES__.keys) do
this.__PROPERTIES__.keys[i + 1] = k
end
key = key or ("Ar:" .. (htime.inc or 0) .. string.random(5))
this.__PROPERTIES__.keys[1] = key
this.__PROPERTIES__.values[key] = value
end
end
--- 从数组中移除key索引的元素,并用新元素value取代它;没有value可替换则为删除
this.splice = function(key, value)
if (key == nil or not this.keyExists(key)) then
return
end
if (value ~= nil) then
this.__PROPERTIES__.values[key] = value
else
this.__PROPERTIES__.values[key] = nil
table.remove(this.__PROPERTIES__.keys, this.index(key))
end
return this.__PROPERTIES__.values
end
--- 克隆一个副本
---@return Array
this.clone = function()
local copy = Array()
this.forEach(function(key, value)
if (instanceof(value, "Array")) then
copy.push(value.clone(), key)
else
copy.push(value, key)
end
end)
return copy
end
--- 合并另一个array
---@param arr Array
this.merge = function(arr)
if (instanceof(arr, "Array")) then
arr.forEach(function(key, value)
if (instanceof(value, "Array")) then
if (type(key) == "number") then
this.push(this.clone(value))
else
this.push(this.clone(value), key)
end
else
if (type(key) == "number") then
this.push(value)
else
if (this.keyExists(key)) then
this.__PROPERTIES__.values[key] = value
else
this.push(value, key)
end
end
end
end)
end
return this
end
--- 键排序
---@param
---@return Array
this.sort = function()
local ks = table.clone(this.__PROPERTIES__.keys)
table.sort(ks)
local kArr = Array()
for _, k in ipairs(ks) do
kArr.set(k, this.__PROPERTIES__.values[k])
end
return kArr
end
return this
end
|
-- NO TOUCHY, IF SOMETHING IS WRONG CONTACT KANERSPS! --
-- NO TOUCHY, IF SOMETHING IS WRONG CONTACT KANERSPS! --
-- NO TOUCHY, IF SOMETHING IS WRONG CONTACT KANERSPS! --
-- NO TOUCHY, IF SOMETHING IS WRONG CONTACT KANERSPS! --
-- Server
Users = {}
commands = {}
settings = {}
settings.defaultSettings = {
['banReason'] = "You are currently banned. Please go to: insertsite.com/bans",
['pvpEnabled'] = true,
['permissionDenied'] = false,
['debugInformation'] = false,
['startingCash'] = 5000,
['enableRankDecorators'] = false,
['moneyIcon'] = "$"
}
settings.sessionSettings = {}
require "resources/essentialmode/lib/MySQL"
AddEventHandler('playerConnecting', function(name, setCallback)
local identifiers = GetPlayerIdentifiers(source)
for i = 1, #identifiers do
local identifier = identifiers[i]
debugMsg('Checking user ban: ' .. identifier .. " (" .. name .. ")")
local status, err = pcall(isIdentifierBanned(identifier))
if(err) then
MySQL:open("127.0.0.1", "gta5_gamemode_essential", "root", "space031")
end
local banned = isIdentifierBanned(identifier)
if(banned)then
if(type(settings.defaultSettings.banreason) == "string")then
setCallback(settings.defaultSettings.banreason)
elseif(type(settings.defaultSettings.banreason) == "function")then
setCallback(settings.defaultSettings.banreason(identifier, name))
else
setCallback("Default ban reason error")
end
CancelEvent()
end
end
end)
AddEventHandler('playerDropped', function(reason)
if(Users[source])then
TriggerEvent("es:playerDropped", Users[source])
MySQL:executeQuery("UPDATE users SET `money`='@value' WHERE identifier = '@identifier'", {['@value'] = Users[source].money, ['@identifier'] = Users[source].identifier})
Users[source] = nil
end
end)
local justJoined = {}
RegisterServerEvent('es:firstJoinProper')
AddEventHandler('es:firstJoinProper', function()
local identifiers = GetPlayerIdentifiers(source)
for i = 1, #identifiers do
if(Users[source] == nil)then
debugMsg("Essential | Loading user: " .. GetPlayerName(source))
local identifier = identifiers[i]
registerUser(identifier, source)
TriggerEvent('es:initialized', source)
justJoined[source] = true
if(settings.defaultSettings.pvpEnabled)then
TriggerClientEvent("es:enablePvp", source)
end
end
end
end)
AddEventHandler('es:setSessionSetting', function(k, v)
settings.sessionSettings[k] = v
end)
AddEventHandler('es:getSessionSetting', function(k, cb)
cb(settings.sessionSettings[k])
end)
RegisterServerEvent('playerSpawn')
AddEventHandler('playerSpawn', function()
if(justJoined[source])then
TriggerEvent("es:firstSpawn", source)
justJoined[source] = nil
end
end)
AddEventHandler("es:setDefaultSettings", function(tbl)
for k,v in pairs(tbl) do
if(settings.defaultSettings[k] ~= nil)then
settings.defaultSettings[k] = v
end
end
debugMsg("Default settings edited.")
end)
AddEventHandler('chatMessage', function(source, n, message)
if(startswith(message, "/"))then
local command_args = stringsplit(message, " ")
command_args[1] = string.gsub(command_args[1], "/", "")
local command = commands[command_args[1]]
if(command)then
CancelEvent()
if(command.perm > 0)then
if(Users[source].permission_level >= command.perm or Users[source].group:canTarget(command.group))then
command.cmd(source, command_args, Users[source])
TriggerEvent("es:adminCommandRan", source, command_args, Users[source])
else
command.callbackfailed(source, command_args, Users[source])
TriggerEvent("es:adminCommandFailed", source, command_args, Users[source])
if(type(settings.defaultSettings.permissionDenied) == "string" and not WasEventCanceled())then
TriggerClientEvent('chatMessage', source, "", {0,0,0}, defaultSettings.permissionDenied)
end
debugMsg("Non admin (" .. GetPlayerName(source) .. ") attempted to run admin command: " .. command_args[1])
end
else
command.cmd(source, command_args, Users[source])
TriggerEvent("es:userCommandRan", source, command_args, Users[source])
end
TriggerEvent("es:commandRan", source, command_args, Users[source])
else
TriggerEvent('es:invalidCommandHandler', source, command_args, Users[source])
if WasEventCanceled() then
CancelEvent()
end
end
else
TriggerEvent('es:chatMessage', source, message, Users[source])
end
end)
AddEventHandler('es:addCommand', function(command, callback)
commands[command] = {}
commands[command].perm = 0
commands[command].group = "user"
commands[command].cmd = callback
debugMsg("Command added: " .. command)
end)
AddEventHandler('es:addAdminCommand', function(command, perm, callback, callbackfailed)
commands[command] = {}
commands[command].perm = perm
commands[command].group = "superadmin"
commands[command].cmd = callback
commands[command].callbackfailed = callbackfailed
debugMsg("Admin command added: " .. command .. ", requires permission level: " .. perm)
end)
AddEventHandler('es:addGroupCommand', function(command, group, callback, callbackfailed)
commands[command] = {}
commands[command].perm = math.maxinteger
commands[command].group = group
commands[command].cmd = callback
commands[command].callbackfailed = callbackfailed
debugMsg("Group command added: " .. command .. ", requires group: " .. group)
end)
RegisterServerEvent('es:updatePositions')
AddEventHandler('es:updatePositions', function(x, y, z)
if(Users[source])then
Users[source]:setCoords(x, y, z)
end
end)
-- Info command
commands['info'] = {}
commands['info'].perm = 0
commands['info'].cmd = function(source, args, user)
TriggerClientEvent('chatMessage', source, 'SYSTEM', {255, 0, 0}, "^2[^3EssentialMode^2]^0 Version: ^22.1.0")
TriggerClientEvent('chatMessage', source, 'SYSTEM', {255, 0, 0}, "^2[^3EssentialMode^2]^0 Commands loaded: ^2" .. (returnIndexesInTable(commands) - 1))
end
|
---------------------------------------------------------------------------------------------------
-- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/3556
---------------------------------------------------------------------------------------------------
-- Description: Check that SDL sends response to SDL.GetListOfPermission with appId and function group
-- in case the 'default' section contains groups with user_consent_prompt.
--
-- Preconditions:
-- 1. Clean environment
-- 2. PT contains "Location_1" group with user_consent_prompt in default section
-- 3. SDL, HMI, Mobile session are started
-- 4. App is registered
-- 5. App is activated
-- Steps:
-- 1. HMI sends GetListOfPermissions request
-- SDL does:
-- - sends GetListOfPermissions response with allowedFunctions { name = "Location" }
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require("user_modules/sequences/actions")
local utils = require("user_modules/utils")
local json = require('modules/json')
--[[ Test Configuration ]]
runner.testSettings.restrictions.sdlBuildOptions = {{ extendedPolicy = { "EXTERNAL_PROPRIETARY" }}}
runner.testSettings.isSelfIncluded = false
--[[ Local Functions ]]
local function updatePreloadedPT()
local pt = common.sdl.getPreloadedPT()
pt.policy_table.functional_groupings["DataConsent-2"].rpcs = utils.json.null
pt.policy_table.app_policies.default.groups = { "Base-4", "Location-1" }
common.sdl.setPreloadedPT(pt)
end
local function getListOfPermissions()
local rid = common.getHMIConnection():SendRequest("SDL.GetListOfPermissions", { appID = common.getHMIAppId() })
local resultGetListOfPermissions = {
code = 0,
method = "SDL.GetListOfPermissions",
allowedFunctions = {{ id = 156072572, name = "Location" }},
externalConsentStatus = json.EMPTY_ARRAY
}
common.getHMIConnection():ExpectResponse(rid, { result = resultGetListOfPermissions })
:ValidIf(function(_,data)
if data.result.externalConsentStatus ~= resultGetListOfPermissions.externalConsentStatus then
return false, "externalConsentStatus contains unexpected parameters\n"
end
return true
end)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Update Preloaded PT", updatePreloadedPT)
runner.Step("Start SDL, HMI, connect regular mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("Send GetListOfPermissions", getListOfPermissions)
runner.Title("Postconditions")
runner.Step("Stop SDL, restore SDL settings and PPT", common.postconditions)
|
local lfdbL = require "lfdb_lib"
local ffi = require "ffi"
lfdbL.setup_ffi(ffi)
local C = ffi.C
local fdb = ffi.load("fdb_c")
local pthread = ffi.load("pthread")
local unique_id = tostring( {} ):sub(8)
local chunk = [[
local unique_id = tostring( {} ):sub(8)
local lfdbL = require "lfdb_lib"
local ffi = require "ffi"
lfdbL.setup_ffi(ffi)
local fdb = ffi.load("fdb_c")
print(string.format("{%s} Spawned thread: {%s}", unique_id, unique_id))
local function fdb_network_thread()
return lfdbL.run_network(ffi, fdb)
end
cb_fdb_network_thread = tonumber(ffi.cast('intptr_t', ffi.cast('void *(*)(void *)', fdb_network_thread)))
]]
local function spawn_thread()
local pid = ffi.new("pthread_t[1]")
local L = assert(C.luaL_newstate())
C.luaL_openlibs(L)
local res = C.luaL_loadstring(L, chunk)
assert(res == 0)
--res = C.lua_pcall(L, 0, 1, 0)
res = C.lua_pcall(L, 0, 0, 0)
if res ~= 0 then
print(string.format("thread error[%s]: %s", unique_id, ffi.string(C.lua_tolstring(L, -1, nil))))
end
assert(res == 0)
C.lua_getfield(L, C.LUA_GLOBALSINDEX, "cb_fdb_network_thread")
local fun = C.lua_tointeger(L, -1)
print(string.format("THREAD FUN IS: %s", fun))
C.lua_settop(L, -2)
print(string.format("{%s} THREAD CREATING", unique_id))
res = pthread.pthread_create(pid, nil, ffi.cast('void *(*)(void *)', fun), nil)
print(string.format("{%s} THREAD CREATED", unique_id))
assert(res == 0)
return pid, L
end
lfdbL.select_api_version(ffi, fdb)
lfdbL.setup_network(ffi, fdb)
print(string.format("fdb.C.fdb_get_error(1): %s", lfdbL.error_to_string(1, ffi, fdb)))
print(string.format("{%s} INVOKING THE THREAD!", unique_id))
local thread, thread_L = spawn_thread()
print(string.format("{%s} DONE INVOKING THE THREAD!", unique_id))
print(string.format("THREAD IS: %s", thread[0]))
-- busy loop networking thread coordination hack
local t = 1
for i=1,100000 do t = t * i * math.log(t*3) end
print("CREATING FDB_DB")
local fdb_db = lfdbL.create_database(ffi, fdb)
print(string.format("FDB_DB IS: %s", fdb_db))
local fdb_tx = lfdbL.create_transaction(ffi, fdb, fdb_db)
print(string.format("FDB_TX IS: %s", fdb_tx))
lfdbL.do_transaction(ffi, fdb, fdb_tx, function(tx) print("IN TRANSACTION!"); assert(true) end)
lfdbL.destroy_transaction(fdb, fdb_tx)
lfdbL.transactional(ffi, fdb, fdb_db, function(tx) print("Failing the transaction!"); assert(false) end)
local key = "asdffdsa"
local val = lfdbL.db_get(ffi, fdb, fdb_db, key)
print(string.format("GOT VAL FOR KEY{%s}: %s", key, val))
lfdbL.db_set(ffi, fdb, fdb_db, key, "12344321")
val = lfdbL.db_get(ffi, fdb, fdb_db, key)
print(string.format("GOT VAL FOR KEY{%s}: %s", key, val))
print("Closing shop...")
local res = pthread.pthread_cancel(thread[0])
assert(res == 0)
lfdbL.destroy_database(fdb, fdb_db)
C.lua_close(thread_L)
print("Exiting...")
|
-- Slight rewrite of the dump function from luvit/pretty-print
local controls = require('./controls')
local match, find = string.match, string.find
local gsub, rep = string.gsub, string.rep
local byte = string.byte
local concat, insert = table.concat, table.insert
local type = type
local dump
local seen, output, stack = {}, {}, {}
local offset = 0
local function escape(input)
return controls[byte(input, 1)]
end
local function recalculateOffset(index)
for i = index + 1, #output do
local value = output[i]
local result = match(value, '\n([^\n]*)$')
offset = result and #result or offset + #value
end
end
local function write(input)
local length = #input
local i = 1
local entry = stack[i]
while offset + length > 80 and entry do
if not entry.opened then
local index = entry.index
entry.opened = true
insert(output, index + 1, '\n'..rep(' ', i))
recalculateOffset(index)
for x = i + 1, #stack do
stack[x].index = stack[x].index + 1
end
end
i = i + 1
entry = stack[i]
end
output[#output + 1] = input
offset = offset + length
end
local process
function process(input, esc, recursive)
local t = type(input)
if t == 'string' then
if find(input, "'") and not find(input, '"') then
write('"')
write(esc and gsub(input, '[%c\\\128-\255]', escape) or input)
write('"')
else
write("'")
write(esc and gsub(input, '[%c\\\128-\255]', escape) or input)
write("'")
end
return
end
if t == 'table' and not seen[input] then
if not recursive then
seen[input] = true
end
write('{ ')
local i, nextIndex = 1, 1
for k, v in pairs(input) do
stack[#stack + 1] = {index = #output, opened = false}
if k == nextIndex then
nextIndex = k + 1
process(v, esc, recursive)
else
if type(k) == 'string' and find(k, '^[%a_][%a%d_]*$') then
write(k)
write(' = ')
else
write('[')
process(k, esc, recursive)
write(']')
write(' = ')
end
if type(v) == 'table' then
process(v, esc, recursive)
else
stack[#stack + 1] = {index = #output, opened = false}
process(v, esc, recursive)
stack[#stack] = nil
end
end
write(', ')
i = i + 1
stack[#stack] = nil
end
output[#output] = ' '
write('}')
else
write(tostring(input))
end
end
function dump(input, esc, recursive)
process(input, esc, recursive)
local result = concat(output)
seen, output, stack = {}, {}, {}
offset = 0
return result
end
return dump
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.