content
stringlengths 1
1.05M
| size
int64 5
1.05M
| max_stars_repo_name
stringlengths 5
114
|
|---|---|---|
--[[
General -> Profiles Tab -> General & Advanced Tabs
--]]
local L = Grid2Options.L
--==============================
local GetAllProfiles, GetUnusedProfiles
do
local profiles, values = {}, {}
local function GetProfiles(showCurrent)
wipe(profiles)
wipe(values)
Grid2.db:GetProfiles(profiles)
for _,k in pairs(profiles) do
values[k] = k
end
if not showCurrent then
values[Grid2.db:GetCurrentProfile()] = nil
end
return values
end
GetAllProfiles = function() return GetProfiles(true) end
GetUnusedProfiles = function() return GetProfiles(false) end
end
--==============================
local options = {}
options.title = {
order = 1,
type = "description",
name = L["You can change the active database profile, so you can have different settings for every character.\n"],
}
options.current = {
type = "select",
name = L["Current Profile"],
desc = L["Select one of your currently available profiles."],
order = 2,
get = function() return Grid2.db:GetCurrentProfile() end,
set = function(_, v) Grid2.db:SetProfile(v) end,
validate = function() return not InCombatLockdown() or L["Profile cannot be changed in combat"] end,
disabled = InCombatLockdown,
values = GetAllProfiles,
}
options.reset = {
order = 3,
type = "execute",
width = "half",
name = L["Reset"],
desc = L["Reset the current profile back to its default values."],
confirm = true,
confirmText = L["Are you sure you want to reset current profile?"],
func = function()
Grid2:ProfileShutdown()
Grid2.db:ResetProfile()
end,
}
--==============
if not Grid2.isClassic then
options.prodesc = {
order = 8,
type = "description",
name = " ",
}
options.proenabled = {
type = "toggle",
name = "|cffffd200".. L["Enable profiles by Specialization"] .."|r",
desc = L["When enabled, your profile will be set according to the character specialization."],
descStyle = "inline",
order = 9,
width = "full",
get = function(info) return Grid2.profiles.char[1] and Grid2.profiles.char.enabled end,
set = function(info, value)
local db = Grid2.profiles.char
wipe(db)
db.enabled = value or nil
if value then
local pro = Grid2.db:GetCurrentProfile()
for i=1,GetNumSpecializations() or 0 do
db[i] = pro
end
end
Grid2:ReloadProfile()
end,
}
for i=GetNumSpecializations(),1, -1 do
options['profile'..i] = {
type = "select",
name = select( 2, GetSpecializationInfo(i) ),
desc = "",
order = 10.5+i,
get = function() return Grid2.profiles.char[i] end,
set = function(_, v)
Grid2.profiles.char[i] = v
Grid2:ReloadProfile()
end,
values = GetAllProfiles,
hidden = function() return type(Grid2.profiles.char[1])~='string' end,
}
end
end
--==============
options.newdesc = {
order = 15,
type = "description",
name = "\n" .. L["Create a new empty profile by entering a name in the editbox."],
}
options.new = {
name = L["New Profile"],
desc = L["Create a new empty profile by entering a name in the editbox."],
type = "input",
order = 20,
get = false,
set = function(_, v) Grid2.db:SetProfile(v) end,
}
--==============
options.copydesc = {
order = 25,
type = "description",
name = "\n" .. L["Copy the settings from one existing profile into the currently active profile."],
}
options.copyfrom = {
type = "select",
name = L['Copy From'],
desc = L["Copy the settings from one existing profile into the currently active profile."],
order = 30,
get = false,
set = function(_, v)
Grid2:ProfileShutdown()
Grid2.db:CopyProfile(v)
end,
values = GetUnusedProfiles,
confirm = true,
confirmText = L["Are you sure you want to overwrite current profile values?"],
}
--==============
options.deletedesc = {
order = 35,
type = "description",
name = "\n" .. L["Delete existing and unused profiles from the database."],
}
options.delete = {
type = "select",
name = L['Delete a Profile'],
desc = L["Delete existing and unused profiles from the database."],
order = 40,
get = false,
set = function(_, v) Grid2.db:DeleteProfile(v) end,
values = GetUnusedProfiles,
confirm = true,
confirmText = L["Are you sure you want to delete the selected profile?"],
}
--==============================
Grid2Options:AddGeneralOptions("Profiles", nil, {
type = "group",
childGroups = "tab",
order = 100,
name = L["Profiles"],
desc = "",
args = {
general = { type = "group", order= 100, name = L["General"], desc = "", args = options },
import = Grid2Options.AdvancedProfileOptions or {},
},
}, 490 )
| 4,568
|
mrbandler/wow-ui
|
local defaults = require'hop.defaults'
local hint = require'hop.hint'
local M = {}
M.hint = hint.hint
-- Setup user settings.
M.opts = defaults
function M.setup(opts)
-- Look up keys in user-defined table with fallback to defaults.
M.opts = setmetatable(opts or {}, {__index = defaults})
-- Insert the highlights and register the autocommand if asked to.
local highlight = require'hop.highlight'
highlight.insert_highlights()
if M.opts.create_hl_autocmd then
highlight.create_autocmd()
end
end
return M
| 527
|
rish987/hop.nvim
|
registerNpc(394, {
walk_speed = 290,
run_speed = 670,
scale = 225,
r_weapon = 1036,
l_weapon = 0,
level = 112,
hp = 139,
attack = 643,
hit = 370,
def = 802,
res = 246,
avoid = 175,
attack_spd = 120,
is_magic_damage = 0,
ai_type = 132,
give_exp = 509,
drop_type = 385,
drop_money = 0,
drop_item = 99,
union_number = 99,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 250,
npc_type = 10,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end
| 1,076
|
RavenX8/osirosenew
|
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
CInfoPickupManager = inherit(cSingleton)
function CInfoPickupManager:constructor()
local start = getTickCount()
local qh = CDatabase:getInstance():query("select * from infopickups")
for i,v in ipairs(qh) do
local infopickup = createPickup(v["X"],v["Y"],v["Z"],3,1239,0)
setElementInterior(infopickup,v["Int"])
setElementDimension(infopickup,v["Dim"])
enew(infopickup,CInfoPickup,v["ID"],v["X"],v["Y"],v["Z"],v["Int"],v["Dim"],v["Text"])
end
outputDebugString("Es wurden "..#InfoPickups.." Infopickups gefunden (" .. getTickCount() - start .. "ms)", 3)
end
| 828
|
Noneatme/iLife-SA
|
rifle_acid_beam = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Acid beam",
directObjectTemplate = "object/weapon/ranged/rifle/rifle_acid_beam.iff",
craftingValues = {
{"mindamage",60,110,0},
{"maxdamage",170,360,0},
{"attackspeed",12.7,7.4,0},
{"woundchance",11,25,0},
{"hitpoints",750,750,0},
{"attackhealthcost",62,31,0},
{"attackactioncost",53,26,0},
{"attackmindcost",115,57,0},
{"roundsused",30,65,0},
{"zerorangemod",-70,-70,0},
{"maxrangemod",-10,15,0},
{"midrange",50,50,0},
{"midrangemod",10,10,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 = 1000,
junkDealerTypeNeeded = JUNKWEAPONS,
junkMinValue = 20,
junkMaxValue = 60
}
addLootItemTemplate("rifle_acid_beam", rifle_acid_beam)
| 937
|
V-Fib/FlurryClone
|
ESX = nil
Citizen.CreateThread(function()
while true do
Wait(5)
if ESX ~= nil then
else
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
end
end
end)
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
local fishing = false
local lastInput = 0
local pause = false
local pausetimer = 0
local correct = 0
local bait = "none"
local blip = AddBlipForCoord(Config.SellFish.x, Config.SellFish.y, Config.SellFish.z)
SetBlipSprite (blip, 356)
SetBlipDisplay(blip, 4)
SetBlipScale (blip, 1.1)
SetBlipColour (blip, 17)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Fish selling")
EndTextCommandSetBlipName(blip)
local blip2 = AddBlipForCoord(Config.SellTurtle.x, Config.SellTurtle.y, Config.SellTurtle.z)
SetBlipSprite (blip2, 68)
SetBlipDisplay(blip2, 4)
SetBlipScale (blip2, 0.9)
SetBlipColour (blip2, 49)
SetBlipAsShortRange(blip2, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Sea Turtle dealer")
EndTextCommandSetBlipName(blip2)
local blip3 = AddBlipForCoord(Config.SellShark.x, Config.SellShark.y, Config.SellShark.z)
SetBlipSprite (blip3, 68)
SetBlipDisplay(blip3, 4)
SetBlipScale (blip3, 0.9)
SetBlipColour (blip3, 49)
SetBlipAsShortRange(blip3, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Shark meat dealer")
EndTextCommandSetBlipName(blip3)
for _, info in pairs(Config.MarkerZones) do
info.blip = AddBlipForCoord(info.x, info.y, info.z)
SetBlipSprite(info.blip, 455)
SetBlipDisplay(info.blip, 4)
SetBlipScale(info.blip, 1.0)
SetBlipColour(info.blip, 20)
SetBlipAsShortRange(info.blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Boat rental")
EndTextCommandSetBlipName(info.blip)
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
for k in pairs(Config.MarkerZones) do
DrawMarker(1, Config.MarkerZones[k].x, Config.MarkerZones[k].y, Config.MarkerZones[k].z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 1.0, 0, 150, 150, 100, 0, 0, 0, 0)
end
end
end)
function DisplayHelpText(str)
SetTextComponentFormat("STRING")
AddTextComponentString(str)
DisplayHelpTextFromStringLabel(0, 0, 1, -1)
end
Citizen.CreateThread(function()
while true do
Wait(600)
if pause and fishing then
pausetimer = pausetimer + 1
end
end
end)
Citizen.CreateThread(function()
while true do
Wait(5)
if fishing then
if IsControlJustReleased(0, Keys['1']) then
input = 1
end
if IsControlJustReleased(0, Keys['2']) then
input = 2
end
if IsControlJustReleased(0, Keys['3']) then
input = 3
end
if IsControlJustReleased(0, Keys['4']) then
input = 4
end
if IsControlJustReleased(0, Keys['5']) then
input = 5
end
if IsControlJustReleased(0, Keys['6']) then
input = 6
end
if IsControlJustReleased(0, Keys['7']) then
input = 7
end
if IsControlJustReleased(0, Keys['8']) then
input = 8
end
if IsControlJustReleased(0, Keys['X']) then
fishing = false
ESX.ShowNotification("~r~Stopped fishing")
end
if fishing then
playerPed = GetPlayerPed(-1)
local pos = GetEntityCoords(GetPlayerPed(-1))
if pos.y >= 7700 or pos.y <= -4000 or pos.x <= -3700 or pos.x >= 4300 or IsPedInAnyVehicle(GetPlayerPed(-1)) then
else
fishing = false
ESX.ShowNotification("~r~Stopped fishing")
end
if IsEntityDead(playerPed) or IsEntityInWater(playerPed) then
ESX.ShowNotification("~r~Stopped fishing")
end
end
if pausetimer > 3 then
input = 99
end
if pause and input ~= 0 then
pause = false
if input == correct then
TriggerServerEvent('fishing:catch', bait)
else
ESX.ShowNotification("~r~Fish got free")
end
end
end
if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), Config.SellFish.x, Config.SellFish.y, Config.SellFish.z, true) <= 3 then
TriggerServerEvent('fishing:startSelling', "fish")
Citizen.Wait(4000)
end
if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), Config.SellShark.x, Config.SellShark.y, Config.SellShark.z, true) <= 3 then
TriggerServerEvent('fishing:startSelling', "shark")
Citizen.Wait(4000)
end
if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), Config.SellTurtle.x, Config.SellTurtle.y, Config.SellTurtle.z, true) <= 3 then
TriggerServerEvent('fishing:startSelling', "turtle")
Citizen.Wait(4000)
end
end
end)
Citizen.CreateThread(function()
while true do
Wait(1)
DrawMarker(1, Config.SellFish.x, Config.SellFish.y, Config.SellFish.z , 0.0, 0.0, 0.0, 0, 0.0, 0.0, 3.0, 3.0, 2.0, 0, 70, 250, 30, false, true, 2, false, false, false, false)
DrawMarker(1, Config.SellTurtle.x, Config.SellTurtle.y, Config.SellTurtle.z , 0.0, 0.0, 0.0, 0, 0.0, 0.0, 3.0, 3.0, 2.0, 0, 70, 250, 30, false, true, 2, false, false, false, false)
DrawMarker(1, Config.SellShark.x, Config.SellShark.y, Config.SellShark.z, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 3.0, 3.0, 2.0, 0, 70, 250, 30, false, true, 2, false, false, false, false)
end
end)
Citizen.CreateThread(function()
while true do
local wait = math.random(Config.FishTime.a , Config.FishTime.b)
Wait(wait)
if fishing then
pause = true
correct = math.random(1,8)
ESX.ShowNotification("~g~Fish is taking the bait \n ~h~Press " .. correct .. " to catch it")
input = 0
pausetimer = 0
end
end
end)
RegisterNetEvent('fishing:message')
AddEventHandler('fishing:message', function(message)
ESX.ShowNotification(message)
end)
RegisterNetEvent('fishing:break')
AddEventHandler('fishing:break', function()
fishing = false
ClearPedTasks(GetPlayerPed(-1))
end)
RegisterNetEvent('fishing:spawnPed')
AddEventHandler('fishing:spawnPed', function()
RequestModel( GetHashKey( "A_C_SharkTiger" ) )
while ( not HasModelLoaded( GetHashKey( "A_C_SharkTiger" ) ) ) do
Citizen.Wait( 1 )
end
local pos = GetEntityCoords(GetPlayerPed(-1))
local ped = CreatePed(29, 0x06C3F072, pos.x, pos.y, pos.z, 90.0, true, false)
SetEntityHealth(ped, 0)
end)
RegisterNetEvent('fishing:setbait')
AddEventHandler('fishing:setbait', function(bool)
bait = bool
print(bait)
end)
RegisterNetEvent('fishing:fishstart')
AddEventHandler('fishing:fishstart', function()
playerPed = GetPlayerPed(-1)
local pos = GetEntityCoords(GetPlayerPed(-1))
print('started fishing' .. pos)
if IsPedInAnyVehicle(playerPed) then
ESX.ShowNotification("~y~You can not fish from a vehicle")
else
if pos.y >= 7700 or pos.y <= -4000 or pos.x <= -3700 or pos.x >= 4300 then
ESX.ShowNotification("~g~Fishing started")
TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_STAND_FISHING", 0, true)
fishing = true
else
ESX.ShowNotification("~y~You need to go further away from the shore")
end
end
end, false)
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
for k in pairs(Config.MarkerZones) do
local ped = PlayerPedId()
local pedcoords = GetEntityCoords(ped, false)
local distance = Vdist(pedcoords.x, pedcoords.y, pedcoords.z, Config.MarkerZones[k].x, Config.MarkerZones[k].y, Config.MarkerZones[k].z)
if distance <= 1.40 then
DisplayHelpText('Press E to rent a boat')
if IsControlJustPressed(0, Keys['E']) and IsPedOnFoot(ped) then
OpenBoatsMenu(Config.MarkerZones[k].xs, Config.MarkerZones[k].ys, Config.MarkerZones[k].zs)
end
elseif distance < 1.45 then
ESX.UI.Menu.CloseAll()
end
end
end
end)
function OpenBoatsMenu(x, y , z)
local ped = PlayerPedId()
PlayerData = ESX.GetPlayerData()
local elements = {}
table.insert(elements, {label = '<span style="color:green;">Dinghy</span> <span style="color:red;">2500$</span>', value = 'boat'})
table.insert(elements, {label = '<span style="color:green;">Suntrap</span> <span style="color:red;">3500$</span>', value = 'boat6'})
table.insert(elements, {label = '<span style="color:green;">Jetmax</span> <span style="color:red;">4500$</span>', value = 'boat5'})
table.insert(elements, {label = '<span style="color:green;">Toro</span> <span style="color:red;">5500$</span>', value = 'boat2'})
table.insert(elements, {label = '<span style="color:green;">Marquis</span> <span style="color:red;">6000$</span>', value = 'boat3'})
table.insert(elements, {label = '<span style="color:green;">Tug boat</span> <span style="color:red;">7500$</span>', value = 'boat4'})
--If user has police job they will be able to get free Police Predator boat
if PlayerData.job.name == "police" then
table.insert(elements, {label = '<span style="color:green;">Police Predator</span>', value = 'police'})
end
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open(
'default', GetCurrentResourceName(), 'client',
{
title = 'Rent a boat',
align = 'bottom-right',
elements = elements,
},
function(data, menu)
if data.current.value == 'boat' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 2500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 2500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "dinghy4")
end
if data.current.value == 'boat2' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 5500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 5500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "TORO")
end
if data.current.value == 'boat3' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 6000)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 6000)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "MARQUIS")
end
if data.current.value == 'boat4' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 7500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 7500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "tug")
end
if data.current.value == 'boat5' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 4500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 4500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "jetmax")
end
if data.current.value == 'boat6' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 3500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 3500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "suntrap")
end
if data.current.value == 'police' then
ESX.UI.Menu.CloseAll()
TriggerEvent("chatMessage", 'You took out a boat')
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "predator")
end
ESX.UI.Menu.CloseAll()
end,
function(data, menu)
menu.close()
end
)
end
| 12,118
|
Proof93/Zero2HeroRP_ESX
|
local utils = require("rust-tools.utils.utils")
local util = vim.lsp.util
local config = require("rust-tools.config")
local M = {}
local function get_params()
return vim.lsp.util.make_position_params()
end
M._state = { winnr = nil, commands = nil }
local set_keymap_opt = { noremap = true, silent = true }
-- run the command under the cursor, if the thing under the cursor is not the
-- command then do nothing
function M._run_command()
local line = vim.api.nvim_win_get_cursor(M._state.winnr)[1]
if line > #M._state.commands then
return
end
local action = M._state.commands[line]
M._close_hover()
M.execute_rust_analyzer_command(action)
end
function M.execute_rust_analyzer_command(action)
local fn = vim.lsp.commands[action.command]
if fn then
fn(action)
end
end
function M._close_hover()
if M._state.winnr ~= nil then
vim.api.nvim_win_close(M._state.winnr, true)
end
end
local function parse_commands()
local prompt = {}
for i, value in ipairs(M._state.commands) do
if value.command == "rust-analyzer.gotoLocation" then
table.insert(
prompt,
string.format("%d. Go to %s (%s)", i, value.title, value.tooltip)
)
elseif value.command == "rust-analyzer.showReferences" then
table.insert(prompt, string.format("%d. %s", i, "Go to " .. value.title))
else
table.insert(prompt, string.format("%d. %s", i, value.title))
end
end
return prompt
end
function M.handler(_, result)
if not (result and result.contents) then
-- return { 'No information available' }
return
end
local markdown_lines = util.convert_input_to_markdown_lines(result.contents)
if result.actions then
M._state.commands = result.actions[1].commands
local prompt = parse_commands()
local l = {}
for _, value in ipairs(prompt) do
table.insert(l, value)
end
markdown_lines = vim.list_extend(l, markdown_lines)
end
markdown_lines = util.trim_empty_lines(markdown_lines)
if vim.tbl_isempty(markdown_lines) then
-- return { 'No information available' }
return
end
local bufnr, winnr = util.open_floating_preview(
markdown_lines,
"markdown",
vim.tbl_extend("keep", config.options.tools.hover_actions, {
focusable = true,
focus_id = "rust-tools-hover-actions",
close_events = { "CursorMoved", "BufHidden", "InsertCharPre" },
})
)
if config.options.tools.hover_actions.auto_focus then
vim.api.nvim_set_current_win(winnr)
end
if M._state.winnr ~= nil then
return
end
-- update the window number here so that we can map escape to close even
-- when there are no actions, update the rest of the state later
M._state.winnr = winnr
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"<Esc>",
":lua require'rust-tools.hover_actions'._close_hover()<CR>",
set_keymap_opt
)
vim.api.nvim_buf_attach(bufnr, false, {
on_detach = function()
M._state.winnr = nil
end,
})
--- stop here if there are no possible actions
if result.actions == nil then
return
end
-- makes more sense in a dropdown-ish ui
vim.api.nvim_win_set_option(winnr, "cursorline", true)
-- run the command under the cursor
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"<CR>",
":lua require'rust-tools.hover_actions'._run_command()<CR>",
set_keymap_opt
)
-- close on escape
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"<Esc>",
":lua require'rust-tools.hover_actions'._close_hover()<CR>",
set_keymap_opt
)
end
-- Sends the request to rust-analyzer to get hover actions and handle it
function M.hover_actions()
utils.request(0, "textDocument/hover", get_params(), M.handler)
end
return M
| 3,734
|
zmtq05/rust-tools.nvim
|
local Tunnel = module("vrp","lib/Tunnel")
local Proxy = module("vrp","lib/Proxy")
vRP = Proxy.getInterface("vRP")
--[ ARRAY ]------------------------------------------------------------------------------------------------------------------------------
local valores = {
{ item = "cafe", quantidade = 1, compra = 8 },
{ item = "cafecleite", quantidade = 1, compra = 10 },
{ item = "cafeexpresso", quantidade = 1, compra = 14 },
{ item = "capuccino", quantidade = 1, compra = 17 },
{ item = "frappuccino", quantidade = 1, compra = 18 },
{ item = "cha", quantidade = 1, compra = 9 },
{ item = "icecha", quantidade = 1, compra = 9 },
{ item = "sanduiche", quantidade = 1, compra = 12 },
{ item = "rosquinha", quantidade = 1, compra = 9 },
}
--[ COMPRAR ]----------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent("cafeteria-comprar")
AddEventHandler("cafeteria-comprar",function(item)
local source = source
local user_id = vRP.getUserId(source)
if user_id then
for k,v in pairs(valores) do
if item == v.item then
if vRP.getInventoryWeight(user_id)+vRP.getItemWeight(v.item)*v.quantidade <= vRP.getInventoryMaxWeight(user_id) then
local preco = parseInt(v.compra)
if preco then
if vRP.hasPermission(user_id,"ultimate.permissao") then
desconto = math.floor(preco*20/100)
pagamento = math.floor(preco-desconto)
elseif vRP.hasPermission(user_id,"platinum.permissao") then
desconto = math.floor(preco*15/100)
pagamento = math.floor(preco-desconto)
elseif vRP.hasPermission(user_id,"gold.permissao") then
desconto = math.floor(preco*10/100)
pagamento = math.floor(preco-desconto)
elseif vRP.hasPermission(user_id,"standard.permissao") then
desconto = math.floor(preco*5/100)
pagamento = math.floor(preco-desconto)
else
pagamento = math.floor(preco)
end
if vRP.tryPayment(user_id,parseInt(pagamento)) then
TriggerClientEvent("Notify",source,"sucesso","Comprou <b>"..parseInt(v.quantidade).."x "..vRP.itemNameList(v.item).."</b> por <b>$"..vRP.format(parseInt(pagamento)).." dólares</b>.")
vRP.giveInventoryItem(user_id,v.item,parseInt(v.quantidade))
else
TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.")
end
end
else
TriggerClientEvent("Notify",source,"negado","Espaço insuficiente.")
end
end
end
end
end)
| 2,503
|
brazucas/fivem-data
|
if mods['Krastorio2'] then
data:extend({
-- -- Basic science
{
type = "bool-setting",
name = "k2-automation-science-pack",
default_value = true,
setting_type = "startup",
order = "AA-AA-S1"
},
-- K2 extended science packs
{
type = "bool-setting",
name = "basic-tech-card",
default_value = true,
hidden = true,
forced_value = true,
setting_type = "startup",
order = "KK-K2-S1"
},
{
type = "bool-setting",
name = "matter-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S2"
},
{
type = "bool-setting",
name = "advanced-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S3"
},
{
type = "bool-setting",
name = "singularity-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S4"
}
})
end
| 1,061
|
RedRafe/science-not-invited
|
--------------------------------------------------------------------------------
-- config.lua
--------------------------------------------------------------------------------
local aspectRatio = display.pixelHeight / display.pixelWidth
application = {
content = {
width = aspectRatio > 1.5 and 800 or math.ceil(1200 / aspectRatio),
height = aspectRatio < 1.5 and 1200 or math.ceil(800 * aspectRatio),
scale = "letterBox",
fps = 60,
imageSuffix = {
["@2x"] = 1.3
}
}
}
| 487
|
GymbylCoding/CBEffects
|
--[[ Copyright (C) 2018 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
]]
local log = require 'common.log'
local asserts = require 'testing.asserts'
local test_runner = require 'testing.test_runner'
local function mockWriter(expectedText)
local writer = {
text = '',
expectedText = false,
messageWritten = false,
}
function writer:write(text)
if text == expectedText then
self.expectedText = true
end
self.text = self.text .. text
end
function writer:flush()
self.messageWritten = true
end
return writer
end
local tests = {}
function tests.info()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.info('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.info('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.WARN)
log.info('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.INFO)
log.info('Hello')
assert(writer.messageWritten and writer.expectedText)
local writer2 = mockWriter('Hello2')
log.setOutput(writer2)
log.setLogLevel(1)
log.info('Hello2')
assert(writer2.messageWritten and writer2.expectedText)
end
function tests.warn()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.warn('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.warn('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.WARN)
log.warn('Hello')
assert(writer.messageWritten and writer.expectedText)
local writer2 = mockWriter('Hello2')
log.setOutput(writer2)
log.setLogLevel(log.INFO)
log.warn('Hello2')
assert(writer2.messageWritten and writer2.expectedText)
end
function tests.error()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.error('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.error('Hello')
assert(writer.messageWritten and writer.expectedText)
local writer2 = mockWriter('Hello2')
log.setOutput(writer2)
log.setLogLevel(log.WARN)
log.error('Hello2')
assert(writer2.messageWritten and writer2.expectedText)
end
function tests.v()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.WARN)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.INFO)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(1)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(2)
log.v(2, 'Hello')
assert(writer.messageWritten and writer.expectedText)
end
function tests.infoToString()
local writer = mockWriter('25')
log.setOutput(writer)
log.setLogLevel(log.INFO)
log.info(25)
assert(writer.messageWritten and writer.expectedText)
end
return test_runner.run(tests)
| 3,962
|
xuyanbo03/lab
|
#!/usr/bin/env lua
return { -- MySQL
connect = {
name = 'MySQL-test',
user = 'luadbi',
pass = 'testing12345!!!',
},
encoding_test = {
{'unsigned', 12435212 },
{'unsigned', 463769 },
{'signed', 8574678 },
{'signed', -12435212 },
{'unsigned', 0 },
{'signed', 0 },
{'signed', 9998212 },
{'decimal(7,2)', 7653.25 },
{'decimal', 7635236 },
{'decimal(4,3)', 0.000 },
{'decimal(7,2)', -7653.25 },
{'decimal(9,5)', 1636.94783 },
{'char', "string 1" },
{'char(14)', "another_string" },
{'char', "really long string with some escapable chars: #&*%#;@'" },
},
placeholder = '?',
have_last_insert_id = false,
have_typecasts = true,
have_booleans = false,
have_rowcount = true
}
| 835
|
moteus/lua-odbc-dbi
|
---------------------------------------------------------------------------------------------------
-- User story: https://github.com/smartdevicelink/sdl_requirements/issues/2
-- Use case: https://github.com/smartdevicelink/sdl_requirements/blob/master/detailed_docs/current_module_status_data.md
-- Item: Use Case 1: Main Flow
--
-- Requirement summary:
-- [SDL_RC] Current module status data GetInteriorVehicleData
-- [SDL_RC] Policy support of basic RC functionality
--
-- Description:
-- In case:
-- 1) "moduleType" in app's assigned policies has an empty array
-- 2) and RC app sends GetInteriorVehicleData request with valid parameters
-- SDL must:
-- 1) Allow this RPC to be processed
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local json = require('modules/json')
local common = require("test_scripts/RC/commonRC")
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
local function PTUfunc(tbl)
local appId = config.application1.registerAppInterfaceParams.fullAppID
tbl.policy_table.app_policies[appId] = common.getRCAppConfig()
tbl.policy_table.app_policies[appId].moduleType = json.EMPTY_ARRAY
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions, { false })
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("RAI", common.registerApp)
runner.Step("PTU", common.policyTableUpdate, { PTUfunc })
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
for _, mod in pairs(common.modulesWithoutSeat) do
runner.Step("GetInteriorVehicleData " .. mod, common.rpcAllowed, { mod, 1, "GetInteriorVehicleData" })
end
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
| 1,872
|
ychernysheva/sdl_atf_test_scripts
|
--[[
desc:
* Container, be responsible for saving object.
* CAREFULLY: Container isn't object's upper, it doesn't manage object.
author: Musoucrow
since: 2018-3-11
alter: 2019-8-19
]]--
---@param start int @defalut=1
local function _RefreshTransfer(self, start)
start = start or 1
for n=start, #self._transfer.list do
self._transfer.map[self._transfer.list[n]] = n
end
end
---@param tag string
---@param order int
local function _Remove(self, tag, order)
table.remove(self._list, order)
table.remove(self._transfer.list, order)
if (tag) then
self._map[tag] = nil
self._transfer.map[tag] = nil
end
_RefreshTransfer(self, order)
end
---@class Core.Container
---@field public _list list
---@field public _map map
---@field protected _transfer Core.Container.Transfer
---@field protected _willClean boolean
local _Container = require("core.class")()
function _Container:Ctor()
self._list = {}
self._map = {}
---@class Core.Container.Transfer
self._transfer = {
list = {},
map = {}
}
self._willClean = false
end
---@param name string
function _Container:RunEvent_All(name, ...)
for n in ipairs(self._list) do
self._list[n][name](self._list[n], ...)
end
end
---@param tag string
---@param name string
function _Container:RunEvent_Member(tag, name, ...)
self._map[tag][name](self._map[tag], ...)
end
---@param obj table
---@param tag string
---@param order int
function _Container:Add(obj, tag, order)
if (tag and self._map[tag]) then
self:Del(tag)
end
local max = #self._list + 1
order = order or max
if (order > max) then
order = max
end
table.insert(self._list, order, obj)
if (tag) then
table.insert(self._transfer.list, order, tag)
self._map[tag] = obj
end
_RefreshTransfer(self, order)
end
---@param tag string
function _Container:Del(tag)
local order = self._transfer.map[tag]
if (order) then
_Remove(self, tag, order)
end
end
function _Container:DelWithIndex(index)
local tag = self._transfer.list[index]
if (tag) then
_Remove(self, tag, index)
end
end
---@param tag string
---@return table
function _Container:Get(tag)
return self._map[tag]
end
function _Container:GetWithIndex(index)
return self._list[index]
end
---@return int
function _Container:GetLength()
return #self._list
end
function _Container:Iter()
local index = 0
return function()
index = index + 1
return self._list[index], self._transfer.list[index], index
end
end
function _Container:Pairs()
return pairs(self._map)
end
---@param Func function
function _Container:Sort(Func)
for n=1, #self._list-1 do
for m=1, #self._list-n do
if (not Func(self._list[m], self._list[m+1])) then -- For compatibility with table.sort
local tmp = self._list[m]
self._list[m] = self._list[m+1]
self._list[m+1] = tmp
if (self._transfer.list[m] and self._transfer.list[m+1]) then
tmp = self._transfer.list[m]
self._transfer.list[m] = self._transfer.list[m+1]
self._transfer.list[m+1] = tmp
tmp = self._transfer.map[self._transfer.list[m]]
self._transfer.map[self._transfer.list[m]] = self._transfer.map[self._transfer.list[m+1]]
self._transfer.map[self._transfer.list[m+1]] = tmp
end
end
end
end
end
function _Container:TryClean()
if (self._willClean) then
for n=#self._list, 1, -1 do
if (self._list[n].HasDestroyed and self._list[n]:HasDestroyed()) then
_Remove(self, self._transfer.list[n], n)
end
end
self._willClean = not self._willClean
end
end
function _Container:ReadyClean()
self._willClean = true
end
function _Container:Print() --For test.
for n=1, #self._transfer.list do
print (self._transfer.list[n], self._transfer.map[self._transfer.list[n]])
end
end
function _Container:DelAll()
self._list = {}
self._map = {}
self._transfer = {
list = {},
map = {}
}
end
return _Container
| 3,848
|
LeomRonald/DFQ-Original
|
local assert = assert
do --- local
local a, b, c
a, b, c = 0, 1
assert(a == 0)
assert(b == 1)
assert(c == nil)
a, b = a+1, b+1, a+b
assert(a == 1)
assert(b == 2)
a, b, c = 0
assert(a == 0)
assert(b == nil)
assert(c == nil)
end
do --- global !private_G
a, b, c = 0, 1
assert(a == 0)
assert(b == 1)
assert(c == nil)
a, b = a+1, b+1, a+b
assert(a == 1)
assert(b == 2)
a, b, c = 0
assert(a == 0)
assert(b == nil)
assert(c == nil)
end
do --- local lhs in key on lhs
local a = {}
local i = 3
i, a[i] = i+1, 20
assert(i == 4)
assert(a[3] == 20)
end
do --- global lhs in key on lhs !private_G
a = {}
i = 3
i, a[i] = i+1, 20
assert(i == 4)
assert(a[3] == 20)
end
| 724
|
DemiMarie/LuaJIT-test-cleanup
|
-- Copyright © 2016 Silv3r <silv3r@proshine-bot.com>
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the LICENSE file for more details.
name = "Leveling: Route 20 (near Cinnabar)"
author = "Silv3r"
description = [[This script will train the first pokémon of your team.
It will also try to capture shinies by throwing pokéballs.
Start anywhere between Cinnabar Island and Route 20.
You need a pokémon with surf.]]
function onPathAction()
if isPokemonUsable(1) then
if getMapName() == "Pokecenter Cinnabar" then
moveToMap("Cinnabar Island")
elseif getMapName() == "Cinnabar Island" then
moveToMap("Route 20")
elseif getMapName() == "Route 20" then
moveToWater()
end
else
if getMapName() == "Route 20" then
moveToMap("Cinnabar Island")
elseif getMapName() == "Cinnabar Island" then
moveToMap("Pokecenter Cinnabar")
elseif getMapName() == "Pokecenter Cinnabar" then
usePokecenter()
end
end
end
function onBattleAction()
if isWildBattle() and isOpponentShiny() then
if useItem("Ultra Ball") or useItem("Great Ball") or useItem("Pokeball") then
return
end
end
if getActivePokemonNumber() == 1 then
return attack() or run() or sendUsablePokemon() or sendAnyPokemon()
else
return run() or attack() or sendUsablePokemon() or sendAnyPokemon()
end
end
| 1,430
|
liquid8796/ProScript
|
local tbTable = GameMain:GetMod("_SkillScript")
local tbSkill = tbTable:GetSkill("ZSZY")
function tbSkill:Cast(skilldef, from)
end
function tbSkill:Apply(skilldef, key, from)
end
function tbSkill:FightBodyApply(skilldef, fightbody, from)
if fightbody and fightbody.Npc then
local npc = fightbody.Npc
npc:AddModifier("ZSZY")
end
end
function tbSkill:MissileBomb(skilldef, pos, from)
end
function tbSkill:GetValueAddv(skilldef, fightbody, from)
return self.power
end
function tbSkill:FlyCheck(skilldef, keys, from)
return 0
end
| 574
|
xArshy/Skycoveringworld
|
--- ATLAS PARK
local spawnOnce = false
-- Called after MOTD for now.
function player_connected(id)
--Id is player entity Id
printDebug('player_connected Id: ' .. tostring(id))
Tasks.UpdateTasksForZone('Atlas Park')
Contacts.SpawnContacts('Atlas Park')
if spawnOnce == false then
--spinners gather location data
spinSpawners()
spinPersists()
spinCivilians()
spinCars()
--RandomSpawns attempt #x creations of the type (encounter is default)
RandomSpawn(45)
RandomSpawn(80, "Civilians")
RandomSpawn(30, "Cars")
spawnOnce = true
print("Initiating map auto-refresh")
MapInstance.SetOnTickCallback(contactsForZone.TimeCop.entityId, contactsForZone.TimeCop.onTickCallBack);
TimeCopMode(true, 45, 120)
end
return ''
end
function npc_added(id)
printDebug('npc_added Id: ' .. tostring(id))
Contacts.SpawnedContact(id)
-- Spawn next contact
Contacts.SpawnContacts('Atlas Park')
return ''
end
entity_interact = function(id, location)
Contacts.SetContactDialogsWithHeroName(heroName)
if location ~= nil then
printDebug("entity id " .. tostring(id) .. " location info: x: " .. tostring(location.x) .. " y: " .. tostring(location.y) .. " z: " .. tostring(location.z))
else
printDebug("entity id " .. tostring(id))
end
if(Contacts.OpenContactDialog(id) ~= true) then
-- Generic NPC
-- Create generic NPC message script for zone?
end
--[[ NPC chat message test
MapClientSession.npcMessage(client, 'Hello Hero!', id)
MapClientSession.npcMessage(client, 'What are you doing here?', id)
]]
return ""
end
dialog_button = function(id) -- Will be called if no callback is set
printDebug("No Callback set! ButtonId: " .. tostring(id))
return ""
end
contact_call = function(contactIndex)
printDebug("Contact Call. contactIndex: " .. tostring(contactIndex))
return ""
end
revive_ok = function(id)
printDebug("revive Ok. Entity: " .. tostring(id))
Character.respawn(client, 'Gurney'); -- Hospital
Player.Revive(0);
return "ok"
end
| 2,189
|
cat4hurricane/Segs
|
--[[
- util.lua
- Handy module containing various functions for game development in lua,
particularly with Love2D.
- Authored by Thomas Smallridge (sundowns)
- https://github.com/sundowns/lua-utils
MIT LICENSE
Copyright (c) 2011 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local meta = {
__index = function(table, key)
if key == "l" then
return rawget(table, "love")
elseif key == "m" then
return rawget(table, "maths")
elseif key == "t" then
return rawget(table, "table")
elseif key == "f" then
return rawget(table, "file")
elseif key == "d" then
return rawget(table, "debug")
elseif key == "s" then
return rawget(table, "string")
else
return rawget(table, key)
end
end;
}
local util = {}
util.love = {}
util.maths = {}
util.table = {}
util.file = {}
util.debug = {}
util.string = {}
setmetatable(util, meta)
---------------------- TABLES
function util.table.print(table, name)
print("==================")
if not table then
print("<EMPTY TABLE>")
return
end
if type(table) ~= "table" then
assert(false,"Attempted to print NON-TABLE TYPE: "..type(table))
return
end
if name then print("Printing table: " .. name) end
deepprint(table)
end
function deepprint(table, depth)
local d = depth or 0
local spacer = ""
for i=0,d do
spacer = spacer.." "
end
for k, v in pairs(table) do
if type(v) == "table" then
print(spacer.."["..k.."]:")
deepprint(v, d + 1)
else
print(spacer.."[" .. tostring(k) .. "]: " .. tostring(v))
end
end
end
function util.table.concat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- Recursively creates a copy of the given table.
-- Not my code, taken from: https://www.youtube.com/watch?v=dZ_X0r-49cw#t=9m30s
function util.table.copy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[util.table.copy(orig_key)] = util.table.copy(orig_value)
end
else
copy = orig
end
return copy
end
--sums two tables of numbers together
function util.table.sum (t1, t2)
local result = {}
for key, val in pairs(t1) do
result[key] = (result[key] or 0) + val
end
for key, val in pairs(t2) do
result[key] = (result[key] or 0) + val
end
return result
end;
---------------------- MATHS
function util.maths.roundToNthDecimal(num, n)
local mult = 10^(n or 0)
return math.floor(num * mult + 0.5) / mult
end
function util.maths.withinVariance(val1, val2, variance)
local diff = math.abs(val1 - val2)
if diff < variance then
return true
else
return false
end
end
function util.maths.clamp(val, min, max)
assert(min < max, "Minimum value must be less than maximum when clamping values.")
if min - val > 0 then
return min
end
if max - val < 0 then
return max
end
return val
end
function util.maths.midpoint(x1, y1, x2, y2)
assert(x1 and y1 and x2 and y2, "Received invalid input to util.maths.midpoint")
return (x2+x1)/2, (y2+y1)/2
end
function util.maths.jitterBy(value, spread)
assert(love, "This function uses love.math.random for the time being")
return value + love.math.random(-1*spread, spread)
end
--Taken from: https://love2d.org/wiki/HSV_color
function util.maths.HSVtoRGB255(hue, sat, val)
if sat <= 0 then return val,val,val end
local h, s, v = hue/256*6, sat/255, val/255
local c = v*s
local x = (1-math.abs((h%2)-1))*c
local m,r,g,b = (v-c), 0,0,0
if h < 1 then r,g,b = c,x,0
elseif h < 2 then r,g,b = x,c,0
elseif h < 3 then r,g,b = 0,c,x
elseif h < 4 then r,g,b = 0,x,c
elseif h < 5 then r,g,b = x,0,c
else r,g,b = c,0,x
end return (r+m)*255,(g+m)*255,(b+m)*255
end
--Taken from: https://love2d.org/wiki/HSV_color
function util.maths.HSVtoRGB(hue, sat, val)
if sat <= 0 then return val,val,val end
local h, s, v = hue/256*6, sat/255, val/255
local c = v*s
local x = (1-math.abs((h%2)-1))*c
local m,r,g,b = (v-c), 0,0,0
if h < 1 then r,g,b = c,x,0
elseif h < 2 then r,g,b = x,c,0
elseif h < 3 then r,g,b = 0,c,x
elseif h < 4 then r,g,b = 0,x,c
elseif h < 5 then r,g,b = x,0,c
else r,g,b = c,0,x
end return (r+m),(g+m),(b+m)
end
function util.maths.distanceBetween(x1, y1, x2, y2)
return math.sqrt(((x2 - x1)^2) + ((y2 - y1)^2))
end
---------------------- DEBUG
function util.debug.log(text)
if debug then
print(text)
end
end
---------------------- FILE
function util.file.exists(name)
if love then assert(false, "Not to be used in love games, use love.filesystem.getInfo") end
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
function util.file.getLuaFileName(url)
return string.gsub(url, ".lua", "")
end
---------------------- LOVE2D
function util.love.resetColour()
love.graphics.setColor(1,1,1,1)
end
function util.love.renderStats(x, y)
if not x then x = 0 end
if not y then y = 0 end
local stats = love.graphics.getStats()
love.graphics.print("texture memory (MB): ".. stats.texturememory / 1024 / 1024, x, y)
love.graphics.print("drawcalls: ".. stats.drawcalls, x, y+20)
love.graphics.print("canvasswitches: ".. stats.canvasswitches , x, y+40)
love.graphics.print("images loaded: ".. stats.images, x, y+60)
love.graphics.print("canvases loaded: ".. stats.canvases, x, y+80)
love.graphics.print("fonts loaded: ".. stats.fonts, x, y+100)
end
if not love then util.love = nil end
---------------------- STRING
function util.string.randomString(l)
if l < 1 then return nil end
local stringy=""
for i=1,l do
stringy=stringy..util.string.randomLetter()
end
return stringy
end
function util.string.randomLetter()
return string.char(math.random(97, 122));
end
return util
| 6,953
|
sundowns/grim-gamers
|
-- Copyright 2008 Yanira <forum-2008@email.de>
-- Licensed to the public under the Apache License 2.0.
require("nixio.fs")
m = Map("hd-idle", translate("HDD Idle"),
translate("HDD Idle is a utility program for spinning-down external " ..
"disks after a period of idle time."))
s = m:section(TypedSection, "hd-idle", translate("Settings"))
s.anonymous = true
s:option(Flag, "enabled", translate("Enable"))
disk = s:option(Value, "disk", translate("Disk"))
disk.rmempty = true
for dev in nixio.fs.glob("/dev/[sh]d[a-z]") do
disk:value(nixio.fs.basename(dev))
end
s:option(Value, "idle_time_interval", translate("Idle time")).default = 10
s.rmempty = true
unit = s:option(ListValue, "idle_time_unit", translate("Idle time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
unit.rmempty = true
return m
| 868
|
spiccinini/luci
|
shaders = require("core.shaders")
BaseEntity = require("entities.core.baseentity")
NPCBullet = require("entities.npcbullet")
Goomba = require("entities.core.goomba")
Gorilla = class("Gorilla", Goomba)
Gorilla.spritesheet = SpriteSheet:new("sprites/gorilla.png", 32, 32)
function Gorilla:initialize()
Goomba.initialize(self)
-- control variables
self.type = "NPC"
self.collisiongroup = "shared"
self.attackDelay = 0
self.reloadDelay = 1.5
self.clipsize = 3
self.cone = 40 -- in radians
self.health = 500 -- health
self.range = 250 -- range of attack
self.shootFacingPlayer = false -- shoot only facing player
self.canAim = false -- can it aim at the player?
self.stopBeforeShooting = true
self.bulletOffsetX = 20
self.bulletOffsetY = -12
-- no touchy
self.attackAnim = 0
end
function Gorilla:update(dt)
Goomba.update(self, dt)
if self.nextReload <= 0.3 and self.attackAnim <= 0 then
self.attackAnim = 0.75
end
self.attackAnim = self.attackAnim - dt
end
function Gorilla:draw()
self.anim = 7 + math.floor(love.timer.getTime() * 10)%6
if self.attackAnim > 0 then
local a = math.floor((1 - (self.attackAnim / 0.75)) * 7) % 7
self.anim = a
end
love.graphics.scale(2, 2)
love.graphics.scale(-self.ang, 1)
self.spritesheet:draw(self.anim, 0, -16, -21)
if self.lastDamaged > 0 then
love.graphics.setStencil(function ()
love.graphics.setShader(shaders.mask_effect)
self.spritesheet:draw(self.anim, 0, -16, -21)
love.graphics.setShader()
end)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.rectangle("fill", -16, -21, 32, 32)
love.graphics.setStencil()
end
end
return Gorilla
| 1,830
|
qwook/dpsht
|
--[[----------------------------------------------------------------------------
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
------------------------------------------------------------------------------]]
local tnt = require 'torchnet'
require 'donkey'
-- create an instance of DataSetJSON to make roidb and scoredb
-- that are passed to threads
local roidb, scoredb
do
local ds = loadDataSet(opt)
ds:loadROIDB(opt.best_proposals_number)
roidb, scoredb = ds.roidb, ds.scoredb
end
local loader = createTrainLoader(opt, roidb, scoredb, 1)
local bbox_regr = loader:setupData()
g_mean_std = bbox_regr
local opt = tnt.utils.table.clone(opt)
local function getIterator()
return tnt.ParallelDatasetIterator{
nthread = opt.nDonkeys,
init = function(idx)
require 'torchnet'
require 'donkey'
torch.manualSeed(opt.manualSeed + idx)
g_donkey_idx = idx
end,
closure = function()
local loaders = {}
for i=1,(opt.integral and opt.nDonkeys or 1) do
loaders[i] = createTrainLoader(opt, roidb, scoredb, i)
end
for i,v in ipairs(loaders) do
v.bbox_regr = bbox_regr
end
return tnt.ListDataset{
list = torch.range(1,opt.epochSize):long(),
load = function(idx)
return {loaders[torch.random(#loaders)]:sample()}
end,
}
end,
}
end
return getIterator
| 1,695
|
wanyenlo/multipathnet
|
-- @start
-- @namespace com.github.mounthuaguo.mongkeyking.lua
-- @version 0.1
-- @name Base64 Encode
-- @description Base64 encode and decode
-- @author heramerom
-- @type action
-- @action Copy With Base64 Encode
-- @action Copy With Base64 Decode
-- @action Replace With Base64 Encode
-- @action Replace With Base64 Decode
-- @action Output With Base64 Encode
-- @action Output With Base64 Decode
-- @require https://raw.githubusercontent.com/toastdriven/lua-base64/master/base64.lua
-- @end
function inputText()
local text = event.selectionModel.selectedText
if text == nil or text == '' then
toast.warn('Please select text')
return nil
end
return text
end
if menu == 'Copy With Base64 Encode' then
local text = inputText()
if not text then
return
end
clipboard.setContents(to_base64(text))
toast.info('Copied!')
end
if menu == 'Copy With Base64 Decode' then
local text = inputText()
if not text then
return
end
clipboard.setContents(from_base64(text))
toast.info('Copied!')
end
if menu == 'Replace With Base64 Encode' then
local text = inputText()
if not text then
return
end
event.document.replaceString(
action.selectionModel.selectionStart,
action.selectionModel.selectionEnd,
to_base64(text))
end
if menu == 'Replace With Base64 Decode' then
local text = inputText()
if not text then
return
end
event.document.replaceString(
action.selectionModel.selectionStart,
action.selectionModel.selectionEnd,
from_base64(text))
end
if menu == 'Output With Base64 Encode' then
local text = inputText()
if not text then
return
end
print(to_base64(text))
end
if menu == 'Output With Base64 Decode' then
local text = inputText()
if not text then
return
end
print(from_base64(text))
end
| 1,986
|
Mount-Huaguo/MonkeyKingScripts
|
local geezifylua = require('geezifylua')
local test_data = require('test_case')
describe('arabify', function()
it('should convert every geez number in the test data to its equivalent arab number', function()
for i,v in ipairs(test_data) do
print(v[2])
assert.equal(geezifylua.arabify.arabify(v[2]), v[1])
end
end)
end)
| 412
|
yilkalargaw/geezify-lua
|
include("shared.lua")
function ENT:Draw()
local ret = hook.Call("onDrawSpawnedWeapon", nil, self)
if ret ~= nil then return end
self:DrawModel()
if self.dt.amount == 1 then return end
local Pos = self:GetPos()
local Ang = self:GetAngles()
local text = FrenchRP.getPhrase("amount") .. self.dt.amount
surface.SetFont("HUDNumber5")
local TextWidth = surface.GetTextSize(text)
Ang:RotateAroundAxis(Ang:Forward(), 90)
cam.Start3D2D(Pos + Ang:Up(), Ang, 0.11)
draw.WordBox(2, 0, -40, text, "HUDNumber5", Color(140, 0, 0, 100), Color(255,255,255,255))
cam.End3D2D()
Ang:RotateAroundAxis(Ang:Right(), 180)
cam.Start3D2D(Pos + Ang:Up() * 3, Ang, 0.11)
draw.WordBox(2, -TextWidth, -40, text, "HUDNumber5", Color(140, 0, 0, 100), Color(255,255,255,255))
cam.End3D2D()
end
/*---------------------------------------------------------------------------
Create a shipment from a spawned_weapon
---------------------------------------------------------------------------*/
properties.Add("createShipment",
{
MenuLabel = "Create a shipment",
Order = 2002,
MenuIcon = "icon16/add.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then return false end
return ent.IsSpawnedWeapon
end,
Action = function(self, ent)
if not IsValid(ent) then return end
RunConsoleCommand("frenchrp", "makeshipment", ent:EntIndex())
end
})
/*---------------------------------------------------------------------------
Interface
---------------------------------------------------------------------------*/
FrenchRP.hookStub{
name = "onDrawSpawnedWeapon",
description = "Draw spawned weapons.",
realm = "Client",
parameters = {
{
name = "weapon",
description = "The weapon to perform drawing operations on.",
type = "Player"
}
},
returns = {
{
name = "value",
description = "Return a value to completely override drawing",
type = "any"
}
}
}
| 2,218
|
Sxcret/FrenchRP
|
WireLib = WireLib or {}
local pairs = pairs
local setmetatable = setmetatable
local rawget = rawget
local next = next
local IsValid = IsValid
local LocalPlayer = LocalPlayer
local Entity = Entity
local string = string
local hook = hook
-- extra table functions
-- Returns a noniterable version of tbl. So indexing still works, but pairs(tbl) won't find anything
-- Useful for hiding entity lookup tables, since Garrydupe uses util.TableToJSON, which crashes on tables with entity keys
function table.MakeNonIterable(tbl)
return setmetatable({}, { __index = tbl, __setindex = tbl})
end
-- Checks if the table is empty, it's faster than table.Count(Table) > 0
function table.IsEmpty(Table)
return (next(Table) == nil)
end
-- Compacts an array by rejecting entries according to cb.
function table.Compact(tbl, cb, n)
n = n or #tbl
local cpos = 1
for i = 1, n do
if cb(tbl[i]) then
tbl[cpos] = tbl[i]
cpos = cpos + 1
end
end
local new_n = cpos-1
while (cpos <= n) do
tbl[cpos] = nil
cpos = cpos + 1
end
end
-- I don't even know if I need this one.
-- HUD indicator needs this one
function table.MakeSortedKeys(tbl)
local result = {}
for k,_ in pairs(tbl) do table.insert(result, k) end
table.sort(result)
return result
end
-- works like pairs() except that it iterates sorted by keys.
-- criterion is optional and should be a function(a,b) returning whether a is less than b. (same as table.sort's criterions)
function pairs_sortkeys(tbl, criterion)
tmp = {}
for k,v in pairs(tbl) do table.insert(tmp,k) end
table.sort(tmp, criterion)
local iter, state, index, k = ipairs(tmp)
return function()
index,k = iter(state, index)
if index == nil then return nil end
return k,tbl[k]
end
end
-- sorts by values
function pairs_sortvalues(tbl, criterion)
local crit = criterion and
function(a,b)
return criterion(tbl[a],tbl[b])
end
or
function(a,b)
return tbl[a] < tbl[b]
end
tmp = {}
tbl = tbl or {}
for k,v in pairs(tbl) do table.insert(tmp,k) end
table.sort(tmp, crit)
local iter, state, index, k = ipairs(tmp)
return function()
index,k = iter(state, index)
if index == nil then return nil end
return k,tbl[k]
end
end
-- like ipairs, except it maps the value with mapfunction before returning.
function ipairs_map(tbl, mapfunction)
local iter, state, k = ipairs(tbl)
return function(state, k)
local v
k,v = iter(state, k)
if k == nil then return nil end
return k,mapfunction(v)
end, state, k
end
-- like pairs, except it maps the value with mapfunction before returning.
function pairs_map(tbl, mapfunction)
local iter, state, k = pairs(tbl)
return function(state, k)
local v
k,v = iter(state, k)
if k == nil then return nil end
return k,mapfunction(v)
end, state, k
end
-- end extra table functions
local table = table
local pairs_sortkeys = pairs_sortkeys
local pairs_sortvalues = pairs_sortvalues
local ipairs_map = ipairs_map
local pairs_map = pairs_map
--------------------------------------------------------------------------------
do -- containers
local function new(metatable, ...)
local tbl = {}
setmetatable(tbl, metatable)
local init = metatable.Initialize
if init then init(tbl, ...) end
return tbl
end
local function newclass(container_name)
meta = { new = new }
meta.__index = meta
WireLib.containers[container_name] = meta
return meta
end
WireLib.containers = { new = new, newclass = newclass }
do -- class deque
local deque = newclass("deque")
function deque:Initialize()
self.offset = 0
end
function deque:size()
return #self-self.offset
end
-- Prepends the given element.
function deque:unshift(value)
if offset < 1 then
-- TODO: improve
table.insert(self, 1, value)
return
end
self.offset = self.offset - 1
self[self.offset+1] = value
end
-- Removes the first element and returns it
function deque:shift()
--do return table.remove(self, 1) end
local offset = self.offset + 1
local ret = self[offset]
if not ret then self.offset = offset-1 return nil end
self.offset = offset
if offset > 127 then
for i = offset+1,#self-offset do
self[i-offset] = self[i]
end
for i = #self-offset+1,#self do
self[i-offset],self[i] = self[i],nil
end
self.offset = 0
end
return ret
end
-- Appends the given element.
function deque:push(value)
self[#self+1] = value
end
-- Removes the last element and returns it.
function deque:pop()
local ret = self[#self]
self[#self] = nil
return ret
end
-- Returns the last element.
function deque:top()
return self[#self]
end
-- Returns the first element.
function deque:bottom()
return self[self.offset+1]
end
end -- class deque
do -- class autocleanup
local autocleanup = newclass("autocleanup")
function autocleanup:Initialize(depth, parent, parentindex)
rawset(self, "depth", depth or 0)
rawset(self, "parent", parent)
rawset(self, "parentindex", parentindex)
rawset(self, "data", {})
end
function autocleanup:__index(index)
local data = rawget(self, "data")
local element = data[index]
if element then return element end
local depth = rawget(self, "depth")
if depth == 0 then return nil end
element = new(autocleanup, depth-1, self, index)
return element
end
function autocleanup:__newindex(index, value)
local data = rawget(self, "data")
local parent = rawget(self, "parent")
local parentindex = rawget(self, "parentindex")
if value ~= nil and not next(data) and parent then parent[parentindex] = self end
data[index] = value
if value == nil and not next(data) and parent then parent[parentindex] = nil end
end
function autocleanup:__pairs()
local data = rawget(self, "data")
return pairs(data)
end
pairs_ac = autocleanup.__pairs
end -- class autocleanup
end -- containers
--------------------------------------------------------------------------------
--[[ wire_addnotify: send notifications to the client
WireLib.AddNotify([ply, ]Message, Type, Duration[, Sound])
If ply is left out, the notification is sent to everyone. If Sound is left out, no sound is played.
On the client, only the local player can be notified.
]]
do
-- The following sounds can be used:
NOTIFYSOUND_NONE = 0 -- optional, default
NOTIFYSOUND_DRIP1 = 1
NOTIFYSOUND_DRIP2 = 2
NOTIFYSOUND_DRIP3 = 3
NOTIFYSOUND_DRIP4 = 4
NOTIFYSOUND_DRIP5 = 5
NOTIFYSOUND_ERROR1 = 6
NOTIFYSOUND_CONFIRM1 = 7
NOTIFYSOUND_CONFIRM2 = 8
NOTIFYSOUND_CONFIRM3 = 9
NOTIFYSOUND_CONFIRM4 = 10
if CLIENT then
local sounds = {
[NOTIFYSOUND_DRIP1 ] = "ambient/water/drip1.wav",
[NOTIFYSOUND_DRIP2 ] = "ambient/water/drip2.wav",
[NOTIFYSOUND_DRIP3 ] = "ambient/water/drip3.wav",
[NOTIFYSOUND_DRIP4 ] = "ambient/water/drip4.wav",
[NOTIFYSOUND_DRIP5 ] = "ambient/water/drip5.wav",
[NOTIFYSOUND_ERROR1 ] = "buttons/button10.wav",
[NOTIFYSOUND_CONFIRM1] = "buttons/button3.wav",
[NOTIFYSOUND_CONFIRM2] = "buttons/button14.wav",
[NOTIFYSOUND_CONFIRM3] = "buttons/button15.wav",
[NOTIFYSOUND_CONFIRM4] = "buttons/button17.wav",
}
function WireLib.AddNotify(ply, Message, Type, Duration, Sound)
if isstring(ply) then
Message, Type, Duration, Sound = ply, Message, Type, Duration
elseif ply ~= LocalPlayer() then
return
end
GAMEMODE:AddNotify(Message, Type, Duration)
if Sound and sounds[Sound] then surface.PlaySound(sounds[Sound]) end
end
net.Receive("wire_addnotify", function(netlen)
local Message = net.ReadString()
local Type = net.ReadUInt(8)
local Duration = net.ReadFloat()
local Sound = net.ReadUInt(8)
WireLib.AddNotify(LocalPlayer(), Message, Type, Duration, Sound)
end)
elseif SERVER then
NOTIFY_GENERIC = 0
NOTIFY_ERROR = 1
NOTIFY_UNDO = 2
NOTIFY_HINT = 3
NOTIFY_CLEANUP = 4
util.AddNetworkString("wire_addnotify")
function WireLib.AddNotify(ply, Message, Type, Duration, Sound)
if isstring(ply) then ply, Message, Type, Duration, Sound = nil, ply, Message, Type, Duration end
if ply && !ply:IsValid() then return end
net.Start("wire_addnotify")
net.WriteString(Message)
net.WriteUInt(Type or 0,8)
net.WriteFloat(Duration)
net.WriteUInt(Sound or 0,8)
if ply then net.Send(ply) else net.Broadcast() end
end
end
end -- wire_addnotify
--[[ wire_clienterror: displays Lua errors on the client
Usage: WireLib.ClientError("Hello", ply)
]]
if CLIENT then
net.Receive("wire_clienterror", function(netlen)
local message = net.ReadString()
print("sv: "..message)
local lines = string.Explode("\n", message)
for i,line in ipairs(lines) do
if i == 1 then
WireLib.AddNotify(line, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1)
else
WireLib.AddNotify(line, NOTIFY_ERROR, 7)
end
end
end)
elseif SERVER then
util.AddNetworkString("wire_clienterror")
function WireLib.ClientError(message, ply)
net.Start("wire_clienterror")
net.WriteString(message)
net.Send(ply)
end
end
function WireLib.ErrorNoHalt(message)
-- ErrorNoHalt clips messages to 512 characters, so chain calls if necessary
for i=1,#message, 511 do
ErrorNoHalt(message:sub(i,i+510))
end
end
--[[ wire_netmsg system
A basic framework for entities that should send newly connecting players data
Server requirements: ENT:Retransmit(ply) -- Should send all data to one player
Client requirements:
WireLib.netRegister(self) in ENT:Initialize()
ENT:Receive()
To send:
function ENT:Retransmit(ply)
WireLib.netStart(self) -- This automatically net.WriteEntity(self)'s
net.Write*...
WireLib.netEnd(ply) -- you can pass a Player or a table of players to only send to some clients, otherwise it broadcasts
end
To receive:
function ENT:Receive()
net.Read*...
end
To unregister: WireLib.netUnRegister(self) -- Happens automatically on entity removal
]]
if SERVER then
util.AddNetworkString("wire_netmsg_register")
util.AddNetworkString("wire_netmsg_registered")
function WireLib.netStart(self)
net.Start("wire_netmsg_registered")
net.WriteEntity(self)
end
function WireLib.netEnd(ply)
if ply then net.Send(ply) else net.Broadcast() end
end
net.Receive("wire_netmsg_register", function(netlen, ply)
local self = net.ReadEntity()
if IsValid(self) and self.Retransmit then self:Retransmit(ply) end
end)
elseif CLIENT then
function WireLib.netRegister(self)
net.Start("wire_netmsg_register") net.WriteEntity(self) net.SendToServer()
end
net.Receive("wire_netmsg_registered", function(netlen)
local self = net.ReadEntity()
if IsValid(self) and self.Receive then self:Receive() end
end)
end
--[[ wire_ports: client-side input/output names/types/descs
umsg format:
any number of the following:
Char start
start==0: break
start==-1: delete inputs
start==-2: delete outputs
start==-3: set eid
start==-4: connection state
start > 0:
Char amount
abs(amount)*3 strings describing name, type, desc
]]
-- Checks if the entity has wire ports.
-- Works for every entity that has wire in-/output.
-- Very important and useful for checks!
function WireLib.HasPorts(ent)
if (ent.IsWire) then return true end
if (ent.Base == "base_wire_entity") then return true end
-- Checks if the entity is in the list, it checks if the entity has self.in-/outputs too.
local In, Out = WireLib.GetPorts(ent)
if (In and (ent.Inputs or CLIENT)) then return true end
if (Out and (ent.Outputs or CLIENT)) then return true end
return false
end
if SERVER then
local INPUT,OUTPUT = 1,-1
local DELETE,PORT,LINK = 1,2,3
local ents_with_inputs = {}
local ents_with_outputs = {}
--local IOlookup = { [INPUT] = ents_with_inputs, [OUTPUT] = ents_with_outputs }
util.AddNetworkString("wire_ports")
timer.Create("Debugger.PoolTypeStrings",1,1,function()
if WireLib.Debugger and WireLib.Debugger.formatPort then
for typename,_ in pairs(WireLib.Debugger.formatPort) do util.AddNetworkString(typename) end -- Reduce bandwidth
end
end)
local queue = {}
function WireLib.GetPorts(ent)
local eid = ent:EntIndex()
return ents_with_inputs[eid], ents_with_outputs[eid]
end
function WireLib._RemoveWire(eid, DontSend) -- To remove the inputs without to remove the entity. Very important for IsWire checks!
local hasinputs, hasoutputs = ents_with_inputs[eid], ents_with_outputs[eid]
if hasinputs or hasoutputs then
ents_with_inputs[eid] = nil
ents_with_outputs[eid] = nil
if not DontSend then
net.Start("wire_ports")
net.WriteInt(-3, 8) -- set eid
net.WriteUInt(eid, 16) -- entity id
if hasinputs then net.WriteInt(-1, 8) end -- delete inputs
if hasoutputs then net.WriteInt(-2, 8) end -- delete outputs
net.WriteInt(0, 8) -- break
net.Broadcast()
end
end
end
hook.Add("EntityRemoved", "wire_ports", function(ent)
if not ent:IsPlayer() then
WireLib._RemoveWire(ent:EntIndex())
end
end)
function WireLib._SetInputs(ent, lqueue)
local queue = lqueue or queue
local eid = ent:EntIndex()
if not ents_with_inputs[eid] then ents_with_inputs[eid] = {} end
queue[#queue+1] = { eid, DELETE, INPUT }
for Name, CurPort in pairs_sortvalues(ent.Inputs, WireLib.PortComparator) do
local entry = { Name, CurPort.Type, CurPort.Desc or "" }
ents_with_inputs[eid][#ents_with_inputs[eid]+1] = entry
queue[#queue+1] = { eid, PORT, INPUT, entry, CurPort.Num }
end
for Name, CurPort in pairs_sortvalues(ent.Inputs, WireLib.PortComparator) do
WireLib._SetLink(CurPort, lqueue)
end
end
function WireLib._SetOutputs(ent, lqueue)
local queue = lqueue or queue
local eid = ent:EntIndex()
if not ents_with_outputs[eid] then ents_with_outputs[eid] = {} end
queue[#queue+1] = { eid, DELETE, OUTPUT }
for Name, CurPort in pairs_sortvalues(ent.Outputs, WireLib.PortComparator) do
local entry = { Name, CurPort.Type, CurPort.Desc or "" }
ents_with_outputs[eid][#ents_with_outputs[eid]+1] = entry
queue[#queue+1] = { eid, PORT, OUTPUT, entry, CurPort.Num }
end
end
function WireLib._SetLink(input, lqueue)
local ent = input.Entity
local num = input.Num
local state = input.SrcId and true or false
local queue = lqueue or queue
local eid = ent:EntIndex()
queue[#queue+1] = {eid, LINK, num, state}
end
local eid = 0
local numports, firstportnum, portstrings = {}, {}, {}
local function writeCurrentStrings()
-- Write the current (input or output) string information
for IO=OUTPUT,INPUT,2 do -- so, k= -1 and k= 1
if numports[IO] then
net.WriteInt(firstportnum[IO], 8) -- Control code for inputs/outputs is also the offset (the first port number we're writing over)
net.WriteUInt(numports[IO], 8) -- Send number of ports
net.WriteBit(IO==OUTPUT)
for i=1,numports[IO]*3 do net.WriteString(portstrings[IO][i] or "") end
numports[IO] = nil
end
end
end
local function writemsg(msg)
-- First write a signed int for the command code
-- Then sometimes write extra data specific to the command (type varies)
if msg[1] ~= eid then
eid = msg[1]
writeCurrentStrings() -- We're switching to talking about a different entity, lets send port information
net.WriteInt(-3,8)
net.WriteUInt(eid,16)
end
local msgtype = msg[2]
if msgtype == DELETE then
numports[msg[3]] = nil
net.WriteInt(msg[3] == INPUT and -1 or -2, 8)
elseif msgtype == PORT then
local _,_,IO,entry,num = unpack(msg)
if not numports[IO] then
firstportnum[IO] = num
numports[IO] = 0
portstrings[IO] = {}
end
local i = numports[IO]*3
portstrings[IO][i+1] = entry[1]
portstrings[IO][i+2] = entry[2]
portstrings[IO][i+3] = entry[3]
numports[IO] = numports[IO]+1
elseif msgtype == LINK then
local _,_,num,state = unpack(msg)
net.WriteInt(-4, 8)
net.WriteUInt(num, 8)
net.WriteBit(state)
end
end
local function FlushQueue(lqueue, ply)
// Zero these two for the writemsg function
eid = 0
numports = {}
net.Start("wire_ports")
for i=1,#lqueue do
writemsg(lqueue[i])
end
writeCurrentStrings()
net.WriteInt(0,8)
if ply then net.Send(ply) else net.Broadcast() end
end
hook.Add("Think", "wire_ports", function()
if not next(queue) then return end
FlushQueue(queue)
queue = {}
end)
hook.Add("PlayerInitialSpawn", "wire_ports", function(ply)
local lqueue = {}
for eid, entry in pairs(ents_with_inputs) do
WireLib._SetInputs(Entity(eid), lqueue)
end
for eid, entry in pairs(ents_with_outputs) do
WireLib._SetOutputs(Entity(eid), lqueue)
end
FlushQueue(lqueue, ply)
end)
elseif CLIENT then
local ents_with_inputs = {}
local ents_with_outputs = {}
net.Receive("wire_ports", function(netlen)
local eid = 0
local connections = {} -- In case any cmd -4's come in before link strings
while true do
local cmd = net.ReadInt(8)
if cmd == 0 then
break
elseif cmd == -1 then
ents_with_inputs[eid] = nil
elseif cmd == -2 then
ents_with_outputs[eid] = nil
elseif cmd == -3 then
eid = net.ReadUInt(16)
elseif cmd == -4 then
connections[#connections+1] = {eid, net.ReadUInt(8), net.ReadBit() ~= 0} -- Delay this process till after the loop
elseif cmd > 0 then
local entry
local amount = net.ReadUInt(8)
if net.ReadBit() ~= 0 then
-- outputs
entry = ents_with_outputs[eid]
if not entry then
entry = {}
ents_with_outputs[eid] = entry
end
else
-- inputs
entry = ents_with_inputs[eid]
if not entry then
entry = {}
ents_with_inputs[eid] = entry
end
end
local endindex = cmd+amount-1
for i = cmd,endindex do
entry[i] = {net.ReadString(), net.ReadString(), net.ReadString()}
end
end
end
for i=1, #connections do
local eid, num, state = unpack(connections[i])
local entry = ents_with_inputs[eid]
if not entry then
entry = {}
ents_with_inputs[eid] = entry
elseif entry[num] then
entry[num][4] = state
end
end
end)
function WireLib.GetPorts(ent)
local eid = ent:EntIndex()
return ents_with_inputs[eid], ents_with_outputs[eid]
end
function WireLib._RemoveWire(eid) -- To remove the inputs without to remove the entity.
ents_with_inputs[eid] = nil
ents_with_outputs[eid] = nil
end
local flag = false
function WireLib.TestPorts()
flag = not flag
if flag then
local lasteid = 0
hook.Add("HUDPaint", "wire_ports_test", function()
local ent = LocalPlayer():GetEyeTraceNoCursor().Entity
--if not ent:IsValid() then return end
local eid = IsValid(ent) and ent:EntIndex() or lasteid
lasteid = eid
local text = "ID "..eid.."\nInputs:\n"
for num,name,tp,desc,connected in ipairs_map(ents_with_inputs[eid] or {}, unpack) do
text = text..(connected and "-" or " ")
text = text..string.format("%s (%s) [%s]\n", name, tp, desc)
end
text = text.."\nOutputs:\n"
for num,name,tp,desc in ipairs_map(ents_with_outputs[eid] or {}, unpack) do
text = text..string.format("%s (%s) [%s]\n", name, tp, desc)
end
draw.DrawText(text,"Trebuchet24",10,300,Color(255,255,255,255),0)
end)
else
hook.Remove("HUDPaint", "wire_ports_test")
end
end
end
-- For transmitting the yellow lines showing links between controllers and ents, as used by the Adv Entity Marker
if SERVER then
util.AddNetworkString("WireLinkedEnts")
function WireLib.SendMarks(controller, marks)
if not IsValid(controller) or not (controller.Marks or marks) then return end
net.Start("WireLinkedEnts")
net.WriteEntity(controller)
net.WriteUInt(#(controller.Marks or marks), 16)
for k,v in pairs(controller.Marks or marks) do
net.WriteEntity(v)
end
net.Broadcast()
end
else
net.Receive("WireLinkedEnts", function(netlen)
local Controller = net.ReadEntity()
if IsValid(Controller) then
Controller.Marks = {}
for i=1, net.ReadUInt(16) do
local link = net.ReadEntity()
if IsValid(link) then
table.insert(Controller.Marks, link)
end
end
end
end)
end
--[[
Returns the "distance" between two strings
ie the amount of character swaps you have to do to get the first string to equal the second
Example:
levenshtein( "test", "toast" ) returns 2, because two steps: 'e' swapped to 'o', and 'a' is added
Very useful for searching algorithms
Used by custom spawn menu search & gate tool search, for example
Credits go to: http://lua-users.org/lists/lua-l/2009-07/msg00461.html
]]
function WireLib.levenshtein( s, t )
local d, sn, tn = {}, #s, #t
local byte, min = string.byte, math.min
for i = 0, sn do d[i * tn] = i end
for j = 0, tn do d[j] = j end
for i = 1, sn do
local si = byte(s, i)
for j = 1, tn do
d[i*tn+j] = min(d[(i-1)*tn+j]+1, d[i*tn+j-1]+1, d[(i-1)*tn+j-1]+(si == byte(t,j) and 0 or 1))
end
end
return d[#d]
end
--[[
nicenumber
by Divran
Adds several functions to format numbers into millions, billions, etc
Adds a function to format a number (assumed seconds) into a duration (weeks, days, hours, minutes, seconds, etc)
This is used, for example, by the wire screen.
]]
WireLib.nicenumber = {}
local nicenumber = WireLib.nicenumber
local numbers = {
{
name = "septillion",
short = "sep",
symbol = "Y",
prefix = "yotta",
zeroes = 10^24,
},
{
name = "sextillion",
short = "sex",
symbol = "Z",
prefix = "zetta",
zeroes = 10^21,
},
{
name = "quintillion",
short = "quint",
symbol = "E",
prefix = "exa",
zeroes = 10^18,
},
{
name = "quadrillion",
short = "quad",
symbol = "P",
prefix = "peta",
zeroes = 10^15,
},
{
name = "trillion",
short = "T",
symbol = "T",
prefix = "tera",
zeroes = 10^12,
},
{
name = "billion",
short = "B",
symbol = "B",
prefix = "giga",
zeroes = 10^9,
},
{
name = "million",
short = "M",
symbol = "M",
prefix = "mega",
zeroes = 10^6,
},
{
name = "thousand",
short = "K",
symbol = "K",
prefix = "kilo",
zeroes = 10^3
}
}
local one = {
name = "ones",
short = "",
symbol = "",
prefix = "",
zeroes = 1
}
-- returns a table of tables that inherit from the above info
local floor = math.floor
local min = math.min
function nicenumber.info( n, steps )
if not n or n < 0 then return {} end
if n > 10 ^ 300 then n = 10 ^ 300 end
local t = {}
steps = steps or #numbers
local displayones = true
local cursteps = 0
for i = 1, #numbers do
local zeroes = numbers[i].zeroes
local nn = floor(n / zeroes)
if nn > 0 then
cursteps = cursteps + 1
if cursteps > steps then break end
t[#t+1] = setmetatable({value = nn},{__index = numbers[i]})
n = n % numbers[i].zeroes
displayones = false
end
end
if n >= 0 and displayones then
t[#t+1] = setmetatable({value = n},{__index = one})
end
return t
end
local sub = string.sub
-- returns string
-- example 12B 34M
function nicenumber.format( n, steps )
local t = nicenumber.info( n, steps )
steps = steps or #numbers
local str = ""
for i=1,#t do
if i > steps then break end
str = str .. t[i].value .. t[i].symbol .. " "
end
return sub( str, 1, -2 ) -- remove trailing space
end
-- returns string with decimals
-- example 12.34B
local round = math.Round
function nicenumber.formatDecimal( n, decimals )
local t = nicenumber.info( n, 1 )
decimals = decimals or 2
local largest = t[1]
if largest then
n = n / largest.zeroes
return round( n, decimals ) .. largest.symbol
else
return "0"
end
end
-------------------------
-- nicetime
-------------------------
local floor = math.floor
local times = {
{ "y", 31556926 }, -- years
{ "mon", 2629743.83 }, -- months
{ "w", 604800 }, -- weeks
{ "d", 86400 }, -- days
{ "h", 3600 }, -- hours
{ "m", 60 }, -- minutes
{ "s", 1 }, -- seconds
}
function nicenumber.nicetime( n )
n = math.abs( n )
if n == 0 then return "0s" end
local prev_name = ""
local prev_val = 0
for i=1,#times do
local name = times[i][1]
local num = times[i][2]
local temp = floor(n / num)
if temp > 0 or prev_name ~= "" then
if prev_name ~= "" then
return prev_val .. prev_name .. " " .. temp .. name
else
prev_name = name
prev_val = temp
n = n % num
end
end
end
if prev_name ~= "" then
return prev_val .. prev_name
else
return "0s"
end
end
| 24,256
|
Python1320/wire
|
-- https://github.com/windwp/nvim-autopairs
require("nvim-autopairs").setup()
| 78
|
brucelee07/nvim-config
|
--[[
# Copyright 2001-2014 Cisco Systems, Inc. and/or its affiliates. All rights
# reserved.
#
# This file contains proprietary Detector Content created by Cisco Systems,
# Inc. or its affiliates ("Cisco") and is distributed under the GNU General
# Public License, v2 (the "GPL"). This file may also include Detector Content
# contributed by third parties. Third party contributors are identified in the
# "authors" file. The Detector Content created by Cisco is owned by, and
# remains the property of, Cisco. Detector Content from third party
# contributors is owned by, and remains the property of, such third parties and
# is distributed under the GPL. The term "Detector Content" means specifically
# formulated patterns and logic to identify applications based on network
# traffic characteristics, comprised of instructions in source code or object
# code form (including the structure, sequence, organization, and syntax
# thereof), and all documentation related thereto that have been officially
# approved by Cisco. Modifications are considered part of the Detector
# Content.
--]]
--[[
detection_name: Minecraft
version: 1
description: Online game.
--]]
require "DetectorCommon"
local DC = DetectorCommon
local FT = flowTrackerModule
DetectorPackageInfo = {
name = "Minecraft",
proto = DC.ipproto.tcp,
client = {
init = 'client_init',
clean = 'client_clean',
validate = 'client_validate',
minimum_matches = 1
}
}
gSfAppIdMinecraft = 1802
gPatterns = {
init = { '\019\000\047\013', 0, gSfAppIdMinecraft},
second = { '\008\000\006\086\048\109\105\099\097', 0, gSfAppIdMinecraft}
}
gFastPatterns = {
{DC.ipproto.tcp, gPatterns.init},
}
gAppRegistry = {
--AppIdValue Extracts Info
---------------------------------------
{gSfAppIdMinecraft, 0}
}
--contains detector specific data related to a flow
flowTrackerTable = {}
function clientInProcess(context)
DC.printf('minecraft client: Inprocess Client, packetCount: %d\n', context.packetCount)
return DC.clientStatus.inProcess
end
function clientSuccess(context)
context.detectorFlow:setFlowFlag(DC.flowFlags.clientAppDetected)
DC.printf('minecraft client: Detected Client, packetCount: %d\n', context.packetCount)
gDetector:client_addApp(appServiceId, appTypeId, appProductId, "", gSfAppIdMinecraft);
return DC.clientStatus.success
end
function clientFail(context)
DC.printf('minecraft client: Failed Client, packetCount: %d\n', context.packetCount)
return DC.clientStatus.einvalid
end
--[[ Core engine calls DetectorInit() to initialize a detector.
--]]
function client_init( detectorInstance, configOptions)
gDetector = detectorInstance
DC.printf ('%s:DetectorInit()\n', DetectorPackageInfo.name)
gDetector:client_init()
appTypeId = 19
appProductId = 469
appServiceId = 20192
DC.printf ('%s:DetectorValidator(): appTypeId %d, product %d, service %d\n', DetectorPackageInfo.name, appTypeId, appProductId, appServiceId)
--register pattern based detection
for i,v in ipairs(gFastPatterns) do
if ( gDetector:client_registerPattern(v[1], v[2][1], #v[2][1], v[2][2], v[2][3]) ~= 0) then
DC.printf ('%s: register pattern failed for %s\n', DetectorPackageInfo.name,v[2][1])
else
DC.printf ('%s: register pattern successful for %s\n', DetectorPackageInfo.name,v[2][1])
end
end
for i,v in ipairs(gAppRegistry) do
pcall(function () gDetector:registerAppId(v[1],v[2]) end)
end
return gDetector
end
--[[Validator function registered in DetectorInit()
--]]
function client_validate()
local context = {}
context.detectorFlow = gDetector:getFlow()
context.packetCount = gDetector:getPktCount()
context.packetSize = gDetector:getPacketSize()
context.packetDir = gDetector:getPacketDir()
context.flowKey = context.detectorFlow:getFlowKey()
context.srcPort = gDetector:getPktSrcPort()
context.dstPort = gDetector:getPktDstPort()
local size = context.packetSize
local dir = context.packetDir
local flowKey = context.flowKey
DC.printf ('minecraft client packetCount %d dir %d, size %d\n', context.packetCount, dir, size)
local rft = FT.getFlowTracker(flowKey)
if (not rft) then
DC.printf ('minecraft client adding ft for flowKey %s\n', flowKey)
rft = FT.addFlowTracker(flowKey, {p=1})
end
if (rft.p == 1 and size >= 20) then
rft.p = 2
DC.printf ('minecraft client first packet\n')
return clientInProcess(context)
end
if (rft.p == 2 and
gDetector:memcmp(gPatterns.second[1], #gPatterns.second[1], gPatterns.second[2]) == 0) then
DC.printf ('got minecraft client\n')
FT.delFlowTracker(flowKey)
return clientSuccess(context)
end
FT.delFlowTracker(flowKey)
return clientFail(context)
end
function client_clean()
end
| 4,954
|
Snur/proxySSL
|
bristleback_bristleback_lua = class({})
LinkLuaModifier( "modifier_bristleback_bristleback_lua", "lua_abilities/bristleback_bristleback_lua/modifier_bristleback_bristleback_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Passive Modifier
function bristleback_bristleback_lua:GetIntrinsicModifierName()
return "modifier_bristleback_bristleback_lua"
end
| 422
|
GIANTCRAB/dota-2-lua-abilities
|
function onStepIn(cid, item, position, fromPosition)
level = 150
if getPlayerLevel(cid) < level then
doTeleportThing(cid, fromPosition, true)
doSendMagicEffect(getThingPos(cid), CONST_ME_MAGIC_RED)
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_RED, "Somente level " .. level .. " ou mais podem passar aqui.")
end
if item.actionid == 19456 then
end
return TRUE
end
| 384
|
Renanziinz/Otziinz
|
local K, C, L, _ = select(2, ...):unpack()
if C["Loot"].rolllootframe ~= true then return end
local unpack = unpack
local pairs = pairs
local time = time
local CreateFrame, UIParent = CreateFrame, UIParent
local IsShiftKeyDown = IsShiftKeyDown
local GetLootRollTimeLeft = GetLootRollTimeLeft
-- Based on teksLoot(by Tekkub)
local pos = "TOP"
local frames = {}
local cancelled_rolls = {}
local rolltypes = {"need", "greed", "disenchant", [0] = "pass"}
local LootRollAnchor = CreateFrame("Frame", "LootRollAnchor", UIParent)
LootRollAnchor:SetSize(313, 26)
local function ClickRoll(frame)
RollOnLoot(frame.parent.rollid, frame.rolltype)
end
local function HideTip() GameTooltip:Hide() end
local function HideTip2() GameTooltip:Hide() ResetCursor() end
local function SetTip(frame)
GameTooltip:SetOwner(frame, "ANCHOR_TOPLEFT")
GameTooltip:SetText(frame.tiptext)
if frame:IsEnabled() == 0 then GameTooltip:AddLine("|cffff3333"..L_LOOT_CANNOT) end
for name, roll in pairs(frame.parent.rolls) do if roll == rolltypes[frame.rolltype] then GameTooltip:AddLine(name, 1, 1, 1) end end
GameTooltip:Show()
end
local function SetItemTip(frame)
if not frame.link then return end
GameTooltip:SetOwner(frame, "ANCHOR_TOPLEFT")
GameTooltip:SetHyperlink(frame.link)
if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
if IsModifiedClick("DRESSUP") then ShowInspectCursor() else ResetCursor() end
end
local function ItemOnUpdate(self)
if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
CursorOnUpdate(self)
end
local function LootClick(frame)
if IsControlKeyDown() then DressUpItemLink(frame.link)
elseif IsShiftKeyDown() then ChatEdit_InsertLink(frame.link) end
end
local function OnEvent(frame, event, rollid)
cancelled_rolls[rollid] = true
if frame.rollid ~= rollid then return end
frame.rollid = nil
frame.time = nil
frame:Hide()
end
local function StatusUpdate(frame)
if not frame.parent.rollid then return end
local t = GetLootRollTimeLeft(frame.parent.rollid)
local perc = t / frame.parent.time
frame:SetValue(t)
end
local function CreateRollButton(parent, ntex, ptex, htex, rolltype, tiptext, ...)
local f = CreateFrame("Button", nil, parent)
f:SetPoint(...)
f:SetSize(28, 28)
f:SetNormalTexture(ntex)
if ptex then f:SetPushedTexture(ptex) end
f:SetHighlightTexture(htex)
f.rolltype = rolltype
f.parent = parent
f.tiptext = tiptext
f:SetScript("OnEnter", SetTip)
f:SetScript("OnLeave", HideTip)
f:SetScript("OnClick", ClickRoll)
f:SetMotionScriptsWhileDisabled(true)
local txt = f:CreateFontString(nil, nil)
txt:SetFont(C["Media"].Font, C["Media"].Font_Size, C["Media"].Font_Style)
txt:SetShadowOffset((K.Mult or 1), -(K.Mult or 1))
txt:SetPoint("CENTER", 0, rolltype == 2 and 1 or rolltype == 0 and -1.2 or 0)
return f, txt
end
local function CreateRollFrame()
local frame = CreateFrame("Frame", nil, UIParent)
K.CreateBorder(frame, 10, 2)
frame:SetBackdrop(K.BorderBackdrop)
frame:SetBackdropColor(unpack(C["Media"].Backdrop_Color))
frame:SetSize(280, 22)
frame:SetFrameStrata("MEDIUM")
frame:SetFrameLevel(10)
frame:SetScript("OnEvent", OnEvent)
frame:RegisterEvent("CANCEL_LOOT_ROLL")
frame:Hide()
local button = CreateFrame("Button", nil, frame)
button:SetPoint("LEFT", -29, 0)
button:SetSize(22, 22)
K.CreateBorder(button, 10, 2)
button:SetBackdrop(K.BorderBackdrop)
button:SetBackdropColor(unpack(C["Media"].Backdrop_Color))
button:SetScript("OnEnter", SetItemTip)
button:SetScript("OnLeave", HideTip2)
button:SetScript("OnUpdate", ItemOnUpdate)
button:SetScript("OnClick", LootClick)
frame.button = button
button.icon = button:CreateTexture(nil, "OVERLAY")
button.icon:SetAllPoints()
button.icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
local status = CreateFrame("StatusBar", nil, frame)
status:SetSize(326, 20)
status:SetPoint("TOPLEFT", 0, 0)
status:SetPoint("BOTTOMRIGHT", 0, 0)
status:SetScript("OnUpdate", StatusUpdate)
status:SetFrameLevel(status:GetFrameLevel() - 1)
status:SetStatusBarTexture(C["Media"].Texture)
status:SetStatusBarColor(0.8, 0.8, 0.8, 0.9)
status.parent = frame
frame.status = status
status.bg = status:CreateTexture(nil, "BACKGROUND")
status.bg:SetAlpha(0.1)
status.bg:SetAllPoints()
status.bg:SetDrawLayer("BACKGROUND", 2)
local need, needtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Dice-Up", "Interface\\Buttons\\UI-GroupLoot-Dice-Highlight", "Interface\\Buttons\\UI-GroupLoot-Dice-Down", 1, NEED, "LEFT", frame.button, "RIGHT", 5, -1)
local greed, greedtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Coin-Up", "Interface\\Buttons\\UI-GroupLoot-Coin-Highlight", "Interface\\Buttons\\UI-GroupLoot-Coin-Down", 2, GREED, "LEFT", need, "RIGHT", 0, -1)
local de, detext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-DE-Up", "Interface\\Buttons\\UI-GroupLoot-DE-Highlight", "Interface\\Buttons\\UI-GroupLoot-DE-Down", 3, ROLL_DISENCHANT, "LEFT", greed, "RIGHT", 0, -1)
local pass, passtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Pass-Up", nil, "Interface\\Buttons\\UI-GroupLoot-Pass-Down", 0, PASS, "LEFT", de or greed, "RIGHT", 0, 2.2)
frame.needbutt, frame.greedbutt, frame.disenchantbutt = need, greed, de
frame.need, frame.greed, frame.pass, frame.disenchant = needtext, greedtext, passtext, detext
local bind = frame:CreateFontString()
bind:SetPoint("LEFT", pass, "RIGHT", 3, 1)
bind:SetFont(C["Media"].Font, C["Media"].Font_Size, C["Media"].Font_Style)
bind:SetShadowOffset((K.Mult or 1), -(K.Mult or 1))
frame.fsbind = bind
local loot = frame:CreateFontString(nil, "ARTWORK")
loot:SetFont(C["Media"].Font, C["Media"].Font_Size, C["Media"].Font_Style)
loot:SetShadowOffset((K.Mult or 1), -(K.Mult or 1))
loot:SetPoint("LEFT", bind, "RIGHT", 0, 0)
loot:SetPoint("RIGHT", frame, "RIGHT", -5, 0)
loot:SetSize(200, 10)
loot:SetJustifyH("LEFT")
frame.fsloot = loot
frame.rolls = {}
return frame
end
local function GetFrame()
for i, f in ipairs(frames) do
if not f.rollid then return f end
end
local f = CreateRollFrame()
if pos == "TOP" then
f:SetPoint("TOPRIGHT", next(frames) and frames[#frames] or LootRollAnchor, "BOTTOMRIGHT", next(frames) and 0 or -2, next(frames) and -7 or -5)
else
f:SetPoint("BOTTOMRIGHT", next(frames) and frames[#frames] or LootRollAnchor, "TOPRIGHT", next(frames) and 0 or -2, next(frames) and 7 or 5)
end
table.insert(frames, f)
return f
end
local function START_LOOT_ROLL(rollid, time)
if cancelled_rolls[rollid] then return end
local f = GetFrame()
f.rollid = rollid
f.time = time
for i in pairs(f.rolls) do f.rolls[i] = nil end
f.need:SetText(0)
f.greed:SetText(0)
f.pass:SetText(0)
f.disenchant:SetText(0)
local texture, name, count, quality, bop, canNeed, canGreed, canDisenchant = GetLootRollItemInfo(rollid)
f.button.icon:SetTexture(texture)
f.button.link = GetLootRollItemLink(rollid)
if C["Loot"].auto_greed and K.Level == MAX_PLAYER_LEVEL and quality == 2 and not bop then return end
if canNeed then f.needbutt:Enable() else f.needbutt:Disable() end
if canGreed then f.greedbutt:Enable() else f.greedbutt:Disable() end
if canDisenchant then f.disenchantbutt:Enable() else f.disenchantbutt:Disable() end
SetDesaturation(f.needbutt:GetNormalTexture(), not canNeed)
SetDesaturation(f.greedbutt:GetNormalTexture(), not canGreed)
SetDesaturation(f.disenchantbutt:GetNormalTexture(), not canDisenchant)
if canNeed then f.needbutt:SetAlpha(1) else f.needbutt:SetAlpha(0.2) end
if canGreed then f.greedbutt:SetAlpha(1) else f.greedbutt:SetAlpha(0.2) end
if canDisenchant then f.disenchantbutt:SetAlpha(1) else f.disenchantbutt:SetAlpha(0.2) end
f.fsbind:SetText(bop and "BoP" or "BoE")
f.fsbind:SetVertexColor(bop and 1 or 0.3, bop and 0.3 or 1, bop and 0.1 or 0.3)
local color = ITEM_QUALITY_COLORS[quality]
f.fsloot:SetVertexColor(color.r, color.g, color.b)
f.fsloot:SetText(name)
f:SetBackdropBorderColor(color.r, color.g, color.b, 1)
f.button:SetBackdropBorderColor(color.r, color.g, color.b, 1)
f.status:SetStatusBarColor(color.r, color.g, color.b, 0.7)
f.status:SetMinMaxValues(0, time)
f.status:SetValue(time)
f:SetPoint("CENTER", WorldFrame, "CENTER")
f:Show()
end
local locale = GetLocale()
local rollpairs = locale == "deDE" and {
["(.*) passt automatisch bei (.+), weil [ersie]+ den Gegenstand nicht benutzen kann.$"] = "pass",
["(.*) würfelt nicht für: (.+|r)$"] = "pass",
["(.*) hat für (.+) 'Gier' ausgewählt"] = "greed",
["(.*) hat für (.+) 'Bedarf' ausgewählt"] = "need",
["(.*) hat für '(.+)' Entzauberung gewählt."] = "disenchant",
} or locale == "frFR" and {
["(.*) a passé pour : (.+) parce qu'((il)|(elle)) ne peut pas ramasser cette objet.$"] = "pass",
["(.*) a passé pour : (.+)"] = "pass",
["(.*) a choisi Cupidité pour : (.+)"] = "greed",
["(.*) a choisi Besoin pour : (.+)"] = "need",
["(.*) a choisi Désenchantement pour : (.+)"] = "disenchant",
} or locale == "zhTW" and {
["(.*)自動放棄:(.+),因為他無法拾取該物品$"] = "pass",
["(.*)自動放棄:(.+),因為她無法拾取該物品$"] = "pass",
["(.*)放棄了:(.+)"] = "pass",
["(.*)選擇了貪婪:(.+)"] = "greed",
["(.*)選擇了需求:(.+)"] = "need",
["(.*)選擇了分解:(.+)"] = "disenchant",
} or locale == "zhCN" and {
["(.*)自动放弃了(.+),因为他无法拾取该物品。$"] = "pass",
["(.*)放弃了:(.+)"] = "pass",
["(.*)选择了贪婪取向:(.+)"] = "greed",
["(.*)选择了需求取向:(.+)"] = "need",
["(.*)选择了分解取向:(.+)"] = "disenchant",
} or locale == "ruRU" and {
["(.*) автоматически передает предмет (.+), поскольку не может его забрать"] = "pass",
["(.*) пропускает розыгрыш предмета \"(.+)\", поскольку не может его забрать"] = "pass",
["(.*) отказывается от предмета (.+)%."] = "pass",
["Разыгрывается: (.+)%. (.*): \"Не откажусь\""] = "greed",
["Разыгрывается: (.+)%. (.*): \"Мне это нужно\""] = "need",
["Разыгрывается: (.+)%. (.*): \"Распылить\""] = "disenchant",
} or locale == "koKR" and {
["(.*)님이 획득할 수 없는 아이템이어서 자동으로 주사위 굴리기를 포기했습니다: (.+)"] = "pass",
["(.*)님이 주사위 굴리기를 포기했습니다: (.+)"] = "pass",
["(.*)님이 차비를 선택했습니다: (.+)"] = "greed",
["(.*)님이 입찰을 선택했습니다: (.+)"] = "need",
["(.*)님이 마력 추출을 선택했습니다: (.+)"] = "disenchant",
} or (locale == "esES" or locale == "esMX") and {
["^(.*) pasó automáticamente de: (.+) porque no puede despojar este objeto.$"] = "pass",
["^(.*) pasó de: (.+|r)$"] = "pass",
["(.*) eligió Codicia para: (.+)"] = "greed",
["(.*) eligió Necesidad para: (.+)"] = "need",
["(.*) eligió Desencantar para: (.+)"] = "disenchant",
} or locale == "ptBR" and {
["^(.*) abdicou de (.+) automaticamente porque não pode saquear o item.$"] = "pass",
["^(.*) dispensou: (.+|r)$"] = "pass",
["(.*) selecionou Ganância para: (.+)"] = "greed",
["(.*) escolheu Necessidade para: (.+)"] = "need",
["(.*) selecionou Desencantar para: (.+)"] = "disenchant",
} or {
["^(.*) automatically passed on: (.+) because s?he cannot loot that item.$"] = "pass",
["^(.*) passed on: (.+|r)$"] = "pass",
["(.*) has selected Greed for: (.+)"] = "greed",
["(.*) has selected Need for: (.+)"] = "need",
["(.*) has selected Disenchant for: (.+)"] = "disenchant",
}
local function ParseRollChoice(msg)
for i,v in pairs(rollpairs) do
local _, _, playername, itemname = string.find(msg, i)
if locale == "ruRU" and (v == "greed" or v == "need" or v == "disenchant") then
local temp = playername
playername = itemname
itemname = temp
end
if playername and itemname and playername ~= "Everyone" then return playername, itemname, v end
end
end
local function CHAT_MSG_LOOT(msg)
local playername, itemname, rolltype = ParseRollChoice(msg)
if playername and itemname and rolltype then
for _,f in ipairs(frames) do
if f.rollid and f.button.link == itemname and not f.rolls[playername] then
f.rolls[playername] = rolltype
f[rolltype]:SetText(tonumber(f[rolltype]:GetText()) + 1)
return
end
end
end
end
LootRollAnchor:RegisterEvent("ADDON_LOADED")
LootRollAnchor:SetScript("OnEvent", function(frame, event, addon)
if addon ~= "KkthnxUI" then return end
LootRollAnchor:UnregisterEvent("ADDON_LOADED")
LootRollAnchor:RegisterEvent("START_LOOT_ROLL")
LootRollAnchor:RegisterEvent("CHAT_MSG_LOOT")
UIParent:UnregisterEvent("START_LOOT_ROLL")
UIParent:UnregisterEvent("CANCEL_LOOT_ROLL")
LootRollAnchor:SetScript("OnEvent", function(frame, event, ...) if event == "CHAT_MSG_LOOT" then return CHAT_MSG_LOOT(...) else return START_LOOT_ROLL(...) end end)
LootRollAnchor:SetPoint(unpack(C["position"].group_loot))
end)
SlashCmdList.TESTROLL = function()
local f = GetFrame()
local items = {32837, 34196, 33820, 84004}
if f:IsShown() then
f:Hide()
else
local item = items[math.random(1, #items)]
local _, _, quality, _, _, _, _, _, _, texture = GetItemInfo(item)
local r, g, b = GetItemQualityColor(quality or 1)
f.button.icon:SetTexture(texture)
f.button.icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
f.fsloot:SetText(GetItemInfo(item))
f.fsloot:SetVertexColor(r, g, b)
f.status:SetMinMaxValues(0, 100)
f.status:SetValue(math.random(50, 90))
f.status:SetStatusBarColor(r, g, b, 0.9)
f.status.bg:SetTexture(r, g, b)
f:SetBackdropBorderColor(r, g, b, 0.9)
f.button:SetBackdropBorderColor(r, g, b, 0.9)
f.need:SetText(0)
f.greed:SetText(0)
f.pass:SetText(0)
f.disenchant:SetText(0)
f.button.link = "item:"..item..":0:0:0:0:0:0:0"
f:Show()
end
end
SLASH_TESTROLL1 = "/testroll"
SLASH_TESTROLL2 = "/tr"
| 13,310
|
mopd/KkthnxUI_WotLK
|
identitycontrols = {};
function setCurrent(name)
local idctrl = identitycontrols[name];
if idctrl then
-- Deactivate all identities
for k, v in pairs(identitycontrols) do
v.setCurrent(false);
end
-- Set active
idctrl.setCurrent(true);
end
end
function addIdentity(name, isgm)
local idctrl = identitycontrols[name];
-- Create control if not found
if not idctrl then
createControl("identitylistentry", "ctrl_" .. name);
idctrl = self["ctrl_" .. name];
identitycontrols[name] = idctrl;
idctrl.createLabel(name, isgm);
end
end
function removeIdentity(name)
local idctrl = identitycontrols[name];
if idctrl then
idctrl.destroy();
identitycontrols[name] = nil;
end
end
function renameGmIdentity(name)
for k,v in pairs(identitycontrols) do
if v.gmidentity then
v.rename(name);
identitycontrols[name] = v;
identitycontrols[k] = nil;
return;
end
end
end
function onInit()
GmIdentityManager.registerIdentityList(self);
end
| 1,047
|
sweetrpg/fantasy-grounds-genesys-ruleset
|
function TelekeneticBlobGetMarkedTarget(caster)
local ability = caster:FindAbilityByName("telekenetic_blob_mark_target")
if ability ~= nil then
return ability.lastCastTaget
end
return nil
end
function TelekeneticBlobFlySetup(modifier, fixedSpeed)
if modifier:ApplyHorizontalMotionController() == false or modifier:ApplyVerticalMotionController() == false then
modifier:Destroy()
return
end
modifier.vStartPosition = GetGroundPosition( modifier:GetParent():GetOrigin(), modifier:GetParent() )
modifier.vTargetPosition = modifier:GetAbility():GetCursorPosition()
modifier.flStartHeight = GetGroundHeight( modifier.vStartPosition, modifier:GetParent())
modifier.flTargetHeight = GetGroundHeight( modifier.vTargetPosition, modifier:GetParent())
modifier.flHeight = modifier:GetAbility():GetSpecialValueFor("fly_height")
modifier.vDirection = (modifier.vTargetPosition - modifier.vStartPosition):Normalized()
modifier.flDistance = (modifier.vTargetPosition - modifier.vStartPosition):Length2D()
if fixedSpeed then
modifier.flHorizontalSpeed = modifier:GetAbility():GetSpecialValueFor("fly_speed")
modifier.fDuration = modifier.flDistance / modifier:GetAbility():GetSpecialValueFor("fly_speed")
else
modifier.flHorizontalSpeed = modifier.flDistance / modifier:GetAbility():GetSpecialValueFor("fly_duration")
modifier.fDuration = modifier:GetAbility():GetSpecialValueFor("fly_duration")
end
EmitSoundOnLocationWithCaster(modifier.vStartPosition, "Ability.TossThrow", modifier:GetParent())
end
function TelekeneticBlobFlyTearDown(modifier)
if IsServer() then
modifier:GetParent():RemoveHorizontalMotionController(modifier)
modifier:GetParent():RemoveVerticalMotionController(modifier)
end
end
function TelekeneticBlobFlyUpdateHorizontal(me, dt, modifier)
if IsServer() then
local vOldPosition = me:GetOrigin()
local vNewPos = vOldPosition + modifier.vDirection * modifier.flHorizontalSpeed * dt
me:SetOrigin(vNewPos)
end
end
function TelekeneticBlobFlyUpdateVertical(me, dt, modifier, landingCallback)
if IsServer() then
local vOrigin = me:GetOrigin()
local vDistance = (vOrigin - modifier.vStartPosition):Length2D()
local vZ = (2*modifier.flTargetHeight-2*modifier.flStartHeight-4*modifier.flHeight)/(modifier.fDuration*modifier.fDuration) * (modifier:GetElapsedTime()*modifier:GetElapsedTime()) + (4*modifier.flHeight+modifier.flStartHeight-modifier.flTargetHeight) / modifier.fDuration * modifier:GetElapsedTime() + modifier.flStartHeight
vOrigin.z = vZ
local flGroundHeight = GetGroundHeight( vOrigin, modifier:GetParent() )
local bLanded = false
if (modifier:GetElapsedTime() >= modifier.fDuration) then
vOrigin.z = flGroundHeight
bLanded = true
end
me:SetOrigin(vOrigin)
if bLanded == true then
if landingCallback ~= nil then
landingCallback(modifier)
end
local pid = ParticleManager:CreateParticle("particles/econ/items/earthshaker/earthshaker_totem_ti6/earthshaker_totem_ti6_leap_impact.vpcf", PATTACH_ABSORIGIN, modifier:GetParent())
ParticleManager:SetParticleControl(pid, 0, me:GetOrigin())
ParticleManager:ReleaseParticleIndex(pid)
EmitSoundOnLocationWithCaster(modifier:GetParent():GetOrigin(), "Ability.TossImpact", modifier:GetParent())
modifier:GetParent():RemoveHorizontalMotionController(modifier)
modifier:GetParent():RemoveVerticalMotionController(modifier)
modifier:SetDuration(0.01, true)
end
end
end
modifier_telekenetic_blob = class({})
function modifier_telekenetic_blob:IsPurgable() return false end
function modifier_telekenetic_blob:IsHidden() return true end
function modifier_telekenetic_blob:RemoveOnDeath() return false end
function modifier_telekenetic_blob:DeclareFunctions() return {MODIFIER_PROPERTY_DISABLE_AUTOATTACK} end
function modifier_telekenetic_blob:GetDisableAutoAttack() return 1 end
function modifier_telekenetic_blob:CheckState()
return {[MODIFIER_STATE_DISARMED] = true}
end
| 4,240
|
GuChenGuYing/DOTA2-AI-Fun
|
-- 微信验证
-- 每个需要用到的服务都需要在启动的时候调wx.init
--
local http = require "bw.web.http_helper"
local sha256 = require "bw.auth.sha256"
local json = require "cjson.safe"
local map = {} -- appid -> access
local function request_access_token(appid, secret)
assert(appid and secret)
local ret, resp = http.get("https://api.weixin.qq.com/cgi-bin/token", {
grant_type = "client_credential",
appid = appid,
secret = secret,
})
if ret then
resp = json.decode(resp)
local access = {}
access.token = resp.access_token
access.exires_in = resp.expires_in
access.time = os.time()
map[appid] = access
else
error(resp)
end
end
local M = {}
function M.get_access_token(appid, secret)
assert(appid and secret)
local access = map[appid]
if not access or os.time() - access.time > access.exires_in then
request_access_token(appid, secret)
return map[appid]
end
return access.token
end
function M.check_code(appid, secret, js_code)
assert(appid and secret and js_code)
local ret, resp = http.get("https://api.weixin.qq.com/sns/jscode2session",{
js_code = js_code,
grant_type = "authorization_code",
appid = appid,
secret = secret,
})
if ret then
return json.decode(resp)
else
error(resp)
end
end
-- data {score = 100, gold = 300}
function M:set_user_storage(appid, secret, openid, session_key, data)
local kv_list = {}
for k, v in pairs(data) do
table.insert(kv_list, {key = k, value = v})
end
local post = json.encode({kv_list = kv_list})
local url = "https://api.weixin.qq.com/wxa/set_user_storage?"..http.url_encoding({
access_token = M.get_access_token(appid, secret),
openid = openid,
appid = appid,
signature = sha256.hmac_sha256(post, session_key),
sig_method = "hmac_sha256",
})
local ret, resp = http.post(url, post)
if ret then
return json.decode(resp)
else
error(resp)
end
end
-- key_list {"score", "gold"}
function M:remove_user_storage(appid, secret, openid, session_key, key_list)
local post = json.encode({key = key_list})
local url = "https://api.weixin.qq.com/wxa/remove_user_storage?"..http.url_encoding({
access_token = M.get_access_token(appid, secret),
openid = openid,
appid = appid,
signature = sha256.hmac_sha256(post, session_key),
sig_method = "hmac_sha256",
})
local ret, resp = http.post(url, post)
if ret then
return json.decode(resp)
else
error(resp)
end
end
return M
| 2,717
|
xiaozia/bewater
|
require("bin.npc")
require("bin.gstate")
require("bin.battlestate")
lvgp = lvgp or love.graphics
local val = 0
platform = {}
volume = 1
focusvar = love.window.hasMouseFocus()
scrw, scrh = lvgp.getDimensions()
function love.load()
minimx = 736
exitx = 768
guiRender = true
isPaused = false
Pausable = true
insertbool = insertbool or true
window_x, window_y, window_d = love.window.getPosition( )
window_w = 800
window_h = 500
window_scale = window_scale or 1
game_w = game_w or window_w
game_h = game_h or window_h
game_scale = game_scale or 1
esc_name = esc_name or 'def'
esc_addr = 'assets/gfx/esc/' .. tostring(esc_name)
banner = banner or lvgp.newImage(esc_addr .. '/banner.png')
minimize = minimize or lvgp.newImage(esc_addr .. '/min.png')
exitout = exitout or lvgp.newImage(esc_addr .. '/exit.png')
icon = icon or lvgp.newImage(esc_addr .. '/icon.png')
hpbar = hpbar or lvgp.newImage('assets/gfx/gui/btl/hp_bar.png')
bstate = Gstate.New("bstate")
currstate = bstate
npc1 = Npc.New(2)
npc1.desc = "An old man with a beard. His clothes seem otherworldly."
npc1:AArray(npc1, 1, "Hello there!")
npc1:AArray(npc1, 2, "Well, goodbye now!")
npc1.array = {"Look, it works!"}
titleicon = love.image.newImageData('assets/title.png')
canvas = bstate.canvas or lvgp.newCanvas(game_w*game_scale, game_h*game_scale,"normal",0)
canvas:setFilter( "nearest", "nearest" )
escvas = lvgp.newCanvas(window_w, window_h,"normal",0)
escvas:setFilter( "nearest", "nearest" )
love.window.setMode(window_w, window_h, {borderless=true, vsync=false})
bstate.load()
end
function love.update(dt)
--player.update()
function saveClose(exitmode)
local mode = exitmode or "save"
if mode == "save" then
local title = "Escape"
local message = "Are you sure you want to leave?"
local buttons = {"Yes","No",enterbutton = 2,escapebutton = 1}
local pressedbutton = love.window.showMessageBox(title, message, buttons)
if pressedbutton == 2 then
isPaused = false
elseif pressedbutton == 1 then
love.event.quit()
end
elseif mode == "exit" then
love.event.quit()
elseif mode == "reset" then
end
end
if focusvar == true then
--focusvar = 1
titleicon:paste(love.image.newImageData('assets/title.png'), 0, 0)
end
if focusvar == false then
--focusvar = 0
titleicon:paste(love.image.newImageData('assets/title1.png'), 0, 0)
end
h = h or 1
hh = hh or 1
rot = rot or 0
function love.keypressed(key)
if key == "insert" then
insertbool = not insertbool
love.mouse.setVisible(not love.mouse.isVisible())
guiRender = insertbool
end
if key == "home" then
love.window.setPosition(0,0,1)
end
if key == "r" then
h = h + 1
end
if key == "f" then
h = h - 1
end
if key == "t" then
hh = hh + 1
end
if key == "g" then
hh = hh - 1
end
if key == "y" then
rot = rot + 1/45
end
if key == "h" then
rot = rot - 1/45
end
if key == "escape" then
if Pausable == true then
isPaused = not isPaused
elseif isPaused == true then
isPaused = false
end
end
end
success = love.window.setIcon(titleicon)
bstate.update()
mx = tonumber(love.mouse.getX()/scrh*255)
my = tonumber(love.mouse.getY()/scrh*255)
if love.mouse.getY() <= banner:getHeight() and love.mouse.getY() <= 32 and isPaused == true then
bar_focus = true
end
if love.mouse.isDown(1) then
minitX = minitX or love.mouse.getX()
minitY = minitY or love.mouse.getY()
bar_focus = bar_focus or false
w_x,w_y= love.window.getPosition( )
if isPaused == true and bar_focus == true and (minitX ~= love.mouse.getX() or minitY ~= love.mouse.getY()) then
if love.window.hasMouseFocus() then
--love.mouse.setGrabbed(true)
love.window.setPosition( w_x-(minitX-love.mouse.getX()), w_y-(minitY-love.mouse.getY()),1)
end
else
love.mouse.setGrabbed(false)
end
else
if bar_focus == true then
minitX = love.mouse.getX()
minitY = love.mouse.getY()
if love.mouse.isGrabbed == true and isPaused == true then
love.mouse.setGrabbed(false)
end
end
end
function love.mousepressed(x, y, button, istouch)
if button == 1 then
if love.mouse.getX() > minimx and love.mouse.getX() < minimx + minimize:getWidth() and isPaused == true and love.mouse.getY() <= banner:getHeight() then
love.window.minimize()
bar_focus = false
end
if love.mouse.getX() > exitx and love.mouse.getX() < exitx + exitout:getWidth() and isPaused == true and love.mouse.getY() <= banner:getHeight() then
saveClose("exit")
bar_focus = false
end
end
end
end
function love.draw()
--player.draw()
lvgp.setBackgroundColor(0,0,0)
lvgp.setColor(255,255,255)
lvgp.setCanvas(canvas)
lvgp.setColor(love.mouse.getX(),10,10)
lvgp.rectangle("fill", 0, 0, game_w*game_scale, game_h*game_scale)
lvgp.setColor(255,255,255)
bstate.draw()
lvgp.circle('fill', love.mouse.getX(), love.mouse.getY(), h, hh)
lvgp.setCanvas()
if focusvar == true then
titleicon:paste(love.image.newImageData('assets/title.png'), 0, 0)
lvgp.print(esc_addr .. '/banner.png',16,16)
end
if focusvar == false then
titleicon:paste(love.image.newImageData('assets/title1.png'), 0, 0)
lvgp.print("npc.dialog[draw]: " .. tostring(npc1.array[1]), 16, 272)
end
lvgp.draw(canvas, 0, 0, rot, window_scale, window_scale)
lvgp.setCanvas(escvas)
if isPaused == true and Pausable == true then
if not pausebg then
lvgp.rectangle("fill",0,0,game_w*window_scale,game_h*window_scale)
else
lvgp.draw(pausebg,0,(banner:getHeight() or 32),window_scale)
end
lvgp.draw(banner,0,0,0,window_scale)
lvgp.draw(minimize,736*window_scale,0,0,window_scale)
lvgp.draw(exitout,768*window_scale,0,0,window_scale)
lvgp.draw(icon,0,0,0,window_scale)
end
lvgp.setCanvas()
if isPaused == true then
lvgp.draw(escvas, 0, 0, 0, window_scale, window_scale)
else
if insertbool == true then
edraw = lvgp.newQuad(10 + love.mouse.getX() / window_w * hpbar:getWidth(), 0, (1 - love.mouse.getX() / window_w) * hpbar:getWidth(), hpbar:getHeight(), hpbar:getWidth(), hpbar:getHeight())
gdraw = lvgp.newQuad(0, 0, love.mouse.getX() / window_w * hpbar:getWidth(), hpbar:getHeight(), hpbar:getWidth(), hpbar:getHeight())
lvgp.setColor(108,108,108,128)
drawe = lvgp.draw(hpbar, edraw, 310 + love.mouse.getX() / window_w * hpbar:getWidth(), 100)
drawg = lvgp.draw(hpbar, gdraw, 300, 100)
lvgp.setColor(158,158,158,255)
drawe = lvgp.draw(hpbar, edraw, 305 + love.mouse.getX() / window_w * hpbar:getWidth(), 90)
lvgp.setColor(255,255,255,255)
drawg = lvgp.draw(hpbar, gdraw, 295, 90)
lvgp.print("HP%: " .. tostring(love.mouse.getX() / window_w * hpbar:getWidth()),305,90)
end
end
end
| 6,845
|
Aggrotadpole/brack
|
#! /usr/bin/env lua
--
-- libtest-reflect-var.lua
-- Copyright (C) 2015 Adrian Perez <aperez@igalia.com>
--
-- Distributed under terms of the MIT license.
--
local libtest = require("eol").load("libtest")
assert.Not.Nil(libtest)
function check_variable(variable, expected_name, expected_readonly,
expected_type, expected_type_sizeof)
assert.Not.Nil(variable)
assert.Equal(expected_name, variable.__name)
assert.Equal(libtest, variable.__library)
assert.Match(expected_type, variable.__type.name)
assert.Equal(expected_readonly, variable.__type.readonly)
if expected_type_sizeof ~= nil then
assert.Equal(expected_type_sizeof, variable.__type.sizeof)
end
end
check_variable(libtest.const_int, "const_int", true, "int%d+_t")
check_variable(libtest.var_u16, "var_u16", false, "uint16_t", 2)
check_variable(libtest.intvar, "intvar", false, "int%d+_t")
| 879
|
aperezdc/eris
|
class "SkeletonAnimation"
function SkeletonAnimation:SkeletonAnimation(...)
local arg = {...}
for k,v in pairs(arg) do
if type(v) == "table" then
if v.__ptr ~= nil then
arg[k] = v.__ptr
end
end
end
if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then
self.__ptr = Polycode.SkeletonAnimation(unpack(arg))
end
end
function SkeletonAnimation:getName()
local retVal = Polycode.SkeletonAnimation_getName(self.__ptr)
return retVal
end
function SkeletonAnimation:Play(once)
local retVal = Polycode.SkeletonAnimation_Play(self.__ptr, once)
end
function SkeletonAnimation:Stop()
local retVal = Polycode.SkeletonAnimation_Stop(self.__ptr)
end
function SkeletonAnimation:Reset()
local retVal = Polycode.SkeletonAnimation_Reset(self.__ptr)
end
function SkeletonAnimation:Update(elapsed)
local retVal = Polycode.SkeletonAnimation_Update(self.__ptr, elapsed)
end
function SkeletonAnimation:setSpeed(speed)
local retVal = Polycode.SkeletonAnimation_setSpeed(self.__ptr, speed)
end
function SkeletonAnimation:setWeight(newWeight)
local retVal = Polycode.SkeletonAnimation_setWeight(self.__ptr, newWeight)
end
function SkeletonAnimation:getWeight()
local retVal = Polycode.SkeletonAnimation_getWeight(self.__ptr)
return retVal
end
function SkeletonAnimation:isPlaying()
local retVal = Polycode.SkeletonAnimation_isPlaying(self.__ptr)
return retVal
end
function SkeletonAnimation:__delete()
if self then Polycode.delete_SkeletonAnimation(self.__ptr) end
end
| 1,493
|
my-digital-decay/Polycode
|
--[[ BattleguardSartura.lua
********************************
* *
* The LUA++ Scripting Project *
* *
********************************
This software is provided as free and open source by the
staff of The LUA++ Scripting Project, in accordance with
the AGPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
~~End of License Agreement
-- LUA++ staff, March 26, 2008. ]]
--[[
Battleguard Sartura yells: I sentence you to death!
Battleguard Sartura yells: I serve to the last!
Battleguard Sartura yells: You will be judged for defiling these sacred grounds! The laws of the Ancients will not be challenged! Trespassers will be annihilated!
]]--
function Sartura_Knockback(pUnit, event)
pUnit:CastSpellOnTarget(10689, pUnit:GetRandomPlayer(0))
local kbtimer = math.random(25000, 60000)
pUnit:RegisterEvent("Sartura_Knockback2", kbtimer, 1)
end
function Sartura_Knockback2(pUnit, event)
pUnit:CastSpellOnTarget(10689, pUnit:GetRandomPlayer(0))
local kbtimer = math.random(25000, 60000)
pUnit:RegisterEvent("Sartura_Knockback", kbtimer, 1)
end
function Sartura_Whirlwind(Unit)
Unit:CastSpell(46270)
end
function Sartura_Phase2(Unit, event)
if (Unit:GetHealthPct() < 20) then
Unit:RemoveEvents()
Unit:CastSpell(28747)
Unit:RegisterEvent("Sartura_Enrage", 1000, 0)
end
end
function Sartura_Enrage(Unit)
local vars = getvars(Unit);
vars.EnrageTimer = vars.EnrageTimer + 1;
if (vars.EnrageTimer == 600) then
vars.EnrageTimer = 0;
setvars(Unit, vars);
Unit:CastSpell(34624)
end
setvars(Unit, vars);
end
function Sartura_OnCombat(Unit, event)
setvars(Unit, {EnrageTimer = 1});
local kbtimer=math.random(25000, 60000)
Unit:PlaySoundToSet(8646)
Unit:SendChatMessage(12, 0, "You will be judged for defiling these sacred grounds! The laws of the Ancients will not be challenged! Trespassers will be annihilated!")
Unit:RegisterEvent("Sartura_Whirlwind", 30000, 0)
Unit:RegisterEvent("Sartura_Phase2", 1000, 0)
Unit:RegisterEvent("Sartura_Knockback", kbtimer, 1)
Unit:RegisterEvent("Sartura_Enrage", 1000, 0)
end
function Sartura_OnLeaveCombat(Unit, event)
Unit:RemoveEvents()
end
function Sartura_OnKilledTarget(Unit, event)
Unit:PlaySoundToSet(8647)
Unit:SendChatMessage(12, 0, "I sentence you to death!")
end
function Sartura_OnDied(Unit, event)
Unit:PlaySoundToSet(8648)
Unit:SendChatMessage(12, 0, "I serve to the last!")
Unit:RemoveEvents()
end
RegisterUnitEvent(15516, 1, "Sartura_OnCombat")
RegisterUnitEvent(15516, 2, "Sartura_OnLeaveCombat")
RegisterUnitEvent(15516, 3, "Sartura_OnKilledTarget")
RegisterUnitEvent(15516, 4, "Sartura_OnDied")
| 2,958
|
499453466/Lua-Other
|
---------------------------------------------
-- Slowga
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0
end
function onPetAbility(target, pet, skill, summoner)
local duration = 180 + summoner:getMod(tpz.mod.SUMMONING)
if duration > 350 then
duration = 350
end
if target:addStatusEffect(tpz.effect.SLOW, 3000, 0, duration) then
skill:setMsg(tpz.msg.basic.SKILL_ENFEEB_IS)
else
skill:setMsg(tpz.msg.basic.SKILL_NO_EFFECT)
end
return tpz.effect.SLOW
end
| 757
|
PaulAnthonyReitz/topaz
|
-------------
--- Armor ---
-------------
-- Ver 1.0 --
-- Fire-Forged Armor --
armor:register_armor("draconis:helmet_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Helmet",
inventory_image = "draconis_inv_helmet_fire_draconic_steel.png",
groups = {armor_head=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:chestplate_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Chestplate",
inventory_image = "draconis_inv_chestplate_fire_draconic_steel.png",
groups = {armor_torso=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:leggings_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Leggings",
inventory_image = "draconis_inv_leggings_fire_draconic_steel.png",
groups = {armor_legs=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:boots_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Boots",
inventory_image = "draconis_inv_boots_fire_draconic_steel.png",
groups = {armor_feet=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
-- Ice-Forged Armor --
armor:register_armor("draconis:helmet_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Helmet",
inventory_image = "draconis_inv_helmet_ice_draconic_steel.png",
groups = {armor_head=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:chestplate_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Chestplate",
inventory_image = "draconis_inv_chestplate_ice_draconic_steel.png",
groups = {armor_torso=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:leggings_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Leggings",
inventory_image = "draconis_inv_leggings_ice_draconic_steel.png",
groups = {armor_legs=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:boots_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Boots",
inventory_image = "draconis_inv_boots_ice_draconic_steel.png",
groups = {armor_feet=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
| 3,675
|
ronoaldo/draconis
|
object_building_general_ord_cantina = object_building_general_shared_ord_cantina:new {
}
ObjectTemplates:addTemplate(object_building_general_ord_cantina, "object/building/general/ord_cantina.iff")
| 197
|
V-Fib/FlurryClone
|
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "nixio.util"
local tp = require "luci.template.parser"
local block = io.popen("block info", "r")
local ln, dev, devices = nil, nil, {}
repeat
ln = block:read("*l")
dev = ln and ln:match("^/dev/(.-):")
if dev then
local e, s, key, val = { }
for key, val in ln:gmatch([[(%w+)="(.-)"]]) do
e[key:lower()] = val
devices[val] = e
end
s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev)))
e.dev = "/dev/%s" % dev
e.size = s and math.floor(s / 2048)
devices[e.dev] = e
end
until not ln
block:close()
m = Map("fstab", translate("Mount Points"))
s = m:section(TypedSection, "global", translate("Global Settings"))
s.addremove = false
s.anonymous = true
detect = s:option(Button, "block_detect", translate("Generate Config"), translate("Find all currently attached filesystems and swap and replace configuration with defaults based on what was detected"))
detect.inputstyle = "reload"
detect.write = function(self, section)
luci.sys.call("block detect >/etc/config/fstab")
luci.http.redirect(luci.dispatcher.build_url("admin/system", "fstab"))
end
o = s:option(Flag, "anon_swap", translate("Anonymous Swap"), translate("Mount swap not specifically configured"))
o.default = o.disabled
o.rmempty = false
o = s:option(Flag, "anon_mount", translate("Anonymous Mount"), translate("Mount filesystems not specifically configured"))
o.default = o.disabled
o.rmempty = false
o = s:option(Flag, "auto_swap", translate("Automount Swap"), translate("Automatically mount swap on hotplug"))
o.default = o.enabled
o.rmempty = false
o = s:option(Flag, "auto_mount", translate("Automount Filesystem"), translate("Automatically mount filesystems on hotplug"))
o.default = o.enabled
o.rmempty = false
o = s:option(Flag, "check_fs", translate("Check filesystems before mount"), translate("Automatically check filesystem for errors before mounting"))
o.default = o.disabled
o.rmempty = false
local mounts = luci.sys.mounts()
local non_system_mounts = {}
for rawmount, val in pairs(mounts) do
if (string.find(val.mountpoint, "/tmp/.jail") == nil) then
repeat
val.umount = false
if (val.mountpoint == "/") then
break
elseif (val.mountpoint == "/overlay") then
break
elseif (val.mountpoint == "/rom") then
break
elseif (val.mountpoint == "/tmp") then
break
elseif (val.mountpoint == "/tmp/shm") then
break
elseif (val.mountpoint == "/tmp/upgrade") then
break
elseif (val.mountpoint == "/dev") then
break
end
val.umount = true
until true
non_system_mounts[rawmount] = val
end
end
v = m:section(Table, non_system_mounts, translate("Mounted file systems"))
fs = v:option(DummyValue, "fs", translate("Filesystem"))
mp = v:option(DummyValue, "mountpoint", translate("Mount Point"))
avail = v:option(DummyValue, "avail", translate("Available"))
function avail.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].available) or 0 ) * 1024
) .. " / " .. luci.tools.webadmin.byte_format(
( tonumber(mounts[section].blocks) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("Used"))
function used.cfgvalue(self, section)
return ( mounts[section].percent or "0%" ) .. " (" ..
luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
) .. ")"
end
-- unmount = v:option(Button, "unmount", translate("Unmount"))
-- unmount.render = function(self, section, scope)
-- if non_system_mounts[section].umount then
-- self.title = translate("Unmount")
-- self.inputstyle = "remove"
-- Button.render(self, section, scope)
-- end
-- end
-- unmount.write = function(self, section)
-- if non_system_mounts[section].umount then
-- luci.sys.call("/bin/umount '%s'" % luci.util.shellstartsqescape(non_system_mounts[section].mountpoint))
-- return luci.http.redirect(luci.dispatcher.build_url("admin/system", "fstab"))
-- end
-- end
mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem"))
mount.anonymous = true
mount.addremove = true
mount.template = "cbi/tblsection"
mount.extedit = luci.dispatcher.build_url("admin/system/fstab/mount/%s")
mount.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(mount.extedit % sid)
return
end
end
mount:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = mount:option(DummyValue, "device", translate("Device"))
dev.rawhtml = true
dev.cfgvalue = function(self, section)
local v, e
v = m.uci:get("fstab", section, "uuid")
e = v and devices[v]
if v and e and e.size then
return "UUID: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size }
elseif v and e then
return "UUID: %s (%s)" %{ tp.pcdata(v), e.dev }
elseif v then
return "UUID: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
v = m.uci:get("fstab", section, "label")
e = v and devices[v]
if v and e and e.size then
return "Label: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size }
elseif v and e then
return "Label: %s (%s)" %{ tp.pcdata(v), e.dev }
elseif v then
return "Label: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
v = Value.cfgvalue(self, section) or "?"
e = v and devices[v]
if v and e and e.size then
return "%s (%d MB)" %{ tp.pcdata(v), e.size }
elseif v and e then
return tp.pcdata(v)
elseif v then
return "%s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
end
mp = mount:option(DummyValue, "target", translate("Mount Point"))
mp.cfgvalue = function(self, section)
if m.uci:get("fstab", section, "is_rootfs") == "1" then
return "/overlay"
else
return Value.cfgvalue(self, section) or "?"
end
end
fs = mount:option(DummyValue, "fstype", translate("Filesystem"))
fs.cfgvalue = function(self, section)
local v, e
v = m.uci:get("fstab", section, "uuid")
v = v or m.uci:get("fstab", section, "label")
v = v or m.uci:get("fstab", section, "device")
e = v and devices[v]
return e and e.type or m.uci:get("fstab", section, "fstype") or "?"
end
op = mount:option(DummyValue, "options", translate("Options"))
op.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) or "defaults"
end
rf = mount:option(DummyValue, "is_rootfs", translate("Root"))
rf.cfgvalue = function(self, section)
local target = m.uci:get("fstab", section, "target")
if target == "/" then
return translate("yes")
elseif target == "/overlay" then
return translate("overlay")
else
return translate("no")
end
end
ck = mount:option(DummyValue, "enabled_fsck", translate("Check"))
ck.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) == "1"
and translate("yes") or translate("no")
end
swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>."))
swap.anonymous = true
swap.addremove = true
swap.template = "cbi/tblsection"
swap.extedit = luci.dispatcher.build_url("admin/system/fstab/swap/%s")
swap.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(swap.extedit % sid)
return
end
end
swap:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = swap:option(DummyValue, "device", translate("Device"))
dev.cfgvalue = function(self, section)
local v
v = m.uci:get("fstab", section, "uuid")
if v then return "UUID: %s" % v end
v = m.uci:get("fstab", section, "label")
if v then return "Label: %s" % v end
v = Value.cfgvalue(self, section) or "?"
e = v and devices[v]
if v and e and e.size then
return "%s (%s MB)" % {v, e.size}
else
return v
end
end
return m
| 8,343
|
WYC-2020/luci
|
--
-- YATM Brewery
--
local mod = foundation.new_module("yatm_brewery", "0.2.0")
mod:require("registries.lua")
mod:require("api.lua")
mod:require("nodes.lua")
mod:require("items.lua")
mod:require("fluids.lua")
mod:require("tests.lua")
| 239
|
IceDragon200/mt-yatm
|
-- lightsout v0.0.0
--
--
-- llllllll.co/t/lightsout
--
--
--
-- ▼ instructions below ▼
grid__=include("lightsout/lib/ggrid")
MusicUtil = require "musicutil"
lattice=require("lattice")
engine.name="PolyPerc"
function init()
grid_=grid__:new()
local redrawer=metro.init()
redrawer.time=1/15
redrawer.count=-1
redrawer.event=redraw
redrawer:start()
scale_full=MusicUtil.generate_scale_of_length(12, 1, 64)
for _, note in ipairs(MusicUtil.generate_scale_of_length(12, 1, 128)) do
table.insert(scale_full,note)
end
-- shuffled = {}
-- for i, v in ipairs(scale_full) do
-- local pos = math.random(1, #shuffled+1)
-- table.insert(shuffled, pos, v)
-- end
-- scale_full=shuffled
scales={}
k=1
for col=1,16 do
for row=1,8 do
if col==1 then
scales[row]={}
end
scales[row][col]=scale_full[k]
k=k+1
end
k = k - 3
end
-- start lattice
local sequencer=lattice:new{
ppqn=96
}
divisions={1/2,1/4,1/8,1/16,1/2,1/4,1/8,1/16,1/2,1/4,1/8,1/16,1/2,1/4,1/8,1/16}
for i=1,16 do
local step=0
sequencer:new_pattern({
action=function(t)
step=step+1
play_note(i,step)
end,
division=divisions[i],
})
end
sequencer:hard_restart()
end
function play_note(col,step)
local row=(step-1)%8+1
local light=grid_.lightsout[row][col]
if light>0 then
print(row,col)
print(scales[row][col])
local freq = MusicUtil.note_num_to_freq(scales[row][col])
grid_.visual[row][col]=15
engine.hz(freq)
-- grid_:toggle_key(row,col)
end
end
function enc(k,d)
end
function key(k,z)
end
function redraw()
screen.clear()
screen.move(32,64)
screen.text("lightsout")
screen.update()
end
function rerun()
norns.script.load(norns.state.script)
end
function cleanup()
end
function table.reverse(t)
local len = #t
for i = len - 1, 1, -1 do
t[len] = table.remove(t, i)
end
end
| 1,944
|
schollz/lightsout
|
local t = require('luatest')
local http_lib = require('http.lib')
local g = t.group()
g.test_template_1 = function()
t.assert_equals(http_lib.template("<% for i = 1, cnt do %> <%= abc %> <% end %>",
{abc = '1 <3>&" ', cnt = 3}),
' 1 <3>&" 1 <3>&" 1 <3>&" ',
'tmpl1')
end
g.test_template_2 = function()
t.assert_equals(http_lib.template('<% for i = 1, cnt do %> <%= ab %> <% end %>',
{abc = '1 <3>&" ', cnt = 3}),
' nil nil nil ', 'tmpl2')
end
g.test_broken_template = function()
local r, msg = pcall(http_lib.template, '<% ab() %>', {ab = '1'})
t.assert(r == false and msg:match("call local 'ab'") ~= nil, 'bad template')
end
g.test_rendered_template_truncated_gh_18 = function()
local template = [[
<html>
<body>
<table border='1'>
% for i,v in pairs(t) do
<tr>
<td><%= i %></td>
<td><%= v %></td>
</tr>
% end
</table>
</body>
</html>
]]
local tt = {}
for i=1, 100 do
tt[i] = string.rep('#', i)
end
local rendered, _ = http_lib.template(template, { t = tt })
t.assert(#rendered > 10000, 'rendered size')
t.assert_equals(rendered:sub(#rendered - 7, #rendered - 1), '</html>', 'rendered eof')
end
g.test_incorrect_arguments_escaping_leads_to_segfault_gh_51 = function()
local template = [[<%= {{continue}} %>"]]
local result = http_lib.template(template, {continue = '/'})
t.assert(result:find('\"') ~= nil)
end
| 1,598
|
a1div0/http
|
--[[
This is a guide for how to use this game as a starting point to create your own RPGs or other games.
This entire system uses one shared storage key. Go to 'Window' -> 'Shared Storage', and create a key or make one of your
existing keys associated with this game. Find 'APISharedKey' in Project Content, and change the "StorageKey" custom
property to point to your new shared key. You may have to select 'All Content' and do a bit of scrolling to make this
work.
You can turn on cheats by checking 'Enable' custom property on the 'Developer Cheats' script (under System->Developer
Cheats). It will print to the Event Log on preview start what you can do.
Use the 'DifficultyLevel' custom property on the 'DifficultySystem' group under 'System' to set difficulty. It is set up
to support 1 through 4 (Normal, Hard, Nightmare, Infinite).
In general, the 'System' folder controls how everything works, and should be identical between any dungeons or zones you
use. Right now there isn't a great way to keep that synchronized, just be careful when you make changes.
The 'Data' Folder includes everything that would be different between different dungeons. Use that to add new enemies,
change where enemies are, what attacks they have, what they drop, etc.
The API scripts are a good place to start, and generally have good comments, especially at the top describing how pieces
work. Also, for all of the sections below, copying an existing example that is similar is a way safer than making one
from scratch.
Adding Abilities:
1. Make a single script, generally named "Ability_[Name]".
2. Look at an existing ability script to see how they are set up. They do not exist in the hierarchy.
3. Add your new script as a custom property to APIAbility in Project Content. Leave the property name as is.
4. Note that onCastclient returns the time until it should spawn effects, and must not yield (or you may see janky
behavior.
Adding Status Effects:
1. Make a single script, generally named StatusEffect_[Name]".
2. Add two instances of that script to the hierarchy, under
System->Status Effect Controller->ClientStatusEffectDefinitions and
System->Status Effect Controller->ServerStatusEffectDefinitions.
3. Look at existing scripts to see how these are set up. Any start, tick, or end functions should not yield.
Adding Enemy Tasks:
1. Make two scripts, generally called "Task_[EnemyName]_[TaskName]_[Client/Server]". Put them under
Data->NPC System->Tasks->ClientTasks and Data->NPC System->Tasks->ServerTasks.
2. See existing scripts for examples and API_NPC for a description of what pieces are required.
3. Be VERY careful with timing and edge cases of players connecting/disconnecting. You cannot yield so these make a lot
of use of Tasks, but players can leave or enemies despawn in the middle of a task. Worse, if one of these causes a
script error, it usually results in all enemies no longer responding at all.
Adding Loot:
Loot is defined by a bunch of scripts with 'DATA' in the name. These were created by the spreadsheet below, but they
can also be edited directly.
1. Go to the following spreadsheet and make a copy for yourself:
https://docs.google.com/spreadsheets/d/12KBbew9zlaZre2ByMuCX4WBBaH20W1PXt242qcoHrKw/edit?usp=sharing
2. Edit as desired. Go to each tab and select 'File->Download->Comma-separated values (.csv, current sheeet)'. This will
give you about 20 .csv files.
3. Open https://csv-to-lua.netlify.app/. For each .csv file, open it in a text editor, paste the contents into the left
box, press 'Convert to Lua', then copy paste the right box into the corresponding 'DATA' script.
Adding Enemies:
Enemies are found in Data->NPC System->NPCs->[Foldername]. This is one of the few systems that requires specific
hierarchy setup, and that last folder must be there or they won't work. Those folders also can have a custom property
'Prerequestite' which most of them do, which tells the system which pull must be cleared first. The NPCs are fairly
expensive, so if you have more than ~8 active at a time, it may perform poorly.
NPCs are controlled almost entirely through their custom properties. Many are self-explanatory. Capsule size is used for
nameplate positioning, click targeting, and a few other things. They can drop from as many drop keys as you'd like, and
have as many tasks as you'd like as well. The FollowRoot is used so that client-side movement is smooth.
Controls:
We investigated changing the control scheme some, and may still down the road. We specifically looked to more action RPG
control styles where your cursor is hidden by default and your mouse controls your camera. Here are some of the major
issues we hit:
- The 'classic' MMO control scheme informs certain ability and enemy designs, and having a different control scheme
would probably be better with different abilities and enemies.
- An 'action' RPG control scheme is fairly incompatible with a targeting system entirely. That could be removed with
certain design choices.
- We did not make a robust system to control cursor visibility and interaction, and the 'action' RPG control scheme ran
into MANY issues here. You need the cursor visible whenever inventory/help, etc. are open. You need a way to show the
cursor so a player can rearrange their action bar, or click on UI buttons. This is definitely something that can be
written, but does not currently exist.
]]
| 5,480
|
Core-Team-META/Corehaven
|
-- icon set definition format
--
-- indexed by unique identifier, referenced with icon_ prefix
-- search path is prefixed icons/setname (same as lua file)
--
-- source to the synthesizers and builtin shaders are in icon.lua
--
-- 1. static image:
-- ["myicon"] = {
-- [24] = "myicon_24px.png",
-- [16] = "myicon_16px.png"
-- }
--
-- 2. postprocessed (custom color, SDFs, ...)
-- ["myicon"] = {
-- [24] = function()
-- return icon_synthesize_src("myicon_24px.png", 24,
-- icon_colorize, {color = {"fff", 1.0, 0.0, 0.0}});
-- end
-- }
--
-- 3. synthesized
-- ["myicon"] = {
-- generator =
-- function(px)
-- return icon_synthesize(px,
-- icon_unit_circle, {radius = {"f", 0.5}, color = {"fff", 1.0, 0.0, 0.0}})
-- end
-- }
--
-- and they can be mixed, i.e. if there is no direct match for a certain px size,
-- the generator will be invoked. This is to allow both a SDF based vector synth
-- as well as hand drawn overrides.
--
-- It is up to the UI component that uses the icon to deal with the desired px
-- size not actually being the returned one, and many will rather pad/relayout
-- than force-scale. In that case, use the 3. method with icon_synthesize_src.
--
return {
["cli"] =
{
[24] = function()
return icon_synthesize_src("cli_24px.png", 24,
icon_colorize, {color = {"fff", 0.0, 1.0, 1.0}});
end,
}
};
| 1,335
|
letoram/durden
|
workspace "LiquidEngine"
basedir "../workspace/"
language "C++"
cppdialect "C++17"
architecture "x86_64"
-- Set editor as starting project
startproject "Liquidator"
setupLibraryDirectories{}
setupPlatformDefines{}
linkPlatformLibraries{}
setupToolsetOptions{}
includedirs {
"../engine/src",
"../engine/rhi/core/include",
"../engine/rhi/vulkan/include",
"../engine/platform-tools/include"
}
configurations { "Debug", "Release", "Profile-Debug", "Profile-Release" }
filter { "toolset:msc-*" }
flags { "FatalCompileWarnings" }
filter {"configurations:Debug or configurations:Profile-Debug"}
defines { "LIQUID_DEBUG" }
symbols "On"
filter {"configurations:Release or configurations:Profile-Release"}
defines { "LIQUID_RELEASE" }
optimize "On"
filter {"configurations:Profile-Debug or configurations:Profile-Release"}
defines { "LIQUID_PROFILER" }
| 1,012
|
GasimGasimzada/liquid-engine
|
-----------------------------------
-- Area: The Garden of Ru'Hmet
-- Mob: Ix'aern DRG
-----------------------------------
local ID = require("scripts/zones/The_Garden_of_RuHmet/IDs")
-----------------------------------
function onMobFight(mob, target)
-- Spawn the pets if they are despawned
-- TODO: summon animations?
local mobId = mob:getID()
local x = mob:getXPos()
local y = mob:getYPos()
local z = mob:getZPos()
for i = mobId + 1, mobId + 3 do
local wynav = GetMobByID(i)
if not wynav:isSpawned() then
local repopWynavs = wynav:getLocalVar("repop") -- see Wynav script
if mob:getBattleTime() - repopWynavs > 10 then
wynav:setSpawn(x + math.random(1, 5), y, z + math.random(1, 5))
wynav:spawn()
wynav:updateEnmity(target)
end
end
end
end
function onMobDeath(mob, player, isKiller)
-- despawn pets
local mobId = mob:getID()
for i = mobId + 1, mobId + 3 do
if GetMobByID(i):isSpawned() then
DespawnMob(i)
end
end
end
function onMobDespawn( mob )
-- despawn pets
local mobId = mob:getID()
for i = mobId + 1, mobId + 3 do
if GetMobByID(i):isSpawned() then
DespawnMob(i)
end
end
-- Pick a new PH for Ix'Aern (DRG)
local groups = ID.mob.AWAERN_DRG_GROUPS
SetServerVariable("[SEA]IxAernDRG_PH", groups[math.random(1, #groups)] + math.random(0, 2))
end
| 1,497
|
MatthewJHBerry/topaz
|
--[[
This file has been modified by
Andreas Pittrich <andreas.pittrich@web.de>
in behalf of the german pirate party (Piratenpartei)
www.piratenpartei.de
Original Disclaimer:
-------
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
luci.i18n.loadc("freifunk")
local uci = require "luci.model.uci".cursor()
local fs = require "luci.fs"
m = Map("freifunk", "Custom Splash")
d = m:section(NamedSection, "custom_splash", "settings", "Custom Splash")
----------------
active=d:option(ListValue, "mode", "Custom Splash benutzen?")
active.widget="radio"
active.size=1
active:value("enabled", "Ja")
active:value("disabled", "Nein")
msg=d:option(ListValue, "messages", "Nachrichten aktivieren?")
msg.widget="radio"
msg.size=1
msg:value("enabled", "Ja")
msg:value("disabled", "Nein")
----------------
header=d:option(TextValue, "header", "Custom Header")
header.rows="20"
function header.cfgvalue(self, section)
cs=fs.readfile("/lib/uci/upload/custom_header.htm")
if cs == nil then
return ""
else
return cs
end
end
function header.write(self, section, value)
fs.writefile("/lib/uci/upload/custom_header.htm",value)
end
----------------
footer=d:option(TextValue, "footer", "Custom Footer")
footer.rows="20"
function footer.cfgvalue(self, section)
cs=fs.readfile("/lib/uci/upload/custom_footer.htm")
if cs == nil then
return ""
else
return cs
end
end
function footer.write(self, section, value)
fs.writefile("/lib/uci/upload/custom_footer.htm",value)
end
return m
| 1,750
|
alxhh/piratenluci
|
return {'amnesie','amnestie','amnestiemaatregel','amnestieregeling','amnestieverlening','amnestiewet','amnioscoop','amnioscopie','amnestieen','amnioscopen','amnioscopieen'}
| 172
|
terrabythia/alfabeter
|
blocFunctions = {}
function function_binding(toBind)
for k, v in pairs(toBind) do
blocFunctions[k] = function(position)
local newObjs = {};
for i in string.gmatch(v, "%S+") do
table.insert(newObjs, Engine.Scene:createGameObject(i)({position = position}));
end
return newObjs
end
end
end
function Object:uninit()
Object.initialized = false;
end
function Object:init(path)
print("Init terrain", path)
if not Object.initialized and file_exists(path) then
This:initialize();
print("Terrain initialized");
local lines = lines_from(path)
local maxY;
local maxX;
local sprSize;
local load_table = {};
print("Lines", inspect(lines));
for i, str in pairs(lines) do
if maxY == nil or i>maxY then
maxY = i;
end
load_table[i] = {}
for j = 1, #str do
if maxX == nil or j>maxX then
maxX = j;
end
local char = str:sub(j,j);
load_table[i][j] = char;
end
end
print("Loadtable", inspect(load_table));
local offset = {x = (maxX/2), y = (maxY/2)};
for i, v in pairs(load_table) do
Object.elements[i] = {}
for j, v2 in pairs(v) do
if v2 ~= " " then
local position = { x = j-1, y = i-1 };
print("Loading element", v2);
Object.elements[i][j] = blocFunctions[v2](position);
if sprSize == nil then
sprSize = Object.elements[i][j][1].getSprSize();
end
end
end
end
print("Setting camera");
local pVec = obe.Transform.UnitVector(
offset.x * sprSize.x,
offset.y * sprSize.y
);
local ySize = maxY/Engine.Scene:getCamera():getSize().y;
local xSize = maxX/Engine.Scene:getCamera():getSize().x;
local pSize = sprSize.x * (ySize > xSize and ySize or xSize);
local camera = Engine.Scene:getCamera();
camera:setPosition(pVec, obe.Transform.Referential.Center);
camera:scale(pSize, obe.Transform.Referential.Center);
print("Terrain done :)");
Object.initialized = true;
end
end
function Local.Init(toBind)
function_binding(toBind);
Object.elements = {};
end
function file_exists(path)
local f = io.open(path, "r")
if f then f:close() end
return f ~= nil
end
function lines_from(path)
lines = {}
for line in io.lines(path) do
lines[#lines + 1] = line
end
return lines
end
| 2,748
|
Alaznist/Examples
|
local ffi = require('ffi')
local log = require('log')
local fun = require('fun')
local yaml = require('yaml')
local fiber = require('fiber')
local socket = require('socket')
local boxerrno = require('errno')
local expd = require('memcached.expirationd')
require('memcached.libparser')
ffi_parser = ffi.load('libparser.so')
ffi.cdef[[
enum mc_op {
MC_SET = 1,
MC_ADD,
MC_REPLACE,
MC_APPEND,
MC_PREPEND,
MC_CAS,
MC_GET,
MC_GETS,
MC_DELETE,
MC_INCR,
MC_DECR,
MC_FLUSH,
MC_STATS,
MC_VERSION,
MC_QUIT,
};
struct mc_request {
enum mc_op op;
const char *key;
size_t key_len;
uint32_t key_count;
const char *data;
size_t data_len;
uint64_t flags;
uint64_t bytes;
uint64_t cas;
uint64_t exptime;
uint64_t inc_val;
bool noreply;
};
int mc_parse(struct mc_request *req, const char **p, const char *pe);
void *memmove(void *dst, const void *src, size_t num);
]]
-- func = ffi.load('./libmemctnt.so')
local function dump_request(req)
log.debug('operation: %d', req.op)
log.debug('keys: %d, len(%d) - %s',
tonumber(req.key_count),
tonumber(req.key_len),
ffi.string(req.key, req.key_len))
log.debug('data: len(%d) - %s',
tonumber(req.data_len),
ffi.string(req.data, req.data_len))
end
local buffer_err = {
['EOK'] = 0,
['EINVAL'] = 1,
['ENOMEM'] = 2
}
local buffer_strerr = {
[0] = 'Not an error',
[1] = 'Bad value',
[2] = 'Not enough memory'
}
local buffer_methods = {
extend = function (self, needed)
self:pack()
local had = (self.size - self.woff)
if (had < needed) then
had = self.size * 2
while (had - self.woff < needed) do
had = had * 2
end
self:_extend(had)
end
return
end,
_extend = function (self, new_size)
if (new_size < self.size) then
self.error = buffer_err.EINVAL
return
end
local new_buf = ffi.new('char [?]', new_size)
if (new_buf == nil) then
self.error = buffer_err.ENOMEM
return
end
if (self.buffer ~= nil) then
ffi.copy(new_buf,
self.buffer + self.roff,
self.woff - self.roff)
end
self.woff = self.woff - self.roff
self.roff = 0
self.buffer = new_buf
self.size = new_size
end,
strerror = function(self)
return buffer_strerr[self.error]
end,
write = function (self, str, str_size)
if type(str) == 'string' then
str_size = #str
end
if (self.size - self.woff) < str_size then
self:extend(str_size)
end
ffi.copy(self.buffer + self.woff,
str, str_size)
self.woff = self.woff + str_size
return str_size
end,
write_ans = function (self, str, str_size)
if type(str) == 'string' then
str_size = #str
end
local written = self:write(str, str_size)
written = written + self:write('\r\n')
return written
end,
write_seer = function (self, str, str_size)
if type(str) == 'string' then
str_size = #str
end
local written = self:write('SERVER_ERROR ')
written = written + self:write(str, str_size)
written = written + self:write('\r\n')
return written
end,
write_cler = function (self, str, str_size)
if type(str) == 'string' then
str_size = #str
end
local written = self:write('CLIENT_ERROR ')
written = written + self:write(str, str_size)
written = written + self:write('\r\n')
return written
end,
write_err = function (self)
if type(str) == 'string' then
str_size = #str
end
local written = self:write('ERROR\r\n')
return written
end,
wptr_get = function (self)
return self.buffer + self.woff
end,
read = function (self, size)
if (size == nil or size > self.woff - self.roff) then
size = self.woff - self.roff
end
return ffi.string(self.buffer + self.roff, size)
end,
rptr_get = function (self)
return self.buffer + self.roff
end,
pack = function(self)
if (self.roff == 0) then return end
if (self.roff ~= self.woff) then
ffi.C.memmove(self.buffer,
self.buffer + self.roff,
self.woff - self.roff)
end
self.woff = self.woff - self.roff
self.roff = 0
return
end,
recvfull = function(self, sckt, read_finished)
return self:recv(sckt, self.size - self.woff, read_finished)
end,
recv = function(self, sckt, size, read_finished)
if (read_finished) then
if not sckt:readable() then return -1 end
end
log.debug('read size, woff:'.. tostring(size)..' '..tostring(self.woff))
local retval = ffi.C.read(sckt:fd(), self.buffer + self.woff, size)
log.debug('read size:'.. tostring(retval))
if retval == -1 then
sckt._errno = boxerrno()
return -1
end
self.woff = self.woff + retval
return retval
end,
sendall = function(self, sckt)
local pos = self.roff
local to_write = (self.woff - self.roff)
while to_write > 0 do
if not sckt:writable() then return -1 end
local retval = ffi.C.send(sckt:fd(), self.buffer + pos, to_write, 0)
if retval == -1 then
sckt._errno = boxerrno()
return -1
end
to_write = to_write - retval
pos = pos + retval
end
pos = pos - self.roff
self.roff = 0
self.woff = 0
return pos
end,
log = function(self, str)
log.debug('%s buffer: \'%s\'',
str, ffi.string(self:rptr_get(), self.woff - self.roff))
end
}
local buffer = {
new = function ()
local self = setmetatable({}, { __index = buffer_methods })
self.size = 16384
self.error = buffer_err.EOK
self.roff = 0
self.woff = 0
self:_extend(self.size)
if (self.error ~= buffer_err.EOK) then
log.error('ERROR')
return
end
return self
end
}
local memcached_methods = {
stop_loop = function(self)
if self.srv then
self.srv:close()
self.srv = nil
end
end,
init_loop = function(self, port)
local function memcache_handler(srv, from)
log.debug('begin_loop')
local rbuf = buffer.new()
local wbuf = buffer.new()
local p_ptr = ffi.new('const char *[1]')
local req = ffi.new('struct mc_request')
local size, rval, resp = 0, 0, 0
local read_finished = true
while true do
if (rval > 0) then
rbuf:extend(rval)
end
rbuf:pack()
size = rbuf:recvfull(srv, read_finished) -- may yeild
rbuf:log("Input")
log.debug(tostring(size))
if (size == -1) then
log.error('Error %d: %s', srv:errno(), boxerrno.strerror(srv:errno()))
return
end
local tp = ffi.cast('const char *', rbuf:rptr_get())
p_ptr[0] = tp
while true do
if (p_ptr[0] == rbuf:wptr_get()) then
resp = nil
break
end
rval = ffi_parser.mc_parse(req, p_ptr, rbuf:wptr_get())
log.debug('Parsing result: '..tostring(rval))
log.debug(tostring(req.op))
--dump_request(req)
read_finished = true
if (rval > 0) then
read_finished = false
break
elseif (rval == -1 and req.op == 0) then
wbuf:write_err()
break
elseif (rval == -1 or rval == -3 or rval == -4 or rval == -5) then
wbuf:write_cler('bad command line format')
break
elseif (rval == -2) then
wbuf:write_cler('invalid exptime argument')
break
elseif (rval == -6) then
wbuf:write_cler('invalid numeric delta argument')
break
elseif (rval == -7) then
wbuf:write_cler('bad data chunk')
break
end
--resp = self:cmd_exec(req, wbuf)
local stat, resp = pcall(self.cmd_exec, self, req, wbuf)
if (stat == false) then
if (box.error.last() ~= nil) then
local errcode = box.error.last().code
log.error('Error %d while executed: %s', errcode, resp)
if (errcode == box.error.MEMORY_ISSUE) then
resp = 'object too large for cache or OOM'
else
resp = string.format('%d: %s', errcode, resp)
end
wbuf:write_seer(resp)
break
else
log.error('Error while executed: %s', resp)
wbuf:write_seer(resp)
break
end
end
log.debug('response_stat: '..tostring(resp))
if (resp == 'exit') then
break
end
resp = nil
rbuf.roff = p_ptr[0] - rbuf.buffer
end
wbuf:log("Output")
if (read_finished) then
wbuf:sendall(srv) -- may yeild
end
if (stat == false) then
log.debug('Server error, closing connection')
return
elseif (rval < 0 or resp == 'clerr') then
log.debug('Client error, exiting')
return
elseif (resp == 'exit') then
log.debug('Client requested exit')
return
elseif (size == nil) then
log.debug('Socker error, exiting')
return
end
end
end
self.srv = socket.tcp_server('0.0.0.0', port, {
handler = memcache_handler,
name = 'memcache loop',
}, 50)
end,
-- TODO:
-- Move get/gets (not splitting keys, instead use ffi.string and e.t.c.)
cmd_exec = function(self, req, outbuf)
if (req.op == ffi.C.MC_SET) then
return self:set(ffi.string(req.key, req.key_len),
ffi.string(req.data, req.data_len),
tonumber(req.exptime), tonumber(req.flags),
tonumber(req.noreply), outbuf)
elseif (req.op == ffi.C.MC_ADD) then
return self:add(ffi.string(req.key, req.key_len),
ffi.string(req.data, req.data_len),
tonumber(req.exptime), tonumber(req.flags),
tonumber(req.noreply), outbuf)
elseif (req.op == ffi.C.MC_REPLACE) then
return self:replace(ffi.string(req.key, req.key_len),
ffi.string(req.data, req.data_len),
tonumber(req.exptime), tonumber(req.flags),
tonumber(req.noreply), outbuf)
elseif (req.op == ffi.C.MC_APPEND) then
return self:append(ffi.string(req.key, req.key_len),
ffi.string(req.data, req.data_len),
tonumber(req.noreply), outbuf)
elseif (req.op == ffi.C.MC_PREPEND) then
return self:prepend(ffi.string(req.key, req.key_len),
ffi.string(req.data, req.data_len),
tonumber(req.noreply), outbuf)
elseif (req.op == ffi.C.MC_CAS) then
return self:cas(ffi.string(req.key, req.key_len),
ffi.string(req.data, req.data_len),
tonumber(req.cas), tonumber(req.exptime),
tonumber(req.flags), tonumber(req.noreply),
outbuf)
elseif (req.op == ffi.C.MC_GET) then
local keys = ffi.string(req.key, req.key_len)
if (req.key_count > 1) then
local k = {};
for i in string.gmatch(keys, '%S+') do
table.insert(k, i)
end
keys = k
end
return self:get(keys, outbuf)
elseif (req.op == ffi.C.MC_GETS) then
local keys = ffi.string(req.key, req.key_len)
if (req.key_count > 1) then
local k = {};
for i in string.gmatch(keys, '%S+') do
table.insert(k, i)
end
keys = k
end
return self:gets(keys, outbuf)
elseif (req.op == ffi.C.MC_DELETE) then
return self:delete(ffi.string(req.key, req.key_len),
tonumber(req.noreply), outbuf)
elseif (req.op == ffi.C.MC_INCR) then
return self:incr(ffi.string(req.key, req.key_len),
req.inc_val, tonumber(req.noreply),
outbuf)
elseif (req.op == ffi.C.MC_DECR) then
return self:decr(ffi.string(req.key, req.key_len),
req.inc_val, tonumber(req.noreply),
outbuf)
elseif (req.op == ffi.C.MC_FLUSH) then
return self:flush_all(tonumber(req.exptime), outbuf)
elseif (req.op == ffi.C.MC_STATS) then
-- Stat cmd currently is not implemented
return self:cmd_stats(ffi.string(req.key, req.key_len), outbuf)
elseif (req.op == ffi.C.MC_VERSION) then
return self:version(outbuf)
elseif (req.op == ffi.C.MC_QUIT) then
return 'exit'
else
outbuf:write_err()
log.debug('Processing undefined command')
return 'exit'
end
end,
stat_incr = function(self, stat)
self.stats[stat] = self.stats[stat] + 1
end,
get_tuple_or_expire = function(self, key)
local tuple = self.mcs:get{key}
if tuple == nil then return 'none' end
local time, etime, ptime = fiber.time(), tuple[3], tuple[6]
-- check for invalidation
if ((ptime <= self.flush and self.flush <= time) or
(etime <= time and etime ~= 0)) then
-- invalidate and free
self.mcs:delete{key}
log.debug('expired by get')
self:stat_incr('expired_runtime')
return 'expired'
end
return tuple
end,
normalize_flush_time = function(self, exptime)
exptime = exptime or 0
if type(exptime) ~= 'number' then exptime = 0 end
if (exptime < (30*24*60*60) and exptime >= 0) then
exptime = (fiber.time()) + exptime
end
return exptime
end,
normalize_exptime = function(self, exptime)
exptime = exptime or 0
if type(exptime) ~= 'number' then exptime = 0 end
if (exptime < (30*24*60*60) and exptime > 0) then
exptime = (fiber.time()) + exptime
end
return exptime
end,
----
-- store this data
----
set = function(self, key, value, exptime, flags, noreply, outbuf)
-- Check arguments
key, value = tostring(key), tostring(value)
exptime = self:normalize_exptime(exptime)
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
local ptime = (fiber.time())
self:stat_incr('cmd_set')
self.mcs:replace{key, value, exptime, flags, cas, ptime}
if noreply == true then return 0 end
outbuf:write_ans('STORED')
return 0
end,
----
-- store this data, but only if the server *doesn't* already
-- hold data for this key
----
add = function(self, key, value, exptime, flags, noreply, outbuf)
-- Check arguments
key, value = tostring(key), tostring(value)
exptime = self:normalize_exptime(exptime)
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
local ptime = (fiber.time())
self:stat_incr('cmd_set')
box.begin()
local tuple = self:get_tuple_or_expire(key)
if type(tuple) == 'string' then
self.mcs:replace{key, value, exptime, flags, cas, ptime}
end
box.commit()
if noreply == true then return end
if type(tuple) ~= 'string' then
outbuf:write_ans('NOT_STORED')
else
outbuf:write_ans('STORED')
end
return 0
end,
----
-- store this data, but only if the server *does*
-- already hold data for this key
----
replace = function(self, key, value, exptime, flags, noreply, outbuf)
-- Check arguments
key, value = tostring(key), tostring(value)
exptime = self:normalize_exptime(exptime)
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
local ptime = (fiber.time())
self:stat_incr('cmd_set')
box.begin()
local tuple = self:get_tuple_or_expire(key)
if type(tuple) ~= 'string' then
self.mcs:replace{key, value, exptime, flags, cas, ptime}
end
box.commit()
if noreply == true then return end
if type(tuple) == 'string' then
outbuf:write_ans('NOT_STORED')
else
outbuf:write_ans('STORED')
end
return 0
end,
append = function(self, key, value, noreply, outbuf)
-- Check arguments
key, value = tostring(key), tostring(value)
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
self:stat_incr('cmd_set')
box.begin()
local tuple = self:get_tuple_or_expire(key)
local t = self.mcs:update({key}, {
{':', 2, -1, 0, value}, {'=', 5, cas}
})
box.commit()
if noreply == true then return end
if t == nil then
outbuf:write_ans('NOT_STORED')
else
outbuf:write_ans('STORED')
end
return 0
end,
prepend = function(self, key, value, noreply, outbuf)
-- Check arguments
key, value = tostring(key), tostring(value)
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
self:stat_incr('cmd_set')
box.begin()
local tuple = self:get_tuple_or_expire(key)
local t = self.mcs:update({key}, {
{':', 2, 1, 0, value}, {'=', 5, cas}
})
box.commit()
if noreply == true then return end
if t == nil then
outbuf:write_ans('NOT_STORED')
else
outbuf:write_ans('STORED')
end
return 0
end,
----
-- check and set operation which means "store this data but
-- only if no one else has updated since I last fetched it."
----
cas = function(self, key, value, cas, exptime, flags, noreply, outbuf)
-- Check arguments
key, value = tostring(key), tostring(value)
exptime = self:normalize_exptime(exptime)
-- Execute requests
local ncas = self.casn; self.casn = self.casn + 1
local ptime = (fiber.time())
box.begin()
local tuple = self:get_tuple_or_expire(key)
if type(tuple) ~= 'string' then
if tuple[5] ~= cas then
self:stat_incr('cas_badval')
else
self:stat_incr('cas_hits')
self.mcs:replace{key, value, exptime, flags, ncas, ptime}
end
else
self:stat_incr('cas_misses')
end
box.commit()
if type(tuple) == 'string' then
outbuf:write_ans('NOT_FOUND')
elseif tuple[5] ~= cas then
outbuf:write_ans('EXISTS')
else
outbuf:write_ans('STORED')
end
return 0
end,
get = function(self, keys, outbuf)
-- Check arguments
-- if keys == nil then return 'CLIENT_ERROR Bad key\r\n' end
-- Execute requests
if type(keys) ~= 'table' then keys = {keys} end
box.begin()
for _, key in ipairs(keys) do
local t = self:get_tuple_or_expire(key)
if (type(t) ~= 'string') then
outbuf:write('VALUE ')
outbuf:write(t[1])
outbuf:write(' ')
outbuf:write(tostring(t[4]))
outbuf:write(' ')
outbuf:write_ans(tostring(#t[2]))
outbuf:write_ans(t[2])
self:stat_incr('get_hits')
else
self:stat_incr('get_misses')
end
end
box.commit()
outbuf:write_ans('END')
return 0
end,
gets = function(self, keys, outbuf)
-- Check arguments
-- if keys == nil then return 'CLIENT_ERROR Bad key\r\n' end
-- Execute requests
if type(keys) ~= 'table' then keys = {keys} end
box.begin()
for _, key in ipairs(keys) do
local t = self:get_tuple_or_expire(key)
if (type(t) ~= 'string') then
outbuf:write('VALUE ')
outbuf:write(t[1])
outbuf:write(' ')
outbuf:write(tostring(t[4]))
outbuf:write(' ')
outbuf:write(tostring(#t[2]))
outbuf:write(' ')
outbuf:write_ans(tostring(t[5]))
outbuf:write_ans(t[2])
self:stat_incr('get_hits')
else
self:stat_incr('get_misses')
end
end
box.commit()
outbuf:write_ans('END')
return 0
end,
delete = function(self, key, noreply, outbuf)
-- Check arguments
-- if key == nil then return 'CLIENT_ERROR Bad key\r\n' end
-- if noreply == nil then noreply = false end
-- if type(noreply) ~= 'boolean' then
-- return 'CLIENT_ERROR Bad type of noreply flag\r\n'
-- end
-- Execute requests
box.begin()
local tuple = self:get_tuple_or_expire(key)
if type(tuple) == 'string' then
self:stat_incr('delete_misses')
else
self.mcs:delete{key}
self:stat_incr('delete_hits')
end
box.commit()
if noreply == true then return end
if type(tuple) == 'string' then
outbuf:write_ans('NOT_FOUND')
else
outbuf:write_ans('DELETED')
end
return 0
end,
incr = function(self, key, value, noreply, outbuf)
-- Check arguments
-- if key == nil then return 'CLIENT_ERROR Bad key\r\n' end
-- if value == nil then return 'CLIENT_ERROR Bad value\r\n' end
-- if noreply == nil then noreply = false end
-- if type(noreply) ~= 'boolean' then
-- return 'CLIENT_ERROR Bad type of noreply flag\r\n'
-- end
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
box.begin()
local t = self:get_tuple_or_expire(key)
log.debug('key, value %s %s', key, tostring(t))
if type(t) == 'string' then
self:stat_incr('incr_misses')
else
self:stat_incr('incr_hits')
num = tonumber64(t[2])
if num == nil then
outbuf:write_cler('cannot increment or decrement non-numeric value')
return 'clerr'
end
num = num + 0ULL
log.debug('incr/decr val ' .. tostring(value))
if (num + value < num and num + value < value) then
num = '18446744073709551615ULL'
else
num = tostring(num + value)
end
num = num:sub(1, -4)
t = self.mcs:update({key}, {{'=', 2, num}, {'=', 5, cas}})
end
box.commit()
if noreply == true then return end
if type(t) == 'string' then
outbuf:write_ans('NOT_FOUND')
else
outbuf:write_ans(string.format('%s', t[2]))
end
return 0
end,
decr = function(self, key, value, noreply, outbuf)
-- Check arguments
-- if key == nil then return 'CLIENT_ERROR Bad key\r\n' end
-- if value == nil then return 'CLIENT_ERROR Bad value\r\n' end
-- if noreply == nil then noreply = false end
-- if type(noreply) ~= 'boolean' then
-- return 'CLIENT_ERROR Bad type of noreply flag\r\n'
-- end
-- Execute requests
local cas = self.casn; self.casn = self.casn + 1
box.begin()
local t = self:get_tuple_or_expire(key)
log.debug('key, value %s %s', key, tostring(t))
if type(t) == 'string' then
self:stat_incr('decr_misses')
else
self:stat_incr('decr_hits')
num = tonumber64(t[2])
if num == nil then
outbuf:write_cler('cannot increment or decrement non-numeric value')
return 'clerr'
end
num = num + 0ULL
log.debug('incr/decr val ' .. tostring(value))
if (num < value) then
num = '0ULL'
else
num = tostring(num - value)
end
num = num:sub(1, -4)
t = self.mcs:update({key}, {{'=', 2, num}, {'=', 5, cas}})
end
box.commit()
if noreply == true then return end
if type(t) == 'string' then
outbuf:write_ans('NOT_FOUND')
else
outbuf:write_ans(string.format('%s', t[2]))
end
return 0
end,
touch = function(self, key, exptime, noreply, outbuf)
-- Check arguments
key = tostring(key)
exptime = self:normalize_exptime(time)
-- Execute requests
self:stat_incr('cmd_touch')
box.begin()
local t, tuple = self:get_tuple_or_expire(key)
if type(tuple) == 'string' then
self:stat_incr('touch_misses')
else
self:stat_incr('touch_hits')
t = self.mcs:update({key}, {{'=', 3, exptime}})
end
box.commit()
if noreply == true then return end
if type(tuple) == 'string' then
outbuf:write_ans('NOT_FOUND')
else
outbuf:write_ans('TOUCHED')
end
return 0
end,
flush_all = function(self, time, outbuf)
self:stat_incr('cmd_flush')
time = self:normalize_flush_time(time)
self.flush = math.max(self.flush, self:normalize_flush_time(time))
outbuf:write_ans('OK')
return 0
end,
cmd_stats = function(self, key, outbuf)
log.debug("%s %d ", key, #key)
if (key == nil or #key == 0) then
log.debug('iterating')
for k, v in pairs(self.stats) do
outbuf:write_ans(string.format('STAT %s %d', k, v))
end
else
if self.stats[key] then
outbuf:write_ans(string.format('STAT %s %d', key, self.stats[key]))
end
end
outbuf:write_ans('END')
return 0
end,
version = function(self)
outbuf:write_ans(
string.format('VERSION Tarantool %s', box.info().version)
)
return 0
end,
destroy = function(self)
mc:stop_loop()
expd.kill_task(self.expd)
expd.mcs:drop()
box.space._schema:delete{self.name}
end
}
local function mc_is_expired(args, tuple)
local time, etime, ptime = (fiber.time()), tuple[3], tuple[6]
-- check for invalidation
if ((ptime <= args.flush and args.flush <= time) or
(etime <= time and etime ~= 0)) then
log.debug('expired by expirationd')
return true
end
return false
end
local function mc_pr_expired(space_id, args, tuple)
local key = fun.map(
function(x) return tuple[x.fieldno] end,
box.space[space_id].index[0].parts
):totable()
args:stat_incr('expired_daemon')
log.debug('lsn before '..tostring(box.info.vclock[1]))
log.debug('expired by expirationd')
local t = box.space[space_id]:delete(key)
log.debug(tostring(t))
local t = box.space[space_id]:get(key)
log.debug(tostring(t))
log.debug('lsn after '..tostring(box.info.vclock[1]))
end
local memcached = {
new = function(name)
local self = setmetatable({}, { __index = memcached_methods })
self.name = name
if box.space[self.name] == nil then
local mcs = box.schema.space.create(self.name)
mcs:create_index('primary', {type='HASH', parts={1, 'STR'}})
elseif box.space._schema:get{self.name} == nil then
error('memcached: space is already used')
end
self.mcs = box.space[self.name]
self.casn = 0
self.flush = -1
self.expd = 'memcached_' .. self.name
expd.run_task(self.expd, self.name, mc_is_expired,
mc_pr_expired, self, 1024, 60*60)
self.stats = {
['cmd_get'] = 0,
['cmd_set'] = 0,
['cmd_flush'] = 0,
['cmd_touch'] = 0,
['get_hits'] = 0,
['get_misses'] = 0,
['delete_hits'] = 0,
['delete_misses'] = 0,
['incr_hits'] = 0,
['incr_misses'] = 0,
['decr_hits'] = 0,
['decr_misses'] = 0,
['cas_hits'] = 0,
['cas_misses'] = 0,
['cas_badval'] = 0,
['touch_hits'] = 0,
['touch_misses'] = 0,
['expired_daemon'] = 0,
['expired_runtime'] = 0,
}
box.space._schema:put{self.name}
return self
end
}
return memcached
| 29,056
|
tarantool/memcached
|
function love.load()
auth = require "lib/auth"
login = require "bin/login"
process = require "lib/process"
sha256 = require "lib/sha256"
end
function love.update()
process.update()
end
function love.draw()
windowCanvases = process.renderCanvases()
window.drawWindows(windowCanvases)
end
| 300
|
BEN1JEN/snowballOS
|
--[[
##########################################################
Inked Shadow Vaults By: keivamp
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local pairs = _G.pairs;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local tinsert = _G.tinsert;
local string = _G.string;
local math = _G.math;
--[[ STRING METHODS ]]--
local lower, upper, len = string.lower, string.upper, string.len;
local match, gsub, find = string.match, string.gsub, string.find;
--[[ MATH METHODS ]]--
local parsefloat = math.parsefloat; -- Uncommon
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = _G['InkedSV']
local L = SV.L
local MOD = SV.Maps;
if(not MOD) then return end;
--[[
##########################################################
LOCALIZED GLOBALS
##########################################################
]]--
local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS
--[[
##########################################################
LOCAL VARS
##########################################################
]]--
local temp = SLASH_CALENDAR1:gsub("/", "");
local calendar_string = temp:gsub("^%l", upper)
local cColor = RAID_CLASS_COLORS[SV.class];
local MMBHolder, MMBBar;
local NewHook = hooksecurefunc
local Initialized = false
local CoordPattern = "%.1f";
--[[
##########################################################
DATA UPVALUES
##########################################################
]]--
local MM_XY_COORD = false;
local WMP_XY_COORD = false;
local WMM_XY_COORD = false;
local WM_TINY = false;
local MM_COLOR = "darkest"
local MM_BRDR = 0
local MM_SIZE = 240
local MM_BTN_SIZE = 30
local MM_BTN_ROW = 8
local MM_OFFSET_TOP = (MM_SIZE * 0.07)
local MM_OFFSET_BOTTOM = (MM_SIZE * 0.11)
local MM_WIDTH = MM_SIZE + (MM_BRDR * 2)
local MM_HEIGHT = (MM_SIZE - (MM_OFFSET_TOP + MM_OFFSET_BOTTOM) + (MM_BRDR * 2))
local WM_ALPHA = false;
local MM_BTN_SIZE = 30;
local MM_SHAPE = 'RECTANGLE';
local NARR_TEXT = "Meanwhile";
local NARR_PREFIX = "In ";
--[[
##########################################################
MODULE CHILDREN
##########################################################
]]--
MOD.MinimapButtons = {}
MOD.Holder = _G["InkedSV_MinimapFrame"];
MOD.InfoTop = _G["InkedSV_MinimapInfoTop"];
MOD.InfoBottom = _G["InkedSV_MinimapInfoBottom"];
local MiniMapCoords = _G["InkedSV_MiniMapCoords"];
local WorldMapCoords = _G["InkedSV_WorldMapCoords"];
local InkedSV_MinimapFrame = CreateFrame("Frame", "InkedSV_MinimapFrame", UIParent)
local WMCoords = CreateFrame('Frame', 'InkedSV_WorldMapCoords', WorldMapFrame)
InkedSV_MinimapFrame:SetSize(MM_WIDTH, MM_HEIGHT);
--[[
##########################################################
GENERAL HELPERS
##########################################################
]]--
--[[
/$$$$$$$ /$$ /$$ /$$$$$$$$/$$$$$$$$/$$$$$$ /$$ /$$ /$$$$$$
| $$__ $$| $$ | $$|__ $$__/__ $$__/$$__ $$| $$$ | $$ /$$__ $$
| $$ \ $$| $$ | $$ | $$ | $$ | $$ \ $$| $$$$| $$| $$ \__/
| $$$$$$$ | $$ | $$ | $$ | $$ | $$ | $$| $$ $$ $$| $$$$$$
| $$__ $$| $$ | $$ | $$ | $$ | $$ | $$| $$ $$$$ \____ $$
| $$ \ $$| $$ | $$ | $$ | $$ | $$ | $$| $$\ $$$ /$$ \ $$
| $$$$$$$/| $$$$$$/ | $$ | $$ | $$$$$$/| $$ \ $$| $$$$$$/
|_______/ \______/ |__/ |__/ \______/ |__/ \__/ \______/
--]]
local MMB_OnEnter = function(self)
if(not SV.db.Maps.minimapbar.mouseover or SV.db.Maps.minimapbar.styleType == "NOANCHOR") then return end
UIFrameFadeIn(InkedSV_MiniMapButtonBar, 0.2, InkedSV_MiniMapButtonBar:GetAlpha(), 1)
if self:GetName() ~= "InkedSV_MiniMapButtonBar" then
self:SetBackdropBorderColor(.7, .7, 0)
end
end
local MMB_OnLeave = function(self)
if(not SV.db.Maps.minimapbar.mouseover or SV.db.Maps.minimapbar.styleType == "NOANCHOR") then return end
UIFrameFadeOut(InkedSV_MiniMapButtonBar, 0.2, InkedSV_MiniMapButtonBar:GetAlpha(), 0)
if self:GetName() ~= "InkedSV_MiniMapButtonBar" then
self:SetBackdropBorderColor(0, 0, 0)
end
end
do
local reserved = {"Node", "Tab", "Pin", "InkedSV_ConsolidatedBuffs", "GameTimeframe", "HelpOpenTicketButton", "InkedSV_MinimapFrame", "InkedSV_EnhancedMinimap", "QueueStatusMinimapButton", "TimeManagerClockButton", "Archy", "GatherMatePin", "GatherNote", "GuildInstance", "HandyNotesPin", "MinimMap", "Spy_MapNoteList_mini", "ZGVMarker", "ZygorGuidesViewerMapIcon"}
local function UpdateMinimapButtons()
if(not SV.db.Maps.minimapbar.enable) then return end
MMBBar:SetPoint("CENTER", MMBHolder, "CENTER", 0, 0)
MMBBar:SetHeight(MM_BTN_SIZE + 4)
MMBBar:SetWidth(MM_BTN_SIZE + 4)
MMBBar:SetFrameStrata("LOW")
MMBBar:SetFrameLevel(0)
local list = MOD.MinimapButtons
local count,column = 0,1;
for name,btn in pairs(list) do
local preset = btn.preset;
if(SV.db.Maps.minimapbar.styleType == "NOANCHOR") then
btn:SetParent(preset.Parent)
if preset.DragStart then
btn:SetScript("OnDragStart", preset.DragStart)
end
if preset.DragEnd then
btn:SetScript("OnDragStop", preset.DragEnd)
end
btn:ClearAllPoints()
btn:SetSize(preset.Width, preset.Height)
btn:SetPoint(preset.Point, preset.relativeTo, preset.relativePoint, preset.xOfs, preset.yOfs)
btn:SetFrameStrata(preset.FrameStrata)
btn:SetFrameLevel(preset.FrameLevel)
btn:SetScale(preset.Scale)
btn:SetMovable(true)
else
btn:SetParent(MMBBar)
btn:SetMovable(false)
btn:SetScript("OnDragStart", nil)
btn:SetScript("OnDragStop", nil)
btn:ClearAllPoints()
btn:SetFrameStrata("LOW")
btn:SetFrameLevel(20)
btn:SetSize(MM_BTN_SIZE, MM_BTN_SIZE)
if(column > MM_BTN_ROW) then
column = 1;
end
local xPos, yPos = 0,0;
local row = floor(count / MM_BTN_ROW);
if SV.db.Maps.minimapbar.styleType == "HORIZONTAL"then
xPos = ((MM_BTN_SIZE + 2) * column);
yPos = ((MM_BTN_SIZE + 2) * row);
else
xPos = ((MM_BTN_SIZE + 2) * row);
yPos = ((MM_BTN_SIZE + 2) * column);
end
btn:SetPoint("TOPRIGHT", MMBBar, "TOPRIGHT", -xPos, -yPos)
end
column = column + 1;
count = count + 1;
end
if (SV.db.Maps.minimapbar.styleType ~= "NOANCHOR" and (count > 0)) then
if SV.db.Maps.minimapbar.styleType == "HORIZONTAL" then
MMBBar:SetWidth((MM_BTN_SIZE + 2) * MM_BTN_ROW)
else
MMBBar:SetHeight((MM_BTN_SIZE + 2) * MM_BTN_ROW)
end
MMBHolder:SetSize(MMBBar:GetSize())
MMBBar:Show()
else
MMBBar:Hide()
end
end
local function SetMinimapButton(btn)
if btn == nil or btn:GetName() == nil or btn:GetObjectType() ~= "Button" or not btn:IsVisible() then return end
local name = btn:GetName()
local isLib = false;
if name:sub(1,len("LibDBIcon")) == "LibDBIcon" then isLib = true end
if(not isLib) then
local count = #reserved
for i = 1, count do
if name:sub(1,len(reserved[i])) == reserved[i] then return end
if name:find(reserved[i]) ~= nil then return end
end
end
btn:SetPushedTexture("")
btn:SetHighlightTexture("")
btn:SetDisabledTexture("")
if not btn.isStyled then
btn:HookScript("OnEnter", MMB_OnEnter)
btn:HookScript("OnLeave", MMB_OnLeave)
btn:HookScript("OnClick", UpdateMinimapButtons)
btn.preset = {}
btn.preset.Width, btn.preset.Height = btn:GetSize()
btn.preset.Point, btn.preset.relativeTo, btn.preset.relativePoint, btn.preset.xOfs, btn.preset.yOfs = btn:GetPoint()
btn.preset.Parent = btn:GetParent()
btn.preset.FrameStrata = btn:GetFrameStrata()
btn.preset.FrameLevel = btn:GetFrameLevel()
btn.preset.Scale = btn:GetScale()
if btn:HasScript("OnDragStart") then
btn.preset.DragStart = btn:GetScript("OnDragStart")
end
if btn:HasScript("OnDragEnd") then
btn.preset.DragEnd = btn:GetScript("OnDragEnd")
end
for i = 1, btn:GetNumRegions() do
local frame = select(i, btn:GetRegions())
if frame:GetObjectType() == "Texture" then
local iconFile = frame:GetTexture()
--JV: Check type in case iconFile is a number - reported error involving LiDBIcon - need to find root cause
if((iconFile ~= nil and type(iconFile) == "string") and (iconFile:find("Border") or iconFile:find("Background") or iconFile:find("AlphaMask"))) then
frame:SetTexture("")
else
frame:ClearAllPoints()
frame:SetPoint("TOPLEFT", btn, "TOPLEFT", 2, -2)
frame:SetPoint("BOTTOMRIGHT", btn, "BOTTOMRIGHT", -2, 2)
frame:SetTexCoord(0.1, 0.9, 0.1, 0.9 )
frame:SetDrawLayer("ARTWORK")
if name == "PS_MinimapButton" then
frame.SetPoint = SV.fubar
end
end
end
end
btn:SetStyle("Button", -1, -1)
if(name == "DBMMinimapButton") then
btn:SetNormalTexture("Interface\\Icons\\INV_Helmet_87")
end
if(name == "SmartBuff_MiniMapButton") then
btn:SetNormalTexture(select(3, GetSpellInfo(12051)))
end
btn.isStyled = true
MOD.MinimapButtons[name] = btn
end
end
local StyleMinimapButtons = function()
local count = Minimap:GetNumChildren()
for i=1, count do
local child = select(i,Minimap:GetChildren())
SetMinimapButton(child)
end
UpdateMinimapButtons()
if SV.db.Maps.minimapbar.mouseover then
MMBBar:SetAlpha(0)
else
MMBBar:SetAlpha(1)
end
end
function MOD:UpdateMinimapButtonSettings(notimer)
if(not SV.db.Maps.minimapbar.enable or not MMBBar:IsShown()) then return end
if(notimer) then
StyleMinimapButtons()
else
SV.Timers:ExecuteTimer(StyleMinimapButtons, 4)
end
end
end
local function UpdateMiniMapCoords()
if(WMP_XY_COORD and WorldMapFrame:IsShown()) then return end
if (IsInInstance()) then return end
local map = C_Map.GetBestMapForUnit("player")
local cmap = C_Map.GetBestMapForUnit("player")
local position = C_Map.GetPlayerMapPosition(map, "player");
--print(position.x)
local playerX = position.x
local playerY = position.y
if((playerX ~= 0 and playerY ~= 0)) then
playerX = parsefloat(100 * playerX, 2)
playerY = parsefloat(100 * playerY, 2)
if(playerX ~= 0 and playerY ~= 0) then
if(not MiniMapCoords:IsShown()) then
MiniMapCoords:FadeIn()
end
MiniMapCoords.XLabel:SetText("X:")
MiniMapCoords.X:SetFormattedText(CoordPattern, playerX)
MiniMapCoords.YLabel:SetText("Y:")
MiniMapCoords.Y:SetFormattedText(CoordPattern, playerY)
else
-- if(MiniMapCoords:IsShown()) then
-- MiniMapCoords:FadeOut(0.2, 1, 0)
-- end
MiniMapCoords.XLabel:SetText("")
MiniMapCoords.X:SetText("")
MiniMapCoords.YLabel:SetText("")
MiniMapCoords.Y:SetText("")
end
else
MiniMapCoords.XLabel:SetText("")
MiniMapCoords.X:SetText("")
MiniMapCoords.YLabel:SetText("")
MiniMapCoords.Y:SetText("")
end
end
local function UpdateWorldMapCoords()
if(not WorldMapFrame:IsShown()) then return end
if (IsInInstance()) then return end
if(WMP_XY_COORD) then
local cmap = C_Map.GetBestMapForUnit("player")
local position = C_Map.GetPlayerMapPosition(cmap, "player");
local playerX = position.x
local playerY = position.y
if((playerX ~= 0 and playerY ~= 0)) then
playerX = parsefloat(100 * playerX, 2)
playerY = parsefloat(100 * playerY, 2)
if(playerX ~= 0 and playerY ~= 0) then
if(not WorldMapCoords.Player:IsShown()) then
WorldMapCoords.Player:FadeIn()
end
WorldMapCoords.Player.X:SetFormattedText(CoordPattern, playerX)
WorldMapCoords.Player.Y:SetFormattedText(CoordPattern, playerY)
else
WorldMapCoords.Player:FadeOut(0.2, 1, 0, true)
end
else
WorldMapCoords.Player:FadeOut(0.2, 1, 0, true)
end
end
if(WMM_XY_COORD) then
local scale = WorldMapFrame:GetEffectiveScale()
local width = WorldMapFrame:GetWidth()
local height = WorldMapFrame:GetHeight()
local centerX, centerY = WorldMapFrame:GetCenter()
local cursorX, cursorY = GetCursorPosition()
local mouseX = (cursorX / scale - (centerX - (width / 2))) / width;
local mouseY = (centerY + (height / 2) - cursorY / scale) / height;
if(((mouseX >= 0) and (mouseX <= 1)) and ((mouseY >= 0) and (mouseY <= 1))) then
mouseX = parsefloat(100 * mouseX, 2)
mouseY = parsefloat(100 * mouseY, 2)
if(not WorldMapCoords.Mouse:IsShown()) then
WorldMapCoords.Mouse:FadeIn()
end
WorldMapCoords.Mouse.X:SetFormattedText(CoordPattern, mouseX)
WorldMapCoords.Mouse.Y:SetFormattedText(CoordPattern, mouseY)
else
WorldMapCoords.Mouse:FadeOut(0.2, 1, 0, true)
end
end
--[[if(WM_ALPHA and (not WorldMapFrame_InWindowedMode())) then
local speed = GetUnitSpeed("player")
if(speed ~= 0) then
WorldMapFrame:SetAlpha(0.2)
else
WorldMapFrame:SetAlpha(1)
end
end]]--
end
--[[
/$$ /$$ /$$$$$$ /$$$$$$$ /$$ /$$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$
| $$ /$ | $$ /$$__ $$| $$__ $$| $$ | $$__ $$| $$$ /$$$ /$$__ $$| $$__ $$
| $$ /$$$| $$| $$ \ $$| $$ \ $$| $$ | $$ \ $$| $$$$ /$$$$| $$ \ $$| $$ \ $$
| $$/$$ $$ $$| $$ | $$| $$$$$$$/| $$ | $$ | $$| $$ $$/$$ $$| $$$$$$$$| $$$$$$$/
| $$$$_ $$$$| $$ | $$| $$__ $$| $$ | $$ | $$| $$ $$$| $$| $$__ $$| $$____/
| $$$/ \ $$$| $$ | $$| $$ \ $$| $$ | $$ | $$| $$\ $ | $$| $$ | $$| $$
| $$/ \ $$| $$$$$$/| $$ | $$| $$$$$$$$| $$$$$$$/| $$ \/ | $$| $$ | $$| $$
|__/ \__/ \______/ |__/ |__/|________/|_______/ |__/ |__/|__/ |__/|__/
--]]
local function SetLargeWorldMap()
if InCombatLockdown() then return end
if SV.db.Maps.tinyWorldMap == true then
-- WorldMapFrame:SetParent(SV.Screen)
WorldMapFrame:EnableMouse(false)
WorldMapFrame:EnableKeyboard(false)
WorldMapFrame:SetScale(1)
if WorldMapFrame:GetAttribute('UIPanelLayout-area') ~= 'center'then
SetUIPanelAttribute(WorldMapFrame, "area", "center")
end
if WorldMapFrame:GetAttribute('UIPanelLayout-allowOtherPanels') ~= true then
SetUIPanelAttribute(WorldMapFrame, "allowOtherPanels", true)
end
end
--WorldMapFrameSizeUpButton:Hide()
--WorldMapFrameSizeDownButton:Show()
end
local function SetSmallWorldMap()
if InCombatLockdown() then return end
--WorldMapFrameSizeUpButton:Show()
--WorldMapFrameSizeDownButton:Hide()
end
local function AdjustMapSize()
if InCombatLockdown() then return end
--[[if WORLDMAP_SETTINGS.size == WORLDMAP_FULLMAP_SIZE then
WorldMapFrame:SetPoint("TOP", SV.Screen, "TOP", 0, 0)
end
if SV.db.Maps.tinyWorldMap == true then
BlackoutWorld:SetTexture("")
else
BlackoutWorld:SetColorTexture(0, 0, 0, 1)
end--]]
end
local function UpdateWorldMapConfig()
if(not MM_XY_COORD) then
if MOD.MMCoordTimer then
SV.Timers:RemoveLoop(MOD.MMCoordTimer)
MOD.MMCoordTimer = nil;
end
MiniMapCoords.XLabel:SetText("")
MiniMapCoords.X:SetText("")
MiniMapCoords.YLabel:SetText("")
MiniMapCoords.Y:SetText("")
else
MiniMapCoords.XLabel:SetText("X:")
MiniMapCoords.YLabel:SetText("Y:")
UpdateMiniMapCoords()
MOD.MMCoordTimer = SV.Timers:ExecuteLoop(UpdateMiniMapCoords, 0.1)
end
if((not WMP_XY_COORD) and (not WMM_XY_COORD)) then
if MOD.WMCoordTimer then
SV.Timers:RemoveLoop(MOD.WMCoordTimer)
MOD.WMCoordTimer = nil;
end
WorldMapCoords.Player.Name:SetText("")
WorldMapCoords.Player.XLabel:SetText("")
WorldMapCoords.Player.X:SetText("")
WorldMapCoords.Player.YLabel:SetText("")
WorldMapCoords.Player.Y:SetText("")
WorldMapCoords.Mouse.Name:SetText("")
WorldMapCoords.Mouse.XLabel:SetText("")
WorldMapCoords.Mouse.X:SetText("")
WorldMapCoords.Mouse.YLabel:SetText("")
WorldMapCoords.Mouse.Y:SetText("")
else
if(not WMP_XY_COORD) then
WorldMapCoords.Player.XLabel:SetText("")
WorldMapCoords.Player.X:SetText("")
WorldMapCoords.Player.YLabel:SetText("")
WorldMapCoords.Player.Y:SetText("")
WorldMapCoords.Player.Name:SetText("");
else
WorldMapCoords.Player.XLabel:SetText("X:")
WorldMapCoords.Player.YLabel:SetText("Y:")
WorldMapCoords.Player.Name:SetText(PLAYER);
end
if(not WMM_XY_COORD) then
WorldMapCoords.Mouse.XLabel:SetText("")
WorldMapCoords.Mouse.X:SetText("")
WorldMapCoords.Mouse.YLabel:SetText("")
WorldMapCoords.Mouse.Y:SetText("")
WorldMapCoords.Mouse.Name:SetText("");
else
WorldMapCoords.Mouse.XLabel:SetText("X:")
WorldMapCoords.Mouse.YLabel:SetText("Y:")
WorldMapCoords.Mouse.Name:SetText(MOUSE_LABEL);
end
UpdateWorldMapCoords()
MOD.WMCoordTimer = SV.Timers:ExecuteLoop(UpdateWorldMapCoords, 0.1)
end
if InCombatLockdown()then return end
--[[if(not MOD.WorldMapHooked) then
NewHook("WorldMap_ToggleSizeUp", AdjustMapSize)
--Removed for 7.3
--NewHook("WorldMap_ToggleSizeDown", SetSmallWorldMap)
MOD.WorldMapHooked = true
end--]]
AdjustMapSize()
end
--[[
##########################################################
HANDLERS
##########################################################
]]--
local MiniMap_MouseUp = function(self, btn)
local position = self:GetPoint()
if btn == "RightButton" then
local xoff = -1
if position:match("RIGHT") then xoff = -16 end
ToggleDropDownMenu(1, nil, MiniMapTrackingDropDown, self, xoff, -3)
else
Minimap_OnClick(self)
end
end
local MiniMap_MouseWheel = function(self, delta)
if delta > 0 then
_G.MinimapZoomIn:Click()
elseif delta < 0 then
_G.MinimapZoomOut:Click()
end
end
local Calendar_OnClick = function(self)
GameTimeFrame:Click();
end
local Tracking_OnClick = function(self)
local position = self:GetPoint()
local xoff = -1
if position:match("RIGHT") then xoff = -16 end
ToggleDropDownMenu(1, nil, MiniMapTrackingDropDown, self, xoff, -3)
end
local Basic_OnEnter = function(self)
GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT", 0, 4)
GameTooltip:ClearLines()
GameTooltip:AddLine(self.TText, 1, 1, 1)
GameTooltip:Show()
end
local Basic_OnLeave = function(self)
GameTooltip:Hide()
end
local Tour_OnEnter = function(self, ...)
if InCombatLockdown() then
GameTooltip:Hide()
else
GameTooltip:SetOwner(self, "ANCHOR_BOTTOM", 0, -4)
GameTooltip:ClearAllPoints()
GameTooltip:SetPoint("BOTTOM", self, "BOTTOM", 0, 0)
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(L["Click : "], L["Toggle WorldMap"], 0.7, 0.7, 1, 0.7, 0.7, 1)
GameTooltip:AddDoubleLine(L["ShiftClick : "], L["Announce your position in chat"],0.7, 0.7, 1, 0.7, 0.7, 1)
GameTooltip:Show()
end
end
local Tour_OnLeave = function(self, ...)
GameTooltip:Hide()
end
local Tour_OnClick = function(self, btn)
if IsShiftKeyDown() then
local zoneText = GetRealZoneText() or UNKNOWN;
local subZone = GetSubZoneText() or UNKNOWN;
local edit_box = ChatEdit_ChooseBoxForSend();
local cmap = C_Map.GetBestMapForUnit("player")
local position = C_Map.GetPlayerMapPosition(cmap, "player");
local x = position.x
local y = position.y
x = tonumber(parsefloat(100 * x, 0));
y = tonumber(parsefloat(100 * y, 0));
local coords = ("%d, %d"):format(x, y);
ChatEdit_ActivateChat(edit_box)
if(zoneText ~= subZone) then
local message = ("%s: %s (%s)"):format(zoneText, subZone, coords)
edit_box:Insert(message)
else
local message = ("%s (%s)"):format(zoneText, coords)
edit_box:Insert(message)
end
else
ToggleFrame(WorldMapFrame)
end
GameTooltip:Hide()
end
--[[
##########################################################
HOOKS
##########################################################
]]--
local _hook_WorldMapZoneDropDownButton_OnClick = function(self)
DropDownList1:ClearAllPoints()
DropDownList1:SetPoint("TOPRIGHT",self,"BOTTOMRIGHT",-17,-4)
end
local _hook_WorldMapFrame_OnShow = function()
MOD:RegisterEvent("PLAYER_REGEN_DISABLED");
if InCombatLockdown()then return end
if(not SV.db.Maps.tinyWorldMap and not Initialized) then
WorldMap_ToggleSizeUp()
Initialized = true
end
end
local _hook_WorldMapFrame_OnHide = function()
MOD:UnregisterEvent("PLAYER_REGEN_DISABLED")
end
local _hook_DropDownList1 = function(self)
local parentScale = UIParent:GetScale()
if(self:GetScale() ~= parentScale) then
self:SetScale(parentScale)
end
end
--[[
##########################################################
EVENTS
##########################################################
]]--
function MOD:RefreshZoneText()
if(not SV.db.Maps.locationText or SV.db.Maps.locationText == "HIDE") then
self.InfoTop:Hide();
self.InfoBottom:Hide();
else
if(SV.db.Maps.locationText == "SIMPLE") then
self.InfoTop:Hide();
self.InfoBottom:Show();
NARR_TEXT = "";
NARR_PREFIX = "";
self.InfoTop.Text:SetText(NARR_TEXT)
else
self.InfoTop:Show();
self.InfoBottom:Show();
NARR_TEXT = L['Meanwhile'];
NARR_PREFIX = L["..at "];
self.InfoTop.Text:SetText(NARR_TEXT)
end
local zone = GetMinimapZoneText() or UNKNOWN
zone = zone:sub(1, 25);
local zoneText = ("%s%s"):format(NARR_PREFIX, zone);
self.InfoBottom.Text:SetText(zoneText)
end
end
local InfoBottom_OnEnter = function(self)
if(not self:IsShown()) then return end
local zone = GetRealZoneText() or UNKNOWN
zone = zone:sub(1, 25);
local zoneText = ("%s%s"):format(L["..in "], zone);
self.Text:SetText(zoneText)
end
local InfoBottom_OnLeave = function(self)
if(not self:IsShown()) then return end
local zone = GetMinimapZoneText() or UNKNOWN
zone = zone:sub(1, 25);
local zoneText = ("%s%s"):format(NARR_PREFIX, zone);
self.Text:SetText(zoneText)
end
function MOD:ADDON_LOADED(event, addon)
if TimeManagerClockButton then
TimeManagerClockButton:Die()
end
self:UnregisterEvent("ADDON_LOADED")
if addon == "Blizzard_FeedbackUI" then
FeedbackUIButton:Die()
end
self:UpdateMinimapButtonSettings()
end
function MOD:PLAYER_REGEN_ENABLED()
--WorldMapFrameSizeDownButton:Enable()
--WorldMapFrameSizeUpButton:Enable()
if(self.CombatLocked) then
self:RefreshMiniMap()
self.CombatLocked = nil
end
end
function MOD:PLAYER_REGEN_DISABLED()
--WorldMapFrameSizeDownButton:Disable()
--WorldMapFrameSizeUpButton:Disable()
end
--[[
##########################################################
CORE FUNCTIONS
##########################################################
]]--
function MOD:RefreshMiniMap()
if(InCombatLockdown()) then
self.CombatLocked = true
return
end
self:UpdateLocals()
if(self.Holder and self.Holder:IsShown()) then
local minimapRotationEnabled = GetCVar("rotateMinimap") ~= "0"
if(minimapRotationEnabled or (MM_SHAPE == 'ROUND')) then
--SV.Dock.TopRight:SetSize(MM_WIDTH, (MM_WIDTH + 4))
self.Holder:SetSize(MM_WIDTH, MM_WIDTH)
Minimap:SetSize(MM_SIZE,MM_SIZE)
self.Holder.Square:Hide()
self.Holder.Circle:Show()
Minimap:SetHitRectInsets(0, 0, 0, 0)
Minimap:InsetPoints(self.Holder, MM_BRDR, MM_BRDR)
Minimap:SetMaskTexture('Textures\\MinimapMask')
else
--SV.Dock.TopRight:SetSize(MM_WIDTH, (MM_HEIGHT + 4))
self.Holder:SetSize(MM_WIDTH, MM_HEIGHT)
Minimap:SetSize(MM_SIZE,MM_SIZE)
self.Holder.Circle:Hide()
self.Holder.Square:Show()
self.Holder.Square:SetPanelColor(MM_COLOR)
if MM_SHAPE == 'RECTANGLE' then
Minimap:SetPoint("BOTTOMLEFT", self.Holder, "BOTTOMLEFT", MM_BRDR, (MM_OFFSET_BOTTOM - MM_BRDR) * -1)
Minimap:SetPoint("TOPRIGHT", self.Holder, "TOPRIGHT", -MM_BRDR, (MM_OFFSET_TOP - MM_BRDR))
Minimap:SetMaskTexture(MOD.media.rectangleMask)
else
Minimap:SetHitRectInsets(0, 0, 0, 0)
Minimap:InsetPoints(self.Holder, MM_BRDR, MM_BRDR)
Minimap:SetMaskTexture(MOD.media.squareMask)
end
end
Minimap:SetParent(self.Holder)
Minimap:SetZoom(1)
Minimap:SetZoom(0)
if(SV.Auras and self.Holder.Grip) then
SV.Auras:UpdateAuraHolder(MM_HEIGHT, self.Holder.Grip)
end
--else
--SV.Dock.TopRight:SetSize(MM_WIDTH, (MM_HEIGHT + 4))
end
--self.InfoTop.Text:SetSize(MM_WIDTH,28)
self.InfoBottom.Text:SetSize(MM_WIDTH,32)
self:RefreshZoneText()
if TimeManagerClockButton then
TimeManagerClockButton:Die()
end
UpdateWorldMapConfig()
end
local function RotationHook()
MOD:RefreshMiniMap()
end
--[[
##########################################################
BUILD FUNCTION / UPDATE
##########################################################
]]--
function MOD:UpdateLocals()
local db = SV.db.Maps
if not db then return end
MM_XY_COORD = db.miniPlayerXY;
WMP_XY_COORD = db.worldPlayerXY;
WMM_XY_COORD = db.worldMouseXY;
WM_TINY = db.tinyWorldMap;
MM_COLOR = db.bordercolor
MM_BRDR = db.bordersize or 0
MM_SIZE = db.size or 240
MM_OFFSET_TOP = (MM_SIZE * 0.07)
MM_OFFSET_BOTTOM = (MM_SIZE * 0.11)
MM_WIDTH = MM_SIZE + (MM_BRDR * 2)
MM_SHAPE = db.mapShape;
MM_BTN_SIZE = db.minimapbar.buttonSize;
MM_BTN_ROW = db.minimapbar.perRow;
MM_HEIGHT = (MM_SHAPE == 'RECTANGLE') and (MM_SIZE - (MM_OFFSET_TOP + MM_OFFSET_BOTTOM) + (MM_BRDR * 2)) or MM_WIDTH
WM_ALPHA = GetCVarBool("mapFade")
end
function MOD:ReLoad()
self:RefreshMiniMap()
self:UpdateMinimapButtonSettings(true)
end
local function MapTriggerFired()
MOD:RefreshMiniMap()
MOD:UpdateMinimapButtonSettings()
end
local _hook_BlipTextures = function(self, texture)
if(SV.db.Maps.customIcons and (texture ~= MOD.media.customBlips)) then
self:SetBlipTexture(MOD.media.customBlips)
else
if((not SV.db.Maps.customIcons) and texture ~= MOD.media.defaultBlips) then
self:SetBlipTexture(MOD.media.defaultBlips)
end
end
end
function MOD:Load()
self:UpdateLocals()
--Minimap:SetPlayerTexture(MOD.media.playerArrow)
--Minimap:SetCorpsePOIArrowTexture(MOD.media.corpseArrow)
--Minimap:SetPOIArrowTexture(MOD.media.guideArrow)
if(SV.db.Maps.customIcons) then
--Minimap:SetBlipTexture(MOD.media.customBlips)
else
--Minimap:SetBlipTexture(MOD.media.defaultBlips)
end
Minimap:SetClampedToScreen(false)
if TimeManagerClockButton then
TimeManagerClockButton:Die()
end
Minimap:SetQuestBlobRingAlpha(0)
Minimap:SetArchBlobRingAlpha(0)
Minimap:SetParent(self.Holder)
Minimap:SetFrameStrata("LOW")
Minimap:SetFrameLevel(Minimap:GetFrameLevel() + 2)
self.Holder:SetFrameLevel(Minimap:GetFrameLevel() - 2)
self.Holder:SetFrameStrata("LOW")
self.Holder:SetPoint("TOPRIGHT", SV.Dock.Top, "TOPRIGHT", -15, -18)
self.Holder:SetSize(MM_WIDTH, MM_HEIGHT)
self.Holder.Square = CreateFrame("Frame", nil, self.Holder)
self.Holder.Square:WrapPoints(self.Holder, 2)
self.Holder.Square:SetStyle("Frame", "Minimap")
self.Holder.Square:SetPanelColor(MM_COLOR)
self.Holder.Circle = self.Holder:CreateTexture(nil, "BACKGROUND", nil, -2)
self.Holder.Circle:WrapPoints(self.Holder, 2)
self.Holder.Circle:SetTexture(MOD.media.roundBorder)
self.Holder.Circle:SetVertexColor(0,0,0)
self.Holder.Circle:Hide()
--ShowUIPanel(SpellBookFrame)
HideUIPanel(SpellBookFrame)
MinimapBorder:Hide()
MinimapBorderTop:Hide()
MinimapZoomIn:Hide()
MinimapZoomOut:Hide()
--MiniMapVoiceChatFrame:Hide()
MinimapNorthTag:Die()
GameTimeFrame:Hide()
MinimapZoneTextButton:Hide()
MiniMapTracking:Hide()
MiniMapMailFrame:ClearAllPoints()
MiniMapMailFrame:SetPoint("TOPRIGHT", self.Holder, 3, 4)
MiniMapMailBorder:Hide()
MiniMapMailIcon:SetTexture(MOD.media.mailIcon)
MiniMapWorldMapButton:Hide()
MiniMapInstanceDifficulty:ClearAllPoints()
MiniMapInstanceDifficulty:SetParent(Minimap)
MiniMapInstanceDifficulty:SetPoint("LEFT", self.Holder, "LEFT", 0, 0)
GuildInstanceDifficulty:ClearAllPoints()
GuildInstanceDifficulty:SetParent(Minimap)
GuildInstanceDifficulty:SetPoint("LEFT", self.Holder, "LEFT", 0, 0)
MiniMapChallengeMode:ClearAllPoints()
MiniMapChallengeMode:SetParent(Minimap)
MiniMapChallengeMode:SetPoint("LEFT", self.Holder, "LEFT", 12, 0)
QueueStatusMinimapButton:ClearAllPoints()
QueueStatusMinimapButton:SetPoint("BOTTOMLEFT", self.Holder, "BOTTOMLEFT", 2, 1)
QueueStatusMinimapButton:SetStyle("Frame", "Default", true, 1, -4, -4)
QueueStatusFrame:SetClampedToScreen(true)
QueueStatusMinimapButtonBorder:Hide()
QueueStatusMinimapButton:SetScript("OnShow", function()
MiniMapInstanceDifficulty:SetPoint("BOTTOMLEFT", QueueStatusMinimapButton, "TOPLEFT", 0, 0)
GuildInstanceDifficulty:SetPoint("BOTTOMLEFT", QueueStatusMinimapButton, "TOPLEFT", 0, 0)
MiniMapChallengeMode:SetPoint("BOTTOMLEFT", QueueStatusMinimapButton, "TOPRIGHT", 0, 0)
end)
QueueStatusMinimapButton:SetScript("OnHide", function()
MiniMapInstanceDifficulty:SetPoint("LEFT", self.Holder, "LEFT", 0, 0)
GuildInstanceDifficulty:SetPoint("LEFT", self.Holder, "LEFT", 0, 0)
MiniMapChallengeMode:SetPoint("LEFT", self.Holder, "LEFT", 12, 0)
end)
if FeedbackUIButton then
FeedbackUIButton:Die()
end
local mwfont = SV.media.font.narrator
self.InfoTop:SetPoint("TOPLEFT", self.Holder, "TOPLEFT", 4, -4)
--self.InfoTop:SetSize(100, 22)
self.InfoTop:SetStyle("Frame")
self.InfoTop:SetPanelColor("yellow")
self.InfoTop:SetBackdropColor(1, 1, 0, 1)
self.InfoTop:SetFrameLevel(Minimap:GetFrameLevel() + 2)
self.InfoTop.Text:SetShadowColor(0, 0, 0, 0.3)
self.InfoTop.Text:SetShadowOffset(2, -2);
self.InfoTop.Panel:ClearAllPoints();
self.InfoTop.Panel:SetPoint("TOPLEFT", self.InfoTop.Text, "TOPLEFT", -4, 4);
self.InfoTop.Panel:SetPoint("BOTTOMRIGHT", self.InfoTop.Text, "BOTTOMRIGHT", 4, -4);
self.InfoTop.Panel:SetAttribute("panelLocked", true);
self.InfoBottom:SetPoint("BOTTOMRIGHT", self.Holder, "BOTTOMRIGHT", -MM_BRDR, -3)
self.InfoBottom:SetSize(MM_WIDTH, 28)
self.InfoBottom:SetFrameLevel(Minimap:GetFrameLevel() + 1)
self.InfoBottom.Text:SetShadowColor(0, 0, 0, 0.3)
self.InfoBottom.Text:SetShadowOffset(-2, 2)
self.InfoBottom:SetScript("OnEnter", InfoBottom_OnEnter)
self.InfoBottom:SetScript("OnLeave", InfoBottom_OnLeave)
Minimap:EnableMouseWheel(true)
Minimap:SetScript("OnMouseWheel", MiniMap_MouseWheel)
Minimap:SetScript("OnMouseUp", MiniMap_MouseUp)
SV:NewAnchor(self.Holder, L["Minimap"])
if(SV.db.Maps.tinyWorldMap) then
setfenv(WorldMapFrame_OnShow, setmetatable({ UpdateMicroButtons = SV.fubar }, { __index = _G }))
WorldMapFrame:SetParent(SV.Screen)
WorldMapFrame:HookScript('OnShow', _hook_WorldMapFrame_OnShow)
WorldMapFrame:HookScript('OnHide', _hook_WorldMapFrame_OnHide)
end
WorldMapCoords:SetFrameLevel(QuestLogPopupDetailFrame:GetFrameLevel() + 1);
WorldMapCoords:SetFrameStrata(QuestLogPopupDetailFrame:GetFrameStrata());
WorldMapCoords.Player.Name:SetText(PLAYER);
WorldMapCoords.Mouse.Name:SetText(MOUSE_LABEL);
SV:NewAnchor(WorldMapCoords, L["WorldMap Coordinates"])
DropDownList1:HookScript('OnShow', _hook_DropDownList1)
WorldFrame:SetAllPoints()
SV:ManageVisibility(self.Holder)
MiniMapCoords:ClearAllPoints()
MiniMapCoords:SetFrameLevel(Minimap:GetFrameLevel() + 1)
MiniMapCoords:SetFrameStrata(Minimap:GetFrameStrata())
MiniMapCoords:SetPoint("TOPLEFT", self.Holder, "BOTTOMLEFT", 0, -4)
MiniMapCoords:SetWidth(self.Holder:GetWidth())
MiniMapCoords:EnableMouse(true)
MiniMapCoords:SetScript("OnEnter",Tour_OnEnter)
MiniMapCoords:SetScript("OnLeave",Tour_OnLeave)
MiniMapCoords:SetScript("OnMouseDown",Tour_OnClick)
MiniMapCoords.X:SetTextColor(cColor.r, cColor.g, cColor.b)
MiniMapCoords.Y:SetTextColor(cColor.r, cColor.g, cColor.b)
if (SV.db.Maps.calendarShortcut) then
local calendarButton = CreateFrame("Button", "InkedSV_CalendarButton", MiniMapCoords)
calendarButton:SetSize(22,22)
calendarButton:SetPoint("RIGHT", MiniMapCoords, "RIGHT", 0, 0)
calendarButton:RemoveTextures()
calendarButton:SetNormalTexture(MOD.media.calendarIcon)
calendarButton:SetPushedTexture(MOD.media.calendarIcon)
calendarButton:SetHighlightTexture(MOD.media.calendarIcon)
calendarButton.TText = "Calendar"
calendarButton:RegisterForClicks("AnyUp")
calendarButton:SetScript("OnEnter", Basic_OnEnter)
calendarButton:SetScript("OnLeave", Basic_OnLeave)
calendarButton:SetScript("OnClick", Calendar_OnClick)
end
if (SV.db.Maps.trackingShortcut) then
local trackingButton = CreateFrame("Button", "InkedSV_TrackingButton", MiniMapCoords)
trackingButton:SetSize(22,22)
if (InkedSV_CalendarButton) then
trackingButton:SetPoint("RIGHT", InkedSV_CalendarButton, "LEFT", -4, 0)
else
trackingButton:SetPoint("RIGHT", MiniMapCoords, "RIGHT", 0, 0)
end
trackingButton:RemoveTextures()
trackingButton:SetNormalTexture(MOD.media.trackingIcon)
trackingButton:SetPushedTexture(MOD.media.trackingIcon)
trackingButton:SetHighlightTexture(MOD.media.trackingIcon)
trackingButton.TText = "Tracking"
trackingButton:RegisterForClicks("AnyUp")
trackingButton:SetScript("OnEnter", Basic_OnEnter)
trackingButton:SetScript("OnLeave", Basic_OnLeave)
trackingButton:SetScript("OnClick", Tracking_OnClick)
end
SV:NewAnchor(MiniMapCoords, L["Minimap ToolBar"])
if(SV.db.Maps.minimapbar.enable == true) then
MMBHolder = CreateFrame("Frame", "InkedSV_MiniMapButtonHolder", self.Holder)
MMBHolder:SetPoint("TOPRIGHT", MiniMapCoords, "BOTTOMRIGHT", 0, -4)
MMBHolder:SetSize(self.Holder:GetWidth(), 32)
MMBHolder:SetFrameStrata("BACKGROUND")
MMBBar = CreateFrame("Frame", "InkedSV_MiniMapButtonBar", MMBHolder)
MMBBar:SetFrameStrata("LOW")
MMBBar:ClearAllPoints()
MMBBar:SetPoint("CENTER", MMBHolder, "CENTER", 0, 0)
MMBBar:SetScript("OnEnter", MMB_OnEnter)
MMBBar:SetScript("OnLeave", MMB_OnLeave)
SV:NewAnchor(MMBHolder, L["Minimap Button Bar"])
self:UpdateMinimapButtonSettings()
end
self:RefreshMiniMap()
self:RegisterEvent('ADDON_LOADED')
self:RegisterEvent('PLAYER_REGEN_ENABLED')
self:RegisterEvent('PLAYER_REGEN_DISABLED')
self:RegisterEvent("ZONE_CHANGED", "RefreshZoneText")
self:RegisterEvent("ZONE_CHANGED_NEW_AREA", "RefreshZoneText")
NewHook("Minimap_UpdateRotationSetting", RotationHook)
SV.Events:On("CORE_INITIALIZED", MapTriggerFired);
end
| 33,551
|
UdoChudo/InkedSV
|
(terralib.loadfile("test.t"))()
import "darkroom"
darkroomSimple.setImageSize(128,64)
im out(x,y) [uint8[3]](darkroom.vectorSelect({x>10,x>20,x>50},{255,0,0},{0,255,255})) end
test(out)
| 188
|
jameshegarty/darkroom
|
local class = require('class')
local constants = require('constants')
local Time = require('utils/Time')
local abs, modf, fmod, floor = math.abs, math.modf, math.fmod, math.floor
local format = string.format
local date, time, difftime = os.date, os.time, os.difftime
local isInstance = class.isInstance
local MS_PER_S = constants.MS_PER_S
local US_PER_MS = constants.US_PER_MS
local US_PER_S = US_PER_MS * MS_PER_S
local DISCORD_EPOCH = constants.DISCORD_EPOCH
local months = {
Jan = 1, Feb = 2, Mar = 3, Apr = 4, May = 5, Jun = 6,
Jul = 7, Aug = 8, Sep = 9, Oct = 10, Nov = 11, Dec = 12
}
local function offset() -- difference between *t and !*t
return difftime(time(), time(date('!*t')))
end
local Date = class('Date')
local function check(self, other)
if not isInstance(self, Date) or not isInstance(other, Date) then
return error('Cannot perform operation with non-Date object', 2)
end
end
function Date:__init(seconds, micro)
local f
seconds = tonumber(seconds)
if seconds then
seconds, f = modf(seconds)
else
seconds = time()
end
micro = tonumber(micro)
if micro then
seconds = seconds + modf(micro / US_PER_S)
micro = fmod(micro, US_PER_S)
else
micro = 0
end
if f and f > 0 then
micro = micro + US_PER_S * f
end
self._s = seconds
self._us = floor(micro + 0.5)
end
function Date:__tostring()
return 'Date: ' .. self:toString()
end
function Date:toString()
return date('%a %b %d %Y %T GMT%z (%Z)', self._s)
end
function Date:__eq(other) check(self, other)
return self._s == other._s and self._us == other._us
end
function Date:__lt(other) check(self, other)
return self:toMicroseconds() < other:toMicroseconds()
end
function Date:__le(other) check(self, other)
return self:toMicroseconds() <= other:toMicroseconds()
end
function Date:__add(other)
if not isInstance(self, Date) then
self, other = other, self
end
if not isInstance(other, Time) then
return error('Cannot perform operation with non-Time object')
end
return Date(self:toSeconds() + other:toSeconds())
end
function Date:__sub(other)
if isInstance(self, Date) then
if isInstance(other, Date) then
return Time(abs(self:toMilliseconds() - other:toMilliseconds()))
elseif isInstance(other, Time) then
return Date(self:toSeconds() - other:toSeconds())
else
return error('Cannot perform operation with non-Date/Time object')
end
else
return error('Cannot perform operation with non-Date object')
end
end
function Date.parseISO(str)
local year, month, day, hour, min, sec, other = str:match(
'(%d+)-(%d+)-(%d+).(%d+):(%d+):(%d+)(.*)'
)
other = other:match('%.%d+')
return Date.parseTableUTC {
day = day, month = month, year = year,
hour = hour, min = min, sec = sec, isdst = false,
}, other and other * US_PER_S or 0
end
function Date.parseHeader(str)
local day, month, year, hour, min, sec = str:match(
'%a+, (%d+) (%a+) (%d+) (%d+):(%d+):(%d+) GMT'
)
return Date.parseTableUTC {
day = day, month = months[month], year = year,
hour = hour, min = min, sec = sec, isdst = false,
}
end
function Date.parseSnowflake(id)
return (id / 2^22 + DISCORD_EPOCH) / MS_PER_S
end
function Date.parseTable(tbl)
return time(tbl)
end
function Date.parseTableUTC(tbl)
return time(tbl) + offset()
end
function Date.fromISO(str)
return Date(Date.parseISO(str))
end
function Date.fromHeader(str)
return Date(Date.parseHeader(str))
end
function Date.fromSnowflake(id)
return Date(Date.parseSnowflake(id))
end
function Date.fromTable(tbl)
return Date(Date.parseTable(tbl))
end
function Date.fromTableUTC(tbl)
return Date(Date.parseTableUTC(tbl))
end
function Date.fromSeconds(t)
return Date(t)
end
function Date.fromMilliseconds(t)
return Date(t / MS_PER_S)
end
function Date.fromMicroseconds(t)
return Date(0, t)
end
function Date:toISO(sep, tz)
if sep and tz then
local ret = date('!%F%%s%T%%s', self._s)
return format(ret, sep, tz)
else
if self._us == 0 then
return date('!%FT%T', self._s) .. '+00:00'
else
return date('!%FT%T', self._s) .. format('.%06i+00:00', self._us)
end
end
end
function Date:toHeader()
return date('!%a, %d %b %Y %T GMT', self._s)
end
function Date:toSnowflake()
return format('%i', (self:toMilliseconds() - DISCORD_EPOCH) * 2^22)
end
function Date:toTable()
return date('*t', self._s)
end
function Date:toTableUTC()
return date('!*t', self._s)
end
function Date:toSeconds()
return self._s + self._us / US_PER_S
end
function Date:toMilliseconds()
return self._s * MS_PER_S + self._us / US_PER_MS
end
function Date:toMicroseconds()
return self._s * US_PER_S + self._us
end
function Date:toParts()
return self._s, self._us
end
return Date
| 4,672
|
Mishio595/momiji
|
hslk_item_synthesis({
"双铁剑=铁剑x3+铁盾x3", -- 等于 { { "双铁剑", 1 }, { "铁剑", 3 }, { "铁盾", 3 } }
})
local items = {
{
Name = "铁剑",
Ubertip = "主动演示(效果需要自己处理,本图无效果)|n被动演示(效果需要自己处理,本图无效果)",
Art = "ReplaceableTextures\\CommandButtons\\BTNSteelMelee.blp",
goldcost = 1000,
lumbercost = 0,
powerup = 0,
sellable = 1,
pawnable = 1,
droppable = 1,
Hotkey = "Q",
abilList = "",
_remarks = "精铁铸造的大剑,是武斗者必备的武器",
_weight = 2.3,
_overlie = 2,
_attr = _attr({
attack = "+30", --smart
attack_range = "+100",
xtras = {
_xtras({
on = CONST_EVENT.attack, action = "targetUnit.spec.knocking", val = "triggerUnit.attack",
odds = 30, percent = { 300, 2000 }, effect = nil
})
},
}),
_ring = _ring({
effect = "Abilities\\Spells\\Orc\\CommandAura\\CommandAura.mdl",
effectTarget = "Abilities\\Spells\\NightElf\\BattleRoar\\RoarTarget.mdl",
attachTarget = "overhead",
radius = 600,
target = "air,ground,friend,self,vuln,invu",
attr = {
move = "+20",
}
}),
},
{
Name = "铁盾",
Art = "ReplaceableTextures\\CommandButtons\\BTNHumanArmorUpOne.blp",
goldcost = 1000,
lumbercost = 0,
powerup = 0,
sellable = 1,
pawnable = 1,
droppable = 1,
Hotkey = "W",
abilList = "",
_remarks = "普通的铁盾",
_weight = 3.1,
_overlie = 1,
_attr = {
defend = "+1", --smart
life = "+300",
life_back = "+10",
},
},
{
Name = "双铁剑",
Ubertip = "跳跳跳",
Art = "ReplaceableTextures\\CommandButtons\\BTNDaggerOfEscape.blp",
goldcost = 2000,
lumbercost = 0,
powerup = 0,
sellable = 1,
pawnable = 1,
droppable = 1,
Hotkey = "E",
Rng1 = 1000,
uses = 3,
Missileart = "",
_cooldown = 2,
_cooldownTarget = CONST_ABILITY_TARGET.unit.value,
_remarks = "双倍的铁,双倍的快乐",
_weight = 4,
_overlie = 1,
_attr = {
reborn = '-0.4',
attack = "+50",
attack_space = '-0.1',
sight = "+500",
cure = "+14.5",
xtras = {
{
alias = "水蛇湍乱",
on = CONST_EVENT.attack, action = "targetUnit.spec.paw", val = 'damage',
height = 70, tokenArrowHeight = 30, shake = 'random',
radius = 50, odds = 10, speed = 5, deg = 45, distance = 600, qty = 2,
effect = 'Abilities\\Weapons\\WaterElementalMissile\\WaterElementalMissile.mdl',
damageType = { CONST_DAMAGE_TYPE.water }
},
},
},
_onItemUsed = _onItemUsed(function(evtData)
hunit.portal(evtData.triggerUnit, evtData.targetX, evtData.targetY)
end),
},
}
for _, v in pairs(items) do
v.race = "human"
v._shadow = true
hslk_item(v)
end
| 3,252
|
hunzsig-warcraft3/w3x-h-lua-helloworld-sdk
|
local voteClass = {}
voteClass.__index = voteClass
function amapvote.CreateVote()
local instance = {}
setmetatable(instance, voteClass)
instance:ctor()
return instance
end
function voteClass:ctor()
self._options = {}
self._votes = {}
self._started = false
self._duration = 30
self._startTime = 0
end
function voteClass:GetDuration()
return self._duration
end
function voteClass:SetDuration(dur)
assert(not self._started, "vote already started")
self._duration = dur
end
function voteClass:AddChoice(map)
assert(not self._started, "vote already started")
table.insert(self._options, map)
end
function voteClass:Start()
assert(not self._started, "vote already started")
assert(#self._options > 0, "No totalVotes given")
print("Mapvote started")
self._startTime = CurTime()
self._endTime = self._startTime + self._duration
self._started = true
net.Start(amapvote.NetString)
net.WriteTable({
options = self._options,
endTime = self._endTime,
})
net.Broadcast()
end
function voteClass:UpdatePlayerVote(ply, ballet)
self._votes[ply] = ballet
end
function voteClass:Finish()
print("Mapvote finished")
self:FindWinner()
self:OnComplete(self._winner)
end
function voteClass:FindWinner()
local totalVotes = {}
if table.Count(self._votes) == 0 then
return self:PickRandom()
end
for _, ballet in pairs(self._votes) do
for map, score in pairs(ballet) do
totalVotes[map] = (totalVotes[map] or 0) + score
end
end
local highest = false
local highestScore = -1
print("totalvotes:")
PrintTable(totalVotes)
for map, score in pairs(totalVotes) do
print(map, score, highestScore)
if score > highestScore then
highestScore = score
highest = map
end
end
self._winner = highest
end
function voteClass:PickRandom()
return table.Random(self._options)
end
function voteClass:OnComplete(map)
--Add your code here :D
print("Winning map:", map)
self._started = false
self:AnnounceWinner(map)
self:ChangeMap(map)
end
function voteClass:AnnounceWinner(map)
net.Start(amapvote.ShowWinnerString)
net.WriteString(map)
net.Broadcast()
end
function voteClass:ChangeMap(map)
timer.Simple(5, function()
RunConsoleCommand("changelevel", map)
end)
end
| 2,327
|
maritaria/amapvote
|
--[[
MIT License
Copyright (c) 2021 Michael Wiesendanger
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
--[[
Run all tests:
/run rgpvpw.testCombatEvent.Test(language [, categoryName])
Run combat event tests:
/run rgpvpw.testCombatEvent.ShouldHaveCombatEventTestForAllTrackedEvents(language [, categoryName])
Run combat event self avoid tests:
/run rgpvpw.testCombatEvent.ShouldHaveCombatEventAvoidTestForAllTrackedEvents(
language, RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID [, categoryName]
)
Run combat event enemy avoid tests:
/run rgpvpw.testCombatEvent.ShouldHaveCombatEventAvoidTestForAllTrackedEvents(
language, RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID [, categoryName]
)
]]--
local mod = rgpvpw
local me = {}
mod.testCombatEvent = me
me.tag = "TestCombatEvent"
local testGroupName = "ShouldHaveCombatEventTestForAllTrackedEvents"
--[[
@param {string} language
A supported language such as en, de etc.
@param {string} categoryName
Optional valid categoryName such as "priest", "warrior" etc.
]]--
function me.Test(language, categoryName)
mod.testReporter.StartTestGroup(testGroupName)
if language == nil then
mod.logger.LogError(me.tag, "Missing language - aborting...")
mod.testReporter.StopTestGroup()
return
end
me.ShouldHaveCombatEventTestForAllTrackedEvents(language, categoryName)
me.ShouldHaveCombatEventAvoidTestForAllTrackedEvents(
language, RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID, categoryName)
me.ShouldHaveCombatEventAvoidTestForAllTrackedEvents(
language, RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID, categoryName)
mod.testReporter.StopTestGroup()
end
--[[
Tests whether there is an appropriate testcase for every spell found in the spellMap
@param {string} language
A supported language such as en, de etc.
@param {string} categoryName
Optional valid categoryName such as "priest", "warrior" etc.
]]--
function me.ShouldHaveCombatEventTestForAllTrackedEvents(language, categoryName)
if language == nil then
mod.logger.LogError(me.tag, "Missing language - aborting...")
return
end
if categoryName ~= nil then
me.ShouldHaveCombatEventTestByCategory(categoryName, language)
else
me.ShouldHaveCombatEventTest(language)
end
end
--[[
@param {string} categoryName
A valid categoryName such as "priest", "warrior" etc.
@param {string} language
A supported language such as en, de etc.
]]--
function me.ShouldHaveCombatEventTestByCategory(categoryName, language)
local spellMap = mod.testHelper.GetAllForCategory(RGPVPW_CONSTANTS.SPELL_MAP, categoryName)
if spellMap == nil then
mod.logger.LogError(me.tag, "Unable to get spellMap for categoryName: " .. categoryName)
return
end
me.CombatEventTest(categoryName, spellMap, language)
end
--[[
@param {string} language
A supported language such as en, de etc.
]]--
function me.ShouldHaveCombatEventTest(language)
local spellMap = mod.spellMap.GetSpellConfiguration()
for category, categoryData in pairs(spellMap) do
me.CombatEventTest(category, categoryData, language)
end
end
--[[
Do the actual test whether the expected function is present or not
@param {string} categoryName
A valid categoryName such as "priest", "warrior" etc.
@param {table} categoryData
@param {string} language
A supported language such as en, de etc.
]]--
function me.CombatEventTest(categoryName, categoryData, language)
for name, spellData in pairs (categoryData) do
local spellName = mod.testHelper.NormalizeSpellName(name)
local trackedEvents = spellData.trackedEvents
local module = mod["testCombatEvents" .. mod.testHelper.FirstToUpper(categoryName)
.. mod.testHelper.FirstToUpper(language)]
for _, trackedEvent in pairs(trackedEvents) do
local testName = "CombatEventTestPresent" .. mod.testHelper.FirstToUpper(categoryName) ..
spellName .. "_" .. trackedEvent
mod.testReporter.StartTestRun(testName)
local eventName = mod.testHelper.MappEventToName(trackedEvent)
if eventName == nil then
mod.testReporter.ReportFailureTestRun(
categoryName,
testName,
string.format(mod.testHelper.invalidEvent, spellName, trackedEvent)
)
return
end
local func = module["TestCombatEvent" .. spellName .. eventName]
if type(func) ~= "function" then
mod.testReporter.ReportFailureTestRun(
categoryName,
testName,
string.format(mod.testHelper.missingCombatEventTest, spellName, trackedEvent)
)
else
mod.testReporter.ReportSuccessTestRun()
end
end
end
end
--[[
Tests whether there is an appropriate testcase for every spell found in the spellAvoidMap
@param {string} language
A supported language such as en, de etc.
@param {number} spellAvoidType
RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID or RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID
@param {string} categoryName
Optional valid categoryName such as "priest", "warrior" etc.
]]--
function me.ShouldHaveCombatEventAvoidTestForAllTrackedEvents(language, spellAvoidType, categoryName)
if language == nil then
mod.logger.LogError(me.tag, "Missing language - aborting...")
return
end
if categoryName ~= nil then
me.ShouldHaveCombatEventAvoidTestByCategory(categoryName, language, spellAvoidType)
else
me.ShouldHaveCombatEventAvoidTest(language, spellAvoidType)
end
end
--[[
@param {string} categoryName
A valid categoryName such as "priest", "warrior" etc.
@param {string} language
A supported language such as en, de etc.
@param {number} spellAvoidType
RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID or RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID
]]--
function me.ShouldHaveCombatEventAvoidTestByCategory(categoryName, language, spellAvoidType)
local spellAvoidMap = mod.testHelper.GetAllForCategory(RGPVPW_CONSTANTS.SPELL_AVOID_MAP, categoryName)
if spellAvoidMap == nil then
mod.logger.LogError(me.tag, "Unable to get spellAvoidMap for categoryName: " .. categoryName)
return
end
me.CombatEventAvoidTest(categoryName, spellAvoidMap, language, spellAvoidType)
end
--[[
@param {string} language
A supported language such as en, de etc.
@param {number} spellAvoidType
RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID or RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID
]]--
function me.ShouldHaveCombatEventAvoidTest(language, spellAvoidType)
local spellAvoidMap = mod.spellAvoidMap.GetSpellConfiguration()
for category, categoryData in pairs(spellAvoidMap) do
me.CombatEventAvoidTest(category, categoryData, language, spellAvoidType)
end
end
--[[
Do the actual test whether the expected function is present or not
@param {string} categoryName
A valid categoryName such as "priest", "warrior" etc.
@param {table} categoryData
@param {string} language
A supported language such as en, de etc.
@param {number} spellAvoidType
RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID or RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID
]]--
function me.CombatEventAvoidTest(categoryName, categoryData, language, spellAvoidType)
for name, spellData in pairs (categoryData) do
local spellName = mod.testHelper.NormalizeSpellName(name)
local moduleNameBase
local testNameBase
local testFunctionBase
if spellAvoidType == RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.SELF_AVOID then
moduleNameBase = "testCombatEventsSelfAvoid"
testNameBase = "CombatSelfAvoidEventTestPresent"
testFunctionBase = "TestCombatEventSelfAvoid"
elseif spellAvoidType == RGPVPW_CONSTANTS.SPELL_AVOID_TYPE.ENEMY_AVOID then
moduleNameBase = "testCombatEventsEnemyAvoid"
testNameBase = "CombatEnemyAvoidEventTestPresent"
testFunctionBase = "TestCombatEventEnemyAvoid"
else
mod.logger.LogError(me.tag, "Invalid spellAvoidType: " .. spellAvoidType)
end
local module = mod[moduleNameBase .. mod.testHelper.FirstToUpper(categoryName)
.. mod.testHelper.FirstToUpper(language)]
local avoidCases = {"dodge", "parry", "immune", "miss", "block", "resist"}
local avoidTestName = {"Dodged", "Parried", "Immune", "Missed", "Blocked", "Resisted"}
for index, avoidCase in ipairs(avoidCases) do
if spellData[avoidCase] then
local testName = testNameBase .. mod.testHelper.FirstToUpper(categoryName) ..
spellName .. "_" .. avoidTestName[index]
mod.testReporter.StartTestRun(testName)
local func = module[testFunctionBase .. spellName .. avoidTestName[index]]
if type(func) ~= "function" then
mod.testReporter.ReportFailureTestRun(
categoryName,
testName,
string.format(mod.testHelper.missingCombatEventAvoidTest, spellName, avoidTestName[index])
)
else
mod.testReporter.ReportSuccessTestRun()
end
end
end
end
end
| 10,029
|
RagedUnicorn/wow-classic-pvpwarn
|
-- =========================
-- BUBBLY.NVIM BRANCH BUBBLE
-- =========================
-- Created by: datwaft [github.com/datwaft]
local bubble_factory = require'bubbly.factories.bubble'
local settings = {
symbol = vim.g.bubbly_symbols.branch,
color = vim.g.bubbly_colors.branch,
style = vim.g.bubbly_styles.branch,
}
if not settings.symbol then
print[[[BUBBLY.NVIM] => [WARNING] Couldn't load symbol configuration for the component 'branch', the default symbol will be used.]]
settings.symbol = vim.g.bubbly_symbols.default
end
if not settings.color then
print[[[BUBBLY.NVIM] => [WARNING] Couldn't load color configuration for the component 'branch', the default color will be used.]]
settings.color = vim.g.bubbly_colors.default
end
if not settings.style then
print[[[BUBBLY.NVIM] => [WARNING] Couldn't load style configuration for the component 'branch', the default style will be used.]]
settings.style = vim.g.bubbly_styles.default
end
return function(inactive)
if inactive then return '' end
local data = vim.b.git_branch
if data ~= '' then
data = settings.symbol:format(data)
end
return bubble_factory{{
data = data,
color = settings.color,
style = settings.style,
}}
end
| 1,251
|
ratheesh/bubbly.nvim
|
function findOpenGL()
configuration{}
if os.is("Linux") then
if os.isdir("/usr/include") and os.isfile("/usr/include/GL/gl.h") then return true
end
return false
end
--assume OpenGL is available on Mac OSX, Windows etc
return true
end
function initOpenGL()
configuration {}
configuration {"Windows"}
links {"opengl32","glu32"}
configuration {"MacOSX"}
links { "OpenGL.framework"}
configuration {"not Windows", "not MacOSX"}
links {"GL","GLU"}
configuration{}
end
function initGlut()
configuration {}
if os.is("Windows") then
configuration {"Windows"}
includedirs {
projectRootDir .. "btgui/OpenGLWindow/Glut"
}
libdirs { projectRootDir .. "btgui/OpenGLWindow/Glut"}
configuration {"Windows", "x32"}
links {"glut32"}
configuration {"Windows", "x64"}
links {"glut64"}
end
configuration {"MacOSX"}
links { "Glut.framework" }
configuration {"Linux"}
links {"glut"}
configuration{}
end
function initGlew()
configuration {}
if os.is("Windows") then
configuration {"Windows"}
defines { "GLEW_STATIC"}
includedirs {
projectRootDir .. "btgui/OpenGLWindow/GlewWindows"
}
files { projectRootDir .. "btgui/OpenGLWindow/GlewWindows/glew.c"}
end
if os.is("Linux") then
configuration{"Linux"}
if os.isdir("/usr/include") and os.isfile("/usr/include/GL/glew.h") then
links {"GLEW"}
else
defines { "GLEW_STATIC"}
--,"GLEW_NO_GLU"}
includedirs {
projectRootDir .. "btgui/OpenGLWindow/GlewWindows"
}
files { projectRootDir .. "btgui/OpenGLWindow/GlewWindows/glew.c"}
end
end
configuration{}
end
| 1,756
|
juj/bullet3
|
local Game = {}
local ScreenWidth, ScreenHeight = love.graphics.getDimensions()
local DistBetweenCards = 45
function Game:enter(from, index)
self.gui = Suit.new()
self.index = index
self.cards = {}
self.currentPlayerTurnIndex = nil
self.roundCombination = nil
self.roundStrongestCard = nil
self.roundSequenceLength = 0
self.playersCardLeft = {0, 0, 0, 0}
end
function Game:update(dt)
---- Send ----
---- Receive ----
repeat
local data, msg = UDP:receive()
if data then
local command, params = data:match('^(%S*) (.*)')
if command == 'addCard' then
local rank, suit = params:match('^(%d*) (%d*)')
rank, suit = tonumber(rank), tonumber(suit)
self:addCard(rank, suit)
elseif command == 'update' then
print(params)
local currentPlayerTurnIndex, roundCombination, roundSequenceLength, roundStrongestCardId, playersCardLeft =
params:match('^(%d*) (%S*) (%S*) (%S*%-%S*) (%d*%-%d*%-%d*%-%d*)')
self.currentPlayerTurnIndex = tonumber(currentPlayerTurnIndex)
self.roundCombination = tonumber(roundCombination)
self.roundSequenceLength = roundSequenceLength
local rank, suit = roundStrongestCardId:match('^(%d)%-(%d)')
self.roundStrongestCard = rank == nil and nil or Card(rank, suit)
self.playersCardLeft[1], self.playersCardLeft[2], self.playersCardLeft[3], self.playersCardLeft[4] =
playersCardLeft:match('^(%d)%-(%d)%-(%d)%-(%d)')
else
print('unrecognized command: '..tostring(command))
end
end
until not data
---- Normal stuff ----
for i = #self.cards, 1, -1 do
self.cards[i]:update(
ScreenWidth/2 - 60 + DistBetweenCards * (-#self.cards/2 + (i-1)),
ScreenHeight - 140
)
end
if self.gui:Button('Play', ScreenWidth - 115, ScreenHeight - 70, 100, 40).hit then
if self.index ~= self.currentPlayerTurnIndex then
print("it's not your turn")
else
self:playSelectedCards()
end
end
end
function Game:draw()
self.gui:draw()
end
function Game:addCard(rank, suit)
local card = Card(rank, suit)
table.insert(self.cards, card)
table.sort(self.cards)
end
function Game:playSelectedCards()
local selectedCards = {}
for i = 1, #self.cards do
if self.cards[i].selected then
table.insert(selectedCards, self.cards[i])
end
end
local combination = self:getCombination(selectedCards)
if combination then
print('is valid')
end
end
function Game:getCombination(cards)
table.sort(cards)
if #cards == 1 then
return Combinations.Single
elseif #cards == 2 and cards[1].rank == cards[2].rank then
return Combinations.Double
elseif #cards == 3 and cards[1].rank == cards[2].rank and
cards[1].rank == cards[3].rank then
return Combinations.Triple
elseif #cards == 4 and cards[1].rank == cards[2].rank and
cards[1].rank == cards[3].rank and cards[1].rank == cards[4].rank then
return Combinations.Quadruple
elseif #cards >= 3 then
for i = 1, #cards-1 do
if cards[i+1].rank - cards[i].rank ~= 1 then
return false
end
end
return Combinations.Sequence
elseif #cards >= 6 and #cards % 2 == 0 then
for i = 1, #cards / 2 do
if cards[i*2-1].rank ~= cards[i*2] then
return false
end
end
for i = 1, #cards / 2 - 1 do
if cards[i*2+1].rank - cards[i*2].rank then
return false
end
end
return Combinations.DoubleSequence
else
return false
end
end
return Game
| 3,354
|
MynameisBI/thirteen-madness
|
--[[Author: Pizzalol
Date: 27.09.2015.
Calculate the rift position and play the particle]]
function RealityRiftPosition( keys )
local caster = keys.caster
local target = keys.target
local caster_location = caster:GetAbsOrigin()
local target_location = target:GetAbsOrigin()
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
-- Ability variables
local min_range = ability:GetLevelSpecialValueFor("min_range", ability_level)
local max_range = ability:GetLevelSpecialValueFor("max_range", ability_level)
local reality_rift_particle = keys.reality_rift_particle
-- Position calculation
local distance = (target_location - caster_location):Length2D()
local direction = (target_location - caster_location):Normalized()
local target_point = RandomFloat(min_range, max_range) * distance
local target_point_vector = caster_location + direction * target_point
-- Particle
local particle = ParticleManager:CreateParticle(reality_rift_particle, PATTACH_CUSTOMORIGIN, target)
ParticleManager:SetParticleControlEnt(particle, 0, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster_location, true)
ParticleManager:SetParticleControlEnt(particle, 1, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target_location, true)
ParticleManager:SetParticleControl(particle, 2, target_point_vector)
ParticleManager:SetParticleControlOrientation(particle, 2, direction, Vector(0,1,0), Vector(1,0,0))
ParticleManager:ReleaseParticleIndex(particle)
-- Save the location
ability.reality_rift_location = target_point_vector
ability.reality_rift_direction = direction
end
--[[Author: Pizzalol
Date: 09.04.2015.
Relocates the target, caster and any illusions under the casters control]]
function RealityRift( keys )
local caster = keys.caster
local target = keys.target
local caster_location = caster:GetAbsOrigin()
local player = caster:GetPlayerOwnerID()
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
-- Ability variables
local bonus_duration = ability:GetLevelSpecialValueFor("bonus_duration", ability_level)
local illusion_search_radius = ability:GetLevelSpecialValueFor("illusion_search_radius", ability_level)
local bonus_modifier = keys.bonus_modifier
-- Set the positions to be one on each side of the rift
target:SetAbsOrigin(ability.reality_rift_location - ability.reality_rift_direction * 25)
caster:SetAbsOrigin(ability.reality_rift_location + ability.reality_rift_direction * 25)
-- Set the targets to face eachother
target:SetForwardVector(ability.reality_rift_direction)
caster:Stop()
caster:SetForwardVector(ability.reality_rift_direction * -1)
-- Add the phased modifier to prevent getting stuck
target:AddNewModifier(caster, nil, "modifier_phased", {duration = 0.03})
caster:AddNewModifier(caster, nil, "modifier_phased", {duration = 0.03})
-- Execute the attack order for the caster
local order =
{
UnitIndex = caster:entindex(),
OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET,
TargetIndex = target:entindex(),
Queue = true
}
ExecuteOrderFromTable(order)
-- Find the caster illusions if they exist
local target_teams = DOTA_UNIT_TARGET_TEAM_FRIENDLY
local target_types = DOTA_UNIT_TARGET_HERO
local target_flags = DOTA_UNIT_TARGET_FLAG_PLAYER_CONTROLLED
local units = FindUnitsInRadius(caster:GetTeamNumber(), caster_location, nil, illusion_search_radius, target_teams, target_types, target_flags, FIND_CLOSEST, false)
for _,unit in ipairs(units) do
if unit:IsIllusion() and unit:GetPlayerOwnerID() == player then
-- Do the same thing that we did for the caster
-- Relocate and set the illusion to face the target
unit:SetAbsOrigin(ability.reality_rift_location + ability.reality_rift_direction * 25)
unit:Stop()
unit:SetForwardVector(ability.reality_rift_direction * -1)
-- Add the phased and reality rift modifiers
unit:AddNewModifier(caster, nil, "modifier_phased", {duration = 0.03})
ability:ApplyDataDrivenModifier(caster, unit, bonus_modifier, {duration = bonus_duration})
-- Execute the attack order
local order =
{
UnitIndex = unit:entindex(),
OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET,
TargetIndex = target:entindex(),
Queue = true
}
ExecuteOrderFromTable(order)
end
end
end
| 4,274
|
kulakaa073/SpellLibrary
|
--proc/window/class: window classes in the winapi sense.
--this is unrelated to the oo API for windows (see msdn for what a window class means).
setfenv(1, require'winapi')
require'winapi.winuser'
--register/unregister
ffi.cdef[[
typedef struct tagWNDCLASSEXW {
UINT cbSize;
UINT _style;
WNDPROC proc;
int cbClsExtra;
int cbWndExtra;
HINSTANCE hInstance;
HICON icon;
HCURSOR cursor;
HBRUSH background;
LPCWSTR lpszMenuName;
LPCWSTR lpszClassName;
HICON small_icon;
} WNDCLASSEXW, *PWNDCLASSEXW, *NPWNDCLASSEXW, *LPWNDCLASSEXW;
ATOM RegisterClassExW(const WNDCLASSEXW *);
BOOL UnregisterClassW(
LPCWSTR lpClassName,
HINSTANCE hInstance);
]]
CS_VREDRAW = 0x0001
CS_HREDRAW = 0x0002
CS_DBLCLKS = 0x0008
CS_OWNDC = 0x0020
CS_CLASSDC = 0x0040
CS_PARENTDC = 0x0080
CS_NOCLOSE = 0x0200
CS_SAVEBITS = 0x0800
CS_BYTEALIGNCLIENT = 0x1000
CS_BYTEALIGNWINDOW = 0x2000
CS_GLOBALCLASS = 0x4000
CS_IME = 0x00010000
CS_DROPSHADOW = 0x00020000
WNDCLASSEXW = struct{
ctype = 'WNDCLASSEXW', size = 'cbSize',
fields = sfields{
'name', 'lpszClassName', wcs, mbs,
'style', '_style', flags, pass,
}
}
function RegisterClass(info)
return checknz(C.RegisterClassExW(WNDCLASSEXW(info)))
end
function UnregisterClass(class)
if not class then return end
checknz(C.UnregisterClassW(ffi.cast('LPCWSTR', wcs(MAKEINTRESOURCE(class))), nil))
end
--set/get class long
GCL_MENUNAME = -8
GCL_HBRBACKGROUND = -10
GCL_HCURSOR = -12
GCL_HICON = -14
GCL_HMODULE = -16
GCL_CBWNDEXTRA = -18
GCL_CBCLSEXTRA = -20
GCL_WNDPROC = -24
GCL_STYLE = -26
GCW_ATOM = -32
GCL_HICONSM = -34
if ffi.abi'64bit' then
ffi.cdef[[
LONG_PTR SetClassLongPtrW(HWND hWnd, int nIndex, LONG_PTR dwNewLong);
LONG_PTR GetClassLongPtrW(HWND hWnd, int nIndex);
]]
SetClassLongW = C.SetClassLongPtrW
GetClassLongW = C.GetClassLongPtrW
else --32bit
ffi.cdef[[
LONG SetClassLongW(HWND hWnd, int nIndex, LONG dwNewLong);
LONG GetClassLongW(HWND hWnd, int nIndex);
]]
SetClassLongW = C.SetClassLongW
GetClassLongW = C.GetClassLongW
end
function SetClassLong(hwnd, GCL, long)
callnz2(SetClassLongW, hwnd, flags(GCL), ffi.cast('LONG', long))
end
function GetClassLong(hwnd, GCL) return GetClassLongW(hwnd, flags(GCL)) end
function GetClassStyle(hwnd) return GetClassLong(hwnd, GCL_STYLE) end
function SetClassStyle(hwnd, style) SetClassLong(hwnd, GCL_STYLE, flags(style)) end
function GetClassIcon(hwnd) return ffi.cast('HICON', GetClassLong(hwnd, GCL_HICON)) end
function SetClassIcon(hwnd, icon) SetClassLong(hwnd, GCL_HICON, icon) end
function GetClassSmallIcon(hwnd) return ffi.cast('HICON', GetClassLong(hwnd, GCL_HICONSM)) end
function SetClassSmallIcon(hwnd, icon) SetClassLong(hwnd, GCL_HICONSM, icon) end
function GetClassCursor(hwnd) return ffi.cast('HCURSOR', GetClassLong(hwnd, GCL_HCURSOR)) end
function SetClassCursor(hwnd, cursor) SetClassLong(hwnd, GCL_HCURSOR, cursor) end
function GetClassBackground(hwnd) return ffi.cast('HBRUSH', GetClassLong(hwnd, GCL_HBRBACKGROUND)) end
function SetClassBackground(hwnd, bg) SetClassLong(hwnd, GCL_HBRBACKGROUND, bg) end
--showcase
if not ... then
require'winapi.color'
require'winapi.cursor'
require'winapi.window' --for DefWindowProc
local class = assert(print(RegisterClass{
name='MyClass',
style = bit.bor(CS_HREDRAW, CS_VREDRAW),
background = COLOR_WINDOW,
cursor = LoadCursor(IDC_ARROW),
proc = DefWindowProc,
}))
UnregisterClass(class)
end
| 3,559
|
finnw/grodlob
|
local abclua = require "abclua"
-- Tests check wheter ABCLua can parse a given ABC string
-- and reproduce it exactly. This only tests the parser and emitter,
-- and it only tests those strings which are unchanged by the parse/emit process.
function reproduce(str)
-- parse, then regenerate
local parsed = abclua.parse_abc(str, {no_expand=true}).token_stream
stream, context = compile_tokens(parsed)
return emit_abc(parsed)
end
function check_reproduce(str, name)
-- Verify that a string is reproduced by the ABC parser/emitter
-- Macro expansion is disabled
local r = reproduce(str)
local mis = first_difference_string(str, r)
-- print mismatch
if mis then
print("Mismatch")
print(str)
print(string.sub(r, 1, mis-1)..'-->'..string.sub(r, mis-1))
print(r)
print()
print()
end
assert(str==reproduce(str))
if name then
print("Test "..name.. " passed OK")
end
end
function check_result(str, result, name)
-- Verify that passing a string through the parser gives a particular result
-- This includes macro expansion
local parsed = abclua.parse_abc(str).token_stream
abclua.precompile_token_stream(parsed)
stream, context = compile_tokens(parsed)
str = emit_abc(parsed)
local mis = first_difference_string(str, result)
if mis then
print("Mismatch")
print(name)
print(result)
print(str)
print(string.sub(result, 1, mis)..'-->'..string.sub(result, mis))
end
assert(str==result)
if name then
print("Test "..name.. " passed OK")
end
end
check_reproduce([[X:1]], 'Xref')
check_reproduce([[X:1
K:G
a a a]], 'Key and notes')
check_reproduce([[
I:abc-creator abclua
%%directive this is a directive
K:G]], 'Directives'
)
check_reproduce([[X:1
K:G
ceg & C3 | dfa & D3 | C3 & E3 & G/2 G/2 G/2 G/2G/2G/2 | && D &&& C C C]], 'Voice overlay')
check_result([[X:1
K:G
C D ~F T~.G +fermata+D !legato!G
{cg}D {ab}C {f2fe}G
"Cm7"C G "Dmaj"D A D
{cg}"Cm7"+fermata+~=D
G]],[[X:1
K:G
C D ~F T~.G HD !legato!G
{cg}D {ab}C {f2fe}G
"Cm7"C G "D"D A D
{cg}"Cm7"H~=D
G]], 'Decorations and chord names')
check_reproduce(
[[
X:1
K:G alto
K:G bass
K:G
K:G treble transpose=-4
K:G bass octave=2
K:G bass middle=3]], 'Key with clefs')
check_reproduce([[X:1003
T:Amazing Grace
M:3/4
K:G
"D7"A/B/|(d3d)zB|
"G"d2 B/G/|B2A|"C"G2 E|"G"D2 D|"Em"G2 (3 B/A/G/|"D"B2 A|("G"G3G2)||]], 'Slurs')
check_result([[X:1
K:G
D E D | A B :|
|:: A A A ::|1 B B B :|2 c c c :|3 d d d |] D D D |: e e e :::: f f f :|
|: d e d :|: A B c :|1 g ||]],
[[X:1
K:G
D E D | A B :|
|:: A A A ::|1 B B B :|2 c c c :|3 d d d |] D D D |: e e e ::|:: f f f :|
|: d e d :|: A B c :|1 g ||]],'Repeats')
check_reproduce(
[[X:1
M:3/4
K:G
V:A nm=alto
G G G | G G G | G G G
V:B clef=treble-8
e3 | e3 | e3
V:C octave=-2
b3 | d3 | b/2 d/2 b/2 f/2 a/2 b/2]], 'Multi-voice')
check_reproduce(
[[X:1
M:3/4
K:G
A A/2 A/4 z
A A/2 A/3 A/4 z
A1/2 A1/4 A1/5 z
A2/3 A3/4 A8/5 z
A z A z1 A z2 A z/2 A z/2 A z4
A A A A z A>A A>A z A<A A<A z Z a a a Z2 a a a]], 'Note durations')
check_result(
[[X:1
P:ABABA2(CAC)2
M:3/4
K:G
P:A
D E D [1 G |] [2-4 E F |] [2-4,3-8 E F |] [5,6 A,, |]
P:B
d e d
P:C
a a a [2 a']],
[[X:1
P:ABABA2(CAC)2
M:3/4
K:G
P:A
D E D [1 G |] [2,3,4 E F |] [2,3,4,5,6,7,8 E F |] [5,6 A,, |]
P:B
d e d
P:C
a a a [2 a']],
'Multi-parts')
check_reproduce(
[[X:1
K:G
CDEFGabcdefgab
a'b'c'd'e'f'g'a''b''
a''b''c''d''e''f''g''a'''b'''
C,D,E,F,G,AB
C,,D,,E,,F,,G,,A,B,
C,,,D,,,E,,,F,,,G,,,A,,B,,]], 'Octaves')
check_reproduce([[X:1
K:G
A B C D | E F G A | B4
w:doh re me fah so la~a ti-do]], 'Lyrics')
check_reproduce([[X:1
K:C
A A z z | ^A _A =A z | ^^A __A =A z | z z z
^A A A z | _A A A z | _A A =A z | zzz]], 'Accidentals')
check_result([[X:1
K:C
A A z z | ^/2A _/A =A z | ^2/3A __/9A =A z | z z z
^A A A z | _A A A z | _A A =A z | zzz]], [[X:1
K:C
A A z z | ^/2A _/2A =A z | ^2/3A _2/9A =A z | z z z
^A A A z | _A A A z | _A A =A z | zzz]],'Fractional Accidentals')
check_reproduce([[X:1
m:d2=d//f//d2
m:n4=o//n//t//n4
K:G
A B C | d2 A | a4 B | d4 B | E4 B |]],'Unexapnded macros')
check_result([[X:1
m:d2=gg
K:G
d2]],
[[X:1
K:G
gg]],'Macro expansion'
)
-- check_result([[X:1
-- U:n=g
-- U:p=A
-- U:~=!coda!
-- K:G
-- npn|~g~n|]],
-- [[X:1
-- K:G
-- gAg|!coda!g!coda!g|]],'User macros'
-- )
check_result([[X:1
K:G
A B- D- D2- D3 - D4 - D-|D]],
[[X:1
K:G
A B- D- D2- D3- D4- D-|D]],
'Ties')
check_reproduce([[X:1
K:G
[abc] [def] [CEg] D]], 'Chords')
check_reproduce([[X:1
K:G
"Cm"F "D"(def) "Amin/G"[CEg] "G7"]], 'Chord names')
check_reproduce([[X:1003
T:Amazing Grace
R:Waltz
C:Carrell and Clayton 1831
N:Words by Newton 1779
O:England
M:3/4
L:1/4
Q:1/4=100
K:G
D|"G"G2 B/G/|B2 "D7"A|"Em"G2 "C"E|"G"D2 D|G2 B/G/|B2 "D7"A/B/|("D"d3|d)zB|
"G"d2 B/G/|B2A|"C"G2 E|"G"D2 D|"Em"G2 (3B/A/G/|"D"B2 A|("G"G3|G2)||]], 'Amazing Grace')
check_reproduce([[X:1
K:G
"Cm"y y "D"y !crescendo(!y !crescendo)!y]], 'y Spaces')
check_reproduce([[X:1
K:G
"this is free"AB C "<text" A ">around"[ceg] "@here" a b ">and there"c"<there"]], 'Free text')
check_reproduce([[X:1
K:G
(AB) (CD) (EFG) (EEE)]], 'Slurs')
check_result([[X:1
M:none
M:
M:C
M:C|
M:4/4
M:3/4
M:(1+3)/4
M:(2+2+2)/4
K:G
A B C]],
[[X:1
M:none
M:none
M:4/4
M:2/2
M:4/4
M:3/4
M:(1+3)/4
M:(2+2+2)/4
K:G
A B C]], 'Meters')
check_reproduce([[X:1
K:G
A B C | D E F |] A B C [| DEG ||
ABC |: DEF :|: GAB :|
|: GAB :|1 DEF |2 GEF |3 FED ||
|:: GAB ::|:: DEF ::|
|:: GAB ::|:: DEF ::|
| A B C | [4 DEF ||
| A B C | [4,5 DEF ||
| A B C | [1,4,5 DEF ||]], 'Bar types')
check_result([[X:1
m:n2=lmnopq
K:G
A2]],
[[X:1
K:G
FGABcd]],'Transposing macro expansion'
)
check_reproduce([[X:1
K:G
A A A
B B B\
C C C\
D D D
E E E]],
'Line breaks and continue')
check_result([[X:1
K:G
GABcdefg
K:G ^c _g
GABcdefg z4
K:G ^^c __g _f
GABcdefg
K:G ^2/3c _/4g _/f
GABcdefg
]],
[[X:1
K:G
GABcdefg
K:G ^c _g
GABcdefg z4
K:G ^^c __g _f
GABcdefg
K:G ^2/3c _/4g _/2f
GABcdefg]],
'Keys with fraction accidentals')
check_reproduce([[X:1
K:none
CDEFGABc z4
K:C
CDEFGABc z4
K:D
DEFGABcd z4
K:E
EFGABcde z4
K:G
GABcdefg z4
K:Gb
GABcdefg z4
K:C#
GABcdefg z4
K:Gdor
GABcdefg z4
K:Gloc
GABcdefg z4 [K:Gphr]
GABcdefg z4
K:G ^c _g
GABcdefg z4
[K:G]
GABcdefg z4
K:Gexp ^f
GABcdefg z4]], 'Keys with modes and accidentals')
check_reproduce([[X:1
K:none
CDEFGABc z4
K:Fexp ^c ^f
CDEFGABc z4
K:Fdor
K:HP
K:Hp
GABcdefg z4]], 'Special keys')
check_reproduce(
[[X:1
K:G
A B [CEG] A B [K:G] A B F [R:remarkable] B]], 'Inline fields and chord groups'
)
check_reproduce(
[[X:1
K:G
A B (CDE) (AB) G]], 'Slur groups'
)
check_reproduce([[
X:1
K:G
DED | ABA | DED |
{ed}DED | {fg2A}ABA | {e/d/2}DE{f>AA<f'z}D | {/f}a]], 'Grace notes')
check_reproduce([[
X:1
K:G
"Cm7"B | "D/2"[abc] | "F7"(def) | "Gm/E"]],
'Chord names')
check_reproduce([[
X:1
L:1/8
L:1/2
L:1/1
L:1/16
K:G
A B C]], 'Note lengths')
check_reproduce([[
X:1
K:G
abzabZ2| Z2 | Z4 | z z Z a]], 'Rests')
check_result([[
X:1
Q:1/8=200 "Allegro"
Q:120
Q:"Allegro"
Q:1/4=120
Q:1/8 1/8 1/4=140
K:G
A B C]],
[[
X:1
Q:1/8=200 "Allegro"
Q:120
Q:1/4=120 "Allegro"
Q:1/4=120
Q:1/8 1/8 1/4=140
K:G
A B C]],
'Tempos')
check_reproduce([[X:1
K:G
A A A z | (3 A A A A z | (3::2 A A A z | (5:3:4 A A A A A z | (3:4:2 D D D]],'Tuplets')
check_reproduce([[X:1
K:G
s:* * * *
s:| * | * |
s:"<space" * "*lace" "Cm7"
s:!trill! !fermata! * !trill! | | | !trill!
s:]]
,'Symbol lines')
check_result([[
X:1
T:My song
whose title
+:just goes on
K:G
]], [[X:1
T:My song
+:whose title
+:just goes on
K:G]], 'Continuation')
check_result([[X:1
T:My song
T:Also known as my other song
+:continued
A:Kildare
C:Unknown
B:book
D:none
F:this_file.abc
G:ungrouped
H:Very little is known
H:about
+:this song
but it does support freeform text
I:abc-creator ABCLua
L:1/4
M:4/4
N:A test song
O:The test suite
R:reel
P:AB(CA)2B2
Q:1/4=120
R:remarkable
S:a source
s:* * "<note" * !trill!
w:oh the-se are so-me words to~a song
W:Th-ese app-ear at the end
Z:no one in particular
K:G]],
[[X:1
T:My song
T:Also known as my other song
+:continued
A:Kildare
C:Unknown
B:book
D:none
F:this_file.abc
G:ungrouped
H:Very little is known
H:about
+:this song
+:but it does support freeform text
I:abc-creator ABCLua
L:1/4
M:4/4
N:A test song
O:The test suite
R:reel
P:AB(CA)2B2
Q:1/4=120
R:remarkable
S:a source
s:* * "<note" * !trill!
w:oh the-se are so-me words to~a song
W:Th-ese app-ear at the end
Z:no one in particular
K:G]], 'All fields')
check_result([[
X:18009
T:Roddy McCorley
T:Sean South
R:March
C:Trad. Song
O:Ireland
M:4/4
L:1/8
Q:1/4=120
K:G
GA|"G"B2ABD2GA|B3AG3D|"C"E2G2G2A2|"G"G4-G2Bc|
d2d2d2Bd|"C"e2e2"G"d3B|"Em"G2E2"Am"c2B2|"D"A4-A2Bc|
"G"d2d2d2Bd|"C"e2e2"G"d3B|"Em"G2E2"Am"c2B2|"D"A4-A2GA|
"G"B2ABD2GA|B3AG2DD|"C"E2G2G2-"Am"GA|"G"G4-G2:|]
]],
[[
X:18009
T:Roddy McCorley
T:Sean South
R:March
C:Trad. Song
O:Ireland
M:4/4
L:1/8
Q:1/4=120
K:G
GA|"G"B2ABD2GA|B3AG3D|"C"E2G2G2A2|"G"G4-G2Bc|
d2d2d2Bd|"C"e2e2"G"d3B|"Em"G2E2"Am"c2B2|"D"A4-A2Bc|
"G"d2d2d2Bd|"C"e2e2"G"d3B|"Em"G2E2"Am"c2B2|"D"A4-A2GA|
"G"B2ABD2GA|B3AG2DD|"C"E2G2G2-"Am"GA|"G"G4-G2:|]], 'Sean South'
)
| 9,703
|
johnhw/abclua
|
local parent, ns = debugstack():match[[\AddOns\(.-)\]], oUF
local oUF = ns.oUF or _G.oUF
local LMH = LibStub('LibMobHealth-4.0')
oUF.colors.health = {49/255, 207/255, 37/255}
local Update = function(self, event, unit)
if(self.unit ~= unit) then return end
local health = self.Health
if(health.PreUpdate) then health:PreUpdate(unit) end
--local min, max = UnitHealth(unit), UnitHealthMax(unit)
local min, max = LMH:GetUnitCurrentHP(unit), LMH:GetUnitMaxHP(unit)
local disconnected = not UnitIsConnected(unit)
health:SetMinMaxValues(0, max)
if(disconnected) then
health:SetValue(max)
else
health:SetValue(min)
end
health.disconnected = disconnected
health.unit = unit
local r, g, b, t
if(health.colorTapping and UnitIsTapped(unit) and not UnitIsTappedByPlayer(unit)) then
t = self.colors.tapped
elseif(health.colorDisconnected and not UnitIsConnected(unit)) then
t = self.colors.disconnected
elseif(health.colorHappiness and UnitIsUnit(unit, "pet") and GetPetHappiness()) then
t = self.colors.happiness[GetPetHappiness()]
elseif(health.colorClass and UnitIsPlayer(unit)) or
(health.colorClassNPC and not UnitIsPlayer(unit)) or
(health.colorClassPet and UnitPlayerControlled(unit) and not UnitIsPlayer(unit)) then
local _, class = UnitClass(unit)
t = self.colors.class[class]
elseif(health.colorReaction and UnitReaction(unit, 'player')) then
t = self.colors.reaction[UnitReaction(unit, "player")]
elseif(health.colorSmooth) then
r, g, b = self.ColorGradient(min / max, unpack(health.smoothGradient or self.colors.smooth))
elseif(health.colorHealth) then
t = self.colors.health
end
if(t) then
r, g, b = t[1], t[2], t[3]
end
if(b) then
health:SetStatusBarColor(r, g, b)
local bg = health.bg
if(bg) then
local mu = bg.multiplier or 1
bg:SetVertexColor(r * mu, g * mu, b * mu)
end
end
if(health.PostUpdate) then
return health:PostUpdate(unit, min, max)
end
end
local OnHealthUpdate
do
local UnitHealth = UnitHealth
OnHealthUpdate = function(self)
if(self.disconnected) then return end
local health = UnitHealth(self.unit)
if(health ~= self.min) then
self.min = health
return (self.Update or Update) (self:GetParent(), "OnHealthUpdate", self.unit)
end
end
end
local Enable = function(self, unit)
local health = self.Health
if(health) then
local Update = health.Update or Update
if(health.frequentUpdates and (unit and not unit:match'%w+target$')) then
-- TODO 1.5: We should do this regardless of frequentUpdates.
if(health:GetParent() ~= self) then
return oUF.error('Element [%s] is incorrectly parented on [%s]. Expected self, got something else.', 'Health', unit)
end
health:SetScript('OnUpdate', OnHealthUpdate)
-- The party frames need this to handle disconnect states correctly.
if(unit == 'party') then
self:RegisterEvent("UNIT_HEALTH", Update)
end
else
self:RegisterEvent("UNIT_HEALTH", Update)
end
self:RegisterEvent("UNIT_MAXHEALTH", Update)
self:RegisterEvent('UNIT_HAPPINESS', Update)
-- For tapping.
self:RegisterEvent('UNIT_FACTION', Update)
if(not health:GetStatusBarTexture()) then
health:SetStatusBarTexture[[Interface\TargetingFrame\UI-StatusBar]]
end
return true
end
end
local Disable = function(self)
local health = self.Health
if(health) then
local Update = health.Update or Update
if(health:GetScript'OnUpdate') then
health:SetScript('OnUpdate', nil)
end
self:UnregisterEvent('UNIT_HEALTH', Update)
self:UnregisterEvent('UNIT_MAXHEALTH', Update)
self:UnregisterEvent('UNIT_HAPPINESS', Update)
self:UnregisterEvent('UNIT_FACTION', Update)
end
end
oUF:AddElement('Health', Update, Enable, Disable)
| 3,809
|
sativahigh/SohighUI
|
AddCSLuaFile()
PANEL.Base = "Panel"
function PANEL:Init()
self.CurrentSearch = ""
self.OldResults = -1
self.RebuildResults = false
self:Dock( TOP )
self:SetHeight( 20 )
self:DockMargin( 0, 0, 0, 3 )
self.Search = self:Add( "DTextEntry" )
self.Search:Dock( FILL )
self.Search:SetPlaceholderText( "#spawnmenu.search" )
self.Search.OnEnter = function() self:RefreshResults() end
self.Search.OnFocusChanged = function( _, b ) if ( b ) then self.ContentPanel:SwitchPanel( self.PropPanel ) end end
self.Search:SetTooltip( "#spawnmenu.enter_search" )
local btn = self.Search:Add( "DImageButton" )
btn:SetImage( "icon16/magnifier.png" )
btn:SetText( "" )
btn:Dock( RIGHT )
btn:DockMargin( 4, 2, 4, 2 )
btn:SetSize( 16, 16 )
btn:SetTooltip( "#spawnmenu.press_search" )
btn.DoClick = function()
self:RefreshResults()
end
self.Search.OnKeyCode = function( p, code )
if ( code == KEY_F1 ) then hook.Run( "OnSpawnMenuClose" ) end
if ( code == KEY_ESCAPE ) then hook.Run( "OnSpawnMenuClose" ) end
end
self.PropPanel = vgui.Create( "ContentContainer", self )
self.PropPanel:SetVisible( false )
self.PropPanel:SetTriggerSpawnlistChange( false )
-- Some sort of placeholder
local Header = self:Add( "ContentHeader" )
Header:SetText( "#spawnmenu.enter_search" )
self.PropPanel:Add( Header )
end
function PANEL:Paint()
-- This is a bit of a hack, if there was a request to rebuild the results from the search indexer
-- Do it when the player next sees the search panel, in case they got the spawnmenu closed
-- Think hook causes unexpected 1 frame duplication of all the elements
if ( self.RebuildResults ) then
self.RebuildResults = false
self:RefreshResults( self.CurrentSearch )
end
end
function PANEL:SetSearchType( stype, hookname )
self.m_strSearchType = stype
hook.Add( hookname, "AddSearchContent_" .. hookname, function( pnlContent, tree, node )
self.ContentPanel = pnlContent
end )
hook.Add( "SearchUpdate", "SearchUpdate_" .. hookname, function()
if ( !g_SpawnMenu:IsVisible() ) then self.RebuildResults = true return end
self:RefreshResults( self.CurrentSearch )
end )
-- This stuff is only for the primary search
if ( hookname != "PopulateContent" ) then return end
g_SpawnMenu.SearchPropPanel = self.PropPanel
hook.Add( "StartSearch", "StartSearch", function()
if ( g_SpawnMenu:IsVisible() ) then return hook.Run( "OnSpawnMenuClose" ) end
hook.Run( "OnSpawnMenuOpen" )
hook.Run( "OnTextEntryGetFocus", self.Search )
self.Search:RequestFocus()
self.Search:SetText( "" )
--
-- If we don't call this we'd have to press F1 twice to close it!
-- It's in a timer because of some good reason that!
--
timer.Simple( 0.1, function() g_SpawnMenu:HangOpen( false ) end )
self.ContentPanel:SwitchPanel( self.PropPanel )
end )
end
function PANEL:RefreshResults( str )
if ( !str ) then -- User tried to search for something
self.CurrentSearch = self.Search:GetText()
str = self.CurrentSearch
self.OldResults = -1
else
-- Don't force open the search when you click away from search while this function is called from cl_search_models.lua
if ( self.ContentPanel.SelectedPanel != self.PropPanel ) then
return
end
end
if ( !str or str == "" ) then return end
local results = search.GetResults( str, self.m_strSearchType, GetConVarNumber( "sbox_search_maxresults" ) )
for id, result in pairs( results ) do
if ( !IsValid( result.icon ) ) then ErrorNoHalt( "Failed to create icon for " .. ( result.words && isstring( result.words[ 1 ] ) && result.words[ 1 ] || result.text ).. "\n" ) continue end
result.icon:SetParent( vgui.GetWorldPanel() ) -- Don't parent the icons to search panel prematurely
end
-- I know this is not perfect, but this is the best I am willing to do with how the search library was set up
if ( self.OldResults == #results ) then -- No updates, don't rebuild
for id, result in pairs( results ) do
if ( IsValid( result.icon ) ) then result.icon:Remove() end -- Kill all icons
end
return
end
self.OldResults = #results
self.PropPanel:Clear()
local Header = self:Add( "ContentHeader" )
Header:SetText( #results .. " Results for \"" .. str .. "\"" )
self.PropPanel:Add( Header )
for k, v in pairs( results ) do
self:AddSearchResult( v.text, v.func, v.icon )
end
self.PropPanel:SetParent( self.ContentPanel )
self.ContentPanel:SwitchPanel( self.PropPanel )
end
function PANEL:AddSearchResult( text, func, icon )
if ( !IsValid( icon ) ) then return end
icon:SetParent( self.PropPanel )
self.PropPanel:Add( icon )
end
| 4,731
|
Jck123/gmodserver
|
CustomizableWeaponry:addFireSound("CW_G18_FIRE", "weapons/dmg_glock/fire.wav", 1, 100, CHAN_WEAPON)
CustomizableWeaponry:addFireSound("CW_G18_FIRE_SUPPRESSED", "weapons/dmg_glock/fire-silenced.wav", 0.5, 50, CHAN_WEAPON) --weapons/cw_mp5/mp5_fire_suppressed.wav
CustomizableWeaponry:addReloadSound("CW_G18_MAGIN", "weapons/dmg_glock/magin.wav")
CustomizableWeaponry:addReloadSound("CW_G18_MAGOUT", "weapons/dmg_glock/magout.wav")
CustomizableWeaponry:addReloadSound("CW_G18_BOLTPULL", "weapons/dmg_glock/boltpull.wav")
CustomizableWeaponry:addReloadSound("CW_G18_BOLTRELEASE", "weapons/dmg_glock/boltrelease.wav")
| 615
|
JacubRSTNC/PoliceRP-OpenSource
|
modifier_aura_attack_speed = class(Modifier)
LinkLuaModifier("modifier_aura_attack_speed", modifier_aura_attack_speed)
function modifier_aura_attack_speed:OnCreated ()
self.GetModifierBonus = self.GetModifierBonus
self:SetVisible(false)
--self:AttachVariableModifier("attack_speed");
end
function modifier_aura_attack_speed:OnAttached()
self:AttachVariableModifier("attack_speed");
if(self:GetCaster():GetId() == self:GetParent():GetId()) then
--Debug.Log("modifier_aura_take_damage:OnAttached() is caster -> setting aura")
self:SetAuraRadius(20)
else
--Debug.Log("modifier_aura_take_damage:OnAttached() is not caster -> so auras work?")
end
end
function modifier_aura_attack_speed:GetModifierBonus_attack_speed()
return self:GetAbility():GetSpecialValue("bonus_aura_attack_speed")
end
| 804
|
chrisinajar/spark
|
-- * Metronome IM *
--
-- This file is part of the Metronome XMPP server and is released under the
-- ISC License, please see the LICENSE file in this source package for more
-- information about copyright and licensing.
--
-- As per the sublicensing clause, this file is also MIT/X11 Licensed.
-- ** Copyright (c) 2010-2013, Matthew Wild, Waqas Hussain
local type = type;
local t_insert, t_concat, t_remove, t_sort = table.insert, table.concat, table.remove, table.sort;
local s_char = string.char;
local tostring, tonumber = tostring, tonumber;
local pairs, ipairs = pairs, ipairs;
local next = next;
local error = error;
local getmetatable, setmetatable = getmetatable, setmetatable;
local print = print;
local has_array, array = pcall(require, "util.array");
local array_mt = has_array and getmetatable(array()) or {};
local json = {};
local null = setmetatable({}, { __tostring = function() return "null"; end; });
json.null = null;
local escapes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b",
["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"};
local unescapes = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/",
b = "\b", f = "\f", n = "\n", r = "\r", t = "\t"};
for i=0,31 do
local ch = s_char(i);
if not escapes[ch] then escapes[ch] = ("\\u%.4X"):format(i); end
end
local function codepoint_to_utf8(code)
if code < 0x80 then return s_char(code); end
local bits0_6 = code % 64;
if code < 0x800 then
local bits6_5 = (code - bits0_6) / 64;
return s_char(0x80 + 0x40 + bits6_5, 0x80 + bits0_6);
end
local bits0_12 = code % 4096;
local bits6_6 = (bits0_12 - bits0_6) / 64;
local bits12_4 = (code - bits0_12) / 4096;
return s_char(0x80 + 0x40 + 0x20 + bits12_4, 0x80 + bits6_6, 0x80 + bits0_6);
end
local valid_types = {
number = true,
string = true,
table = true,
boolean = true
};
local special_keys = {
__array = true;
__hash = true;
};
local simplesave, tablesave, arraysave, stringsave;
function stringsave(o, buffer)
-- FIXME do proper utf-8 and binary data detection
t_insert(buffer, "\""..(o:gsub(".", escapes)).."\"");
end
function arraysave(o, buffer)
t_insert(buffer, "[");
if next(o) then
for i, v in ipairs(o) do
simplesave(v, buffer);
t_insert(buffer, ",");
end
t_remove(buffer);
end
t_insert(buffer, "]");
end
function tablesave(o, buffer)
local __array = {};
local __hash = {};
local hash = {};
for i, v in ipairs(o) do
__array[i] = v;
end
for k, v in pairs(o) do
local ktype, vtype = type(k), type(v);
if valid_types[vtype] or v == null then
if ktype == "string" and not special_keys[k] then
hash[k] = v;
elseif (valid_types[ktype] or k == null) and __array[k] == nil then
__hash[k] = v;
end
end
end
if next(__hash) ~= nil or next(hash) ~= nil or next(__array) == nil then
t_insert(buffer, "{");
local mark = #buffer;
if buffer.ordered then
local keys = {};
for k in pairs(hash) do
t_insert(keys, k);
end
t_sort(keys);
for _, k in ipairs(keys) do
stringsave(k, buffer);
t_insert(buffer, ":");
simplesave(hash[k], buffer);
t_insert(buffer, ",");
end
else
for k, v in pairs(hash) do
stringsave(k, buffer);
t_insert(buffer, ":");
simplesave(v, buffer);
t_insert(buffer, ",");
end
end
if next(__hash) ~= nil then
t_insert(buffer, "\"__hash\":[");
for k, v in pairs(__hash) do
simplesave(k, buffer);
t_insert(buffer, ",");
simplesave(v, buffer);
t_insert(buffer, ",");
end
t_remove(buffer);
t_insert(buffer, "]");
t_insert(buffer, ",");
end
if next(__array) then
t_insert(buffer, "\"__array\":");
arraysave(__array, buffer);
t_insert(buffer, ",");
end
if mark ~= #buffer then t_remove(buffer); end
t_insert(buffer, "}");
else
arraysave(__array, buffer);
end
end
function simplesave(o, buffer)
local t = type(o);
if t == "number" then
t_insert(buffer, tostring(o));
elseif t == "string" then
stringsave(o, buffer);
elseif t == "table" then
local mt = getmetatable(o);
if mt == array_mt then
arraysave(o, buffer);
else
tablesave(o, buffer);
end
elseif t == "boolean" then
t_insert(buffer, (o and "true" or "false"));
else
t_insert(buffer, "null");
end
end
function json.encode(obj)
local t = {};
simplesave(obj, t);
return t_concat(t);
end
function json.encode_ordered(obj)
local t = { ordered = true };
simplesave(obj, t);
return t_concat(t);
end
function json.encode_array(obj)
local t = {};
arraysave(obj, t);
return t_concat(t);
end
-----------------------------------
local function _skip_whitespace(json, index)
return json:find("[^ \t\r\n]", index) or index; -- no need to check \r\n, we converted those to \t
end
local function _fixobject(obj)
local __array = obj.__array;
if __array then
obj.__array = nil;
for i, v in ipairs(__array) do
t_insert(obj, v);
end
end
local __hash = obj.__hash;
if __hash then
obj.__hash = nil;
local k;
for i, v in ipairs(__hash) do
if k ~= nil then
obj[k] = v; k = nil;
else
k = v;
end
end
end
return obj;
end
local _readvalue, _readstring;
local function _readobject(json, index)
local o = {};
while true do
local key, val;
index = _skip_whitespace(json, index + 1);
if json:byte(index) ~= 0x22 then -- "\""
if json:byte(index) == 0x7d then return o, index + 1; end -- "}"
return nil, "key expected";
end
key, index = _readstring(json, index);
if key == nil then return nil, index; end
index = _skip_whitespace(json, index);
if json:byte(index) ~= 0x3a then return nil, "colon expected"; end -- ":"
val, index = _readvalue(json, index + 1);
if val == nil then return nil, index; end
o[key] = val;
index = _skip_whitespace(json, index);
local b = json:byte(index);
if b == 0x7d then return _fixobject(o), index + 1; end -- "}"
if b ~= 0x2c then return nil, "object eof"; end -- ","
end
end
local function _readarray(json, index)
local a = {};
local oindex = index;
while true do
local val;
val, index = _readvalue(json, index + 1);
if val == nil then
if json:byte(oindex + 1) == 0x5d then return setmetatable(a, array_mt), oindex + 2; end -- "]"
return val, index;
end
t_insert(a, val);
index = _skip_whitespace(json, index);
local b = json:byte(index);
if b == 0x5d then return setmetatable(a, array_mt), index + 1; end -- "]"
if b ~= 0x2c then return nil, "array eof"; end -- ","
end
end
local _unescape_error;
local function _unescape_surrogate_func(x)
local lead, trail = tonumber(x:sub(3, 6), 16), tonumber(x:sub(9, 12), 16);
local codepoint = lead * 0x400 + trail - 0x35FDC00;
local a = codepoint % 64;
codepoint = (codepoint - a) / 64;
local b = codepoint % 64;
codepoint = (codepoint - b) / 64;
local c = codepoint % 64;
codepoint = (codepoint - c) / 64;
return s_char(0xF0 + codepoint, 0x80 + c, 0x80 + b, 0x80 + a);
end
local function _unescape_func(x)
x = x:match("%x%x%x%x", 3);
if x then
--if x >= 0xD800 and x <= 0xDFFF then _unescape_error = true; end -- bad surrogate pair
return codepoint_to_utf8(tonumber(x, 16));
end
_unescape_error = true;
end
function _readstring(json, index)
index = index + 1;
local endindex = json:find("\"", index, true);
if endindex then
local s = json:sub(index, endindex - 1);
--if s:find("[%z-\31]") then return nil, "control char in string"; end
-- FIXME handle control characters
_unescape_error = nil;
--s = s:gsub("\\u[dD][89abAB]%x%x\\u[dD][cdefCDEF]%x%x", _unescape_surrogate_func);
-- FIXME handle escapes beyond BMP
s = s:gsub("\\u.?.?.?.?", _unescape_func);
if _unescape_error then return nil, "invalid escape"; end
return s, endindex + 1;
end
return nil, "string eof";
end
local function _readnumber(json, index)
local m = json:match("[0-9%.%-eE%+]+", index); -- FIXME do strict checking
return tonumber(m), index + #m;
end
local function _readnull(json, index)
local a, b, c = json:byte(index + 1, index + 3);
if a == 0x75 and b == 0x6c and c == 0x6c then
return null, index + 4;
end
return nil, "null parse failed";
end
local function _readtrue(json, index)
local a, b, c = json:byte(index + 1, index + 3);
if a == 0x72 and b == 0x75 and c == 0x65 then
return true, index + 4;
end
return nil, "true parse failed";
end
local function _readfalse(json, index)
local a, b, c, d = json:byte(index + 1, index + 4);
if a == 0x61 and b == 0x6c and c == 0x73 and d == 0x65 then
return false, index + 5;
end
return nil, "false parse failed";
end
function _readvalue(json, index)
index = _skip_whitespace(json, index);
local b = json:byte(index);
-- TODO try table lookup instead of if-else?
if b == 0x7B then -- "{"
return _readobject(json, index);
elseif b == 0x5B then -- "["
return _readarray(json, index);
elseif b == 0x22 then -- "\""
return _readstring(json, index);
elseif b ~= nil and b >= 0x30 and b <= 0x39 or b == 0x2d then -- "0"-"9" or "-"
return _readnumber(json, index);
elseif b == 0x6e then -- "n"
return _readnull(json, index);
elseif b == 0x74 then -- "t"
return _readtrue(json, index);
elseif b == 0x66 then -- "f"
return _readfalse(json, index);
else
return nil, "value expected";
end
end
local first_escape = {
["\\\""] = "\\u0022";
["\\\\"] = "\\u005c";
["\\/" ] = "\\u002f";
["\\b" ] = "\\u0008";
["\\f" ] = "\\u000C";
["\\n" ] = "\\u000A";
["\\r" ] = "\\u000D";
["\\t" ] = "\\u0009";
["\\u" ] = "\\u";
};
function json.decode(json)
json = json:gsub("\\.", first_escape) -- get rid of all escapes except \uXXXX, making string parsing much simpler
--:gsub("[\r\n]", "\t"); -- \r\n\t are equivalent, we care about none of them, and none of them can be in strings
-- TODO do encoding verification
local val, index = _readvalue(json, 1);
if val == nil then return val, index; end
if json:find("[^ \t\r\n]", index) then return nil, "garbage at eof"; end
return val;
end
function json.test(object)
local encoded = json.encode(object);
local decoded = json.decode(encoded);
local recoded = json.encode(decoded);
if encoded ~= recoded then
print("FAILED");
print("encoded:", encoded);
print("recoded:", recoded);
else
print(encoded);
end
return encoded == recoded;
end
return json;
| 10,213
|
maranda/metronome
|
--Realms is Minetest mod that allows you to use multiple diferent lua landscape generators
--and control exactly where each one runs on the map through the realms.conf file
realms={}
local c_air = minetest.get_content_id("air")
local c_stone = minetest.get_content_id("default:stone")
local c_dirt = minetest.get_content_id("default:dirt")
local c_dirt_grass = minetest.get_content_id("default:dirt_with_grass")
local c_sand = minetest.get_content_id("default:sand")
realms.undefined_biome={
name="undefined_biome",
node_top=c_dirt_grass,
depth_top = 1,
node_filler=c_dirt,
depth_filler = 5,
dec=nil
}
realms.undefined_underwater_biome={
name="undefined_underwater_biome",
node_top=c_sand,
depth_top = 1,
node_filler=c_sand,
depth_filler = 1,
dec=nil
}
local data = {} --define buffers up here to save memory
local vmparam2 = {}
local pts=luautils.pos_to_str
local von=luautils.var_or_nil
local placenode=luautils.place_node
realm={}
--note that these are global
realms.rmg={} --realms map gen
realms.rmf={} --realms map function
realms.noise={} --noise (so you can reuse the same noise or change it easily)
realms.biome={} --where registered biomes are stored. Remember, registered biomes do nothing unless included in a biome map
realms.biomemap={}
--realms map generator
--********************************
function realms.register_mapgen(name, func)
realms.rmg[name]=func
minetest.log("realms-> rmg registered for: "..name)
end --register_mapgen
--realms map function
--********************************
function realms.register_mapfunc(name, func)
realms.rmf[name]=func
minetest.log("realms-> rmf registered for: "..name)
end --register_mapfunc
--realms noise
--********************************
function realms.register_noise(name, noise)
--store the special seed for this noise based on the noise name
--if the user passes a seed, we will add it to this nameseed
--that way ONE seed can be passed and used for multiple noises without giving them all the same seed
local nameseed=0
for i=1,string.len(name) do
nameseed=nameseed+i*string.byte(name,i)
end --for
noise.nameseed=nameseed
realms.noise[name]=noise
minetest.log("realms-> noise registered for: "..name)
end --register_noise
--call this function passing a noise parameter (usually parms.noisename)
--call this function passing a noisename_in (the name of a registered noise, usually parms.noisename)
--and a default noise name. The function will return the default noise if noisename_in is blank.
--if you pass seed, the noise.seed will be set to that
--if seed is nil and default_seed is not, it will use default_seed (usualy pass parms.realm_seed)
--if default_seed is nill, it will not change the seed.
--NOTE: we add the seed you pass to nameseed, a unique seed based on the noise name. that way you get
--unique seeds for each noise even when passing the same realm_seed
--
--this just makes it simpler and more intuitive to get your noise
--it is usually better to use realms.get_noise2d or realms.get_noise3d
--********************************
function realms.get_noise(noisename_in, default_noise, seed, default_seed)
local noisename
if noisename_in~=nil and noisename_in~="" then noisename=noisename_in
else noisename=default_noise
end --if noisename_in
local noise=realms.noise[noisename]
if seed~=nil then
noise.seed=noise.nameseed+tonumber(seed)
elseif default_seed~=nil then
noise.seed=noise.nameseed+tonumber(default_seed)
end --if seed
return noise
end --get_noise
--note that this just saves the step of you getting the perlin map and lets you do it all in one step
--see get_noise for details on that function
--noisename_in=the name of a registered noise, usually parms.noisename
--default_noise=the name of a registered noise to use if noisename_in is nil
--seed=a seed to add to nameseed for this noise (usually parms.seed)
--default_seed=a seed to use if seed=nil (usually parms.realm_seed)
--size2d=the size of the map, (usually parms.isectsize2d)
--minposxz=the min position, (usually parms.minposxz)
--this function will return the noise map
--********************************
function realms.get_noise2d(noisename_in, default_noise, seed, default_seed, size2d, minposxz)
local noise=realms.get_noise(noisename_in, default_noise, seed, default_seed)
local noisemap = minetest.get_perlin_map(noise, size2d):get_2d_map_flat(minposxz)
return noisemap
end --get_noise2d
--same as get_noise2d but for 3d noise
--********************************
function realms.get_noise3d(noisename_in, default_noise, seed, default_seed, size3d, minpos)
local noise=realms.get_noise(noisename_in, default_noise, seed, default_seed)
local noisemap = minetest.get_perlin_map(noise, size3d):get_3d_map_flat(minposxz)
return noisemap
end --get_noise2d
--********************************
function realms.read_realms_config()
minetest.log("realms-> reading realms config file")
realm.count=0
local p
local cmnt
--realms_configpathmod is set in minetest.conf in the games path, OR defaults to just realms
--this is the NAME of the mod where we will get the config file. I would rather use the game path,
--but there is no way to get that in minetest.
local configpathmod=minetest.settings:get("realms_configpathmod") or "realms"
minetest.log("realms.read_realms_config -> configpathmod="..configpathmod)
--using the mod name from configpathmod, we now get the path
local configpath=minetest.get_modpath(configpathmod)
minetest.log("realms.read_realms_config -> configpath="..configpath)
--realms_config is set in minetest.conf in the game path, OR defaults to just realms.conf
local filename = minetest.settings:get("realms_config") or "realms.conf"
minetest.log("realms.read_realms_config -> filename="..filename)
--open the file so we can load the config
local file = io.open(configpath.."/"..filename, "r")
if file then minetest.log("realms.read_realms_config -> loading realms config file: <"..filename.."> from "..configpath)
else minetest.log("realms.read_realms_config -> ERROR!!! unable to find realms config file <"..filename.."> in "..configpath..". This is bad")
end --if file (modpath)
if file then
for str in file:lines() do
str=luautils.trim(str)
cmnt=false
if string.len(str)>=2 and string.sub(str,1,2)=="--" then cmnt=true end
p=string.find(str,"|")
if p~=nil and cmnt~=true then --not a comment, and we found a vertical bar, this is an actual entry
realm.count=realm.count+1
local r=realm.count
realm[r]={}
minetest.log("realms-> count="..realm.count.." str="..str)
--realm[r].rmg,p=tst,p=luautils.next_field(str,"|",1) --for some strange reason THIS wont work
local hld,p=luautils.next_field(str,"|",1,"trim") --but this works fine
realm[r].rmg=hld
realm[r].parms={}
local mapseed = minetest.get_mapgen_setting("seed") --this is how we get the mapgen seed
--lua numbers are double-precision floating-point which can only handle numbers up to 100,000,000,000,000
--but the seed we got back is 20 characters! We dont really need that much randomness anyway, so we are
--going to just take the first 13 chars, and turn it into a number, so we can do multiplication and addition to it
mapseed=tonumber(string.sub(mapseed,1,13))
--multiplying by the realm number should give us a unique seed for each realm that can be used in noise etc
--since we cut 13 chars from the mapseed, even realm[1] seed would should be different from the map seed
realm[r].parms.realm_seed=mapseed*r
realm[r].parms.realm_minp={}
realm[r].parms.realm_minp.x, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.realm_minp.y, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.realm_minp.z, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.realm_maxp={}
realm[r].parms.realm_maxp.x, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.realm_maxp.y, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.realm_maxp.z, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.sealevel, p=luautils.next_field(str,"|",p,"trim","num")
realm[r].parms.biomefunc, p=luautils.next_field(str,"|",p,"trim","str")
if realm[r].parms.biomefunc=="" then realm[r].parms.biomefunc=nil end
local misc
local var
local val
--now we are going to loop through any OTHER flags/variables user set
while p~=nil do
misc, p=luautils.next_field(str,"|",p,"trim","str")
local peq=string.find(misc,"=")
if peq~=nil then --found var=value
var=luautils.trim(string.sub(misc,1,peq-1)) --var is everything to the left of the =
val=luautils.trim(string.sub(misc,peq+1)) --val is everything to the right of the =
if tonumber(val)~=nil then val=tonumber(val) end --if the string is numeric, turn it into a number
realm[r].parms[var]=val
else realm[r].parms[misc]=true --if no equals found, then treat it as a flag and set true
end --if peq~=nil
end --while p~=nil
minetest.log("realms-> r="..r.." minp="..pts(realm[r].parms.realm_minp)..
" maxp="..pts(realm[r].parms.realm_maxp).." sealevel="..realm[r].parms.sealevel)
end --if p~=nil
end --for str
minetest.log("realms-> all realms loaded, count="..realm.count)
end --if file
end --read_realm_config()
--********************************
function realms.decorate(x,y,z, biome, parms)
local dec=biome.dec
--minetest.log(" realms.decorate-> "..luautils.pos_to_str_xyz(x,y,z).." biome="..biome.name)
if dec==nil then return end --no decorations!
local area=parms.area
local data=parms.data
local vmparam2=parms.vmparam2
local d=1
local r=math.random()*100
--minetest.log(" r="..r)
--we will loop until we hit the end of the list, or an entry whose chancebot is <= r
--so when we exit we will be in one of these conditions
--dec[d]==nil (this biome had no decorations)
--r>=dec[d].chancetop (chance was too high, no decoration selected)
--r<dec[d].chancetop (d is the decoration that was selected)
while (dec[d]~=nil) and (r<dec[d].chancebot) do
--minetest.log(" d="..d.." chancetop="..luautils.var_or_nil(dec[d].chancetop).." chancebot="..luautils.var_or_nil(dec[d].chancebot))
d=d+1
end
--minetest.log(" d="..d.." chancetop="..luautils.var_or_nil(dec[d].chancetop).." chancebot="..luautils.var_or_nil(dec[d].chancebot))
if (dec[d]~=nil) and (r<dec[d].chancetop) then
--decorate
--minetest.log(" hit d="..d.." chancetop="..luautils.var_or_nil(dec[d].chancetop).." chancebot="..luautils.var_or_nil(dec[d].chancebot))
--deal with offest here, because we use it for all three decoration types
local px=x
local py=y
local pz=z
if dec[d].offset_x ~= nil then px=px+dec[d].offset_x end
if dec[d].offset_y ~= nil then py=py+dec[d].offset_y end
if dec[d].offset_z ~= nil then pz=pz+dec[d].offset_z end
--this is only used in type=node for right now
local rotate=nil
if dec[d].rotate~=nil then
if type(dec[d].rotate)=="table" then rotate=dec[d].rotate[math.random(1,#dec[d].rotate)]
elseif dec[d].rotate=="random" then rotate=math.random(0,3)
elseif dec[d].rotate=="random3d" then rotate=math.random(0,11)
else rotate=dec[d].rotate
end --if dec[d].rotate==random
end --if dec[d].rotate~=nil
if dec[d].node~=nil then
--minetest.log("decorate:placing node="..dec[d].node.." biomename="..biome.name.." d="..d)
--note that rotate will be nil unless they sent a rotate value, and if it is nil, it will be ignored
placenode(px,py,pz,area,data,dec[d].node, vmparam2,rotate)
if dec[d].height~=nil then
local height_max=dec[d].height_max
if height_max==nil then height_max=dec[d].height end
local r=math.random(dec[d].height,height_max)
--minetest.log("heighttest-> height="..dec[d].height.." height_max="..height_max.." r="..r)
for i=2,r do --start at 2 because we already placed 1
--minetest.log(" i="..i.." y-i+1="..(y-i)+1)
placenode(px,py+i-1,pz,area,data,dec[d].node, vmparam2,rotate)
end --for
end --if dec[d].node.height
elseif dec[d].func~=nil then
dec[d].func(px, py, pz, area, data)
elseif dec[d].schematic~=nil then
--minetest.log(" realms.decorate-> schematic "..luautils.pos_to_str_xyz(x,y,z).." biome="..biome.name)
--placenode(x,y+1,z,area,data,c_mese)
--minetest.place_schematic({x=x,y=y,z=z}, dec[d].schema, "random", nil, true)
--minetest.place_schematic_on_vmanip(parms.vm,{x=x,y=y,z=z}, dec[d].schema, "random", nil, true)
--can't add schematics to the area properly, so they get added to the parms.mts table, then placed at the end just before the vm is saved
--I'm using offset instead of center so I dont have to worry about whether the schematic is a table or mts file
--I dont know how to send flags for mts file schematics, flags dont seem to be working well for me anyway
table.insert(parms.mts,{{x=px,y=py,z=pz},dec[d].schematic})
elseif dec[d].lsystem~=nil then
--minetest.spawn_tree({x=px,y=py,z=pz},dec[d].lsystem)
--cant add it here, so treating the same as schematic
table.insert(parms.lsys,{{x=px,y=py,z=pz},dec[d].lsys})
end --if dec[d].node~=nil
end --if (dec[d]~=nil)
--minetest.log(" realms.decorate-> "..luautils.pos_to_str_xyz(x,y,z).." biome="..biome.name.." r="..r.." d="..d)
end --decorate
--just allows for error checking and for passing a content id
--********************************
function realms.get_content_id(nodename)
if nodename==nil or nodename=="" then return nil
--if you sent a number, assume that is the correct content id
elseif type(nodename)=="number" then return nodename
else return minetest.get_content_id(nodename)
end --if
end --realms.get_content_id
--calculate biomes decoration percentages
--(this is different from the way minetest does its biome decorations)
--********************************
function realms.calc_biome_dec(biome)
--minetest.log("realms calc_biome_dec-> biome="..von(biome.name))
local d=1
if biome.dec~=nil then --there are decorations!
--# gets the length of an array
--putting it in biome.dec.max is probably not really needed, but I find it easy to use and understand
biome.dec.max=#biome.dec
local chancetop=0
local chancebot=0
--loop BACKWARDS from last decoration to first setting our chances.
--the point here is that we dont want to roll each chance individually. We want to roll ONE chance,
--and then determine which decoration, if any, was selected. So this process sets up the chancetop and chancebot
--for each dec element so that we can easily (and quickly) go through them when decorating.
--example: dec[1].chance=3 dec[2].chance=5 dec 3.chance=2
--after this runs
--dec[1].chancebot=7 dec[1].chancetop=9
--dec[2].chancebot=2 dec[2].chancetop=7
--dec[3].chancebot=0 dec[3].chancetop=2
for d=biome.dec.max, 1, -1 do
--minetest.log("realms calc_biome_dec-> decoration["..d.."] =")
luautils.log_table(biome.dec[d])
if biome.dec[d].chance~=nil then --check this because intend to incorporate noise option in future.
chancebot=chancetop
chancetop=chancetop+biome.dec[d].chance
biome.dec[d].chancetop=chancetop
biome.dec[d].chancebot=chancebot
--turn node entries from strings into numbers
biome.dec[d].node=realms.get_content_id(biome.dec[d].node) --will return nil if passed nil
--minetest.log("realms calc_biome_dec-> content_id="..von(biome.dec[d].node))
end --if dec.chance~=nil
end --for d
--this is the default function for realms defined biomes, no need to have to specify it every time
if biome.decorate==nil then biome.decorate=realms.decorate end
end --if biome.dec~=nil
end --calc_biome_dec
--********************************
--untested, probably needs to be modified so you could add multiple decorations
function realms.add_decoration(biome,newdec)
--minetest.log("add_decoration-> #newdec="..#newdec)
if biome.dec==nil then biome.dec=newdec
else
for _,v in pairs(newdec) do
table.insert(biome.dec, v)
end--for
--biome.dec[#biome.dec+1]=newdec
end --if
realms.calc_biome_dec(biome)
--minetest.log(" add_decoration -> #biome.dec="..#biome.dec)
end --add_decoration
--********************************
function realms.add_dec_flowers(biomein,modifier,cat)
local biome
if type(biomein)=="string" then biome=realms.biome[biomein]
else biome=biomein
end --if type(biomein)
if modifer==nil or modifier==0 then modifier=1 end
if flowers then --if the flowers mod is available
--the category parm may not be needed, since I'm just adding all flowers the same right now
if cat==nil or cat=="all" then
realms.add_decoration(biome,
{
{chance=0.30*modifier, node="flowers:dandelion_yellow"},
{chance=0.30*modifier, node="flowers:dandelion_white"},
{chance=0.25*modifier, node="flowers:rose"},
{chance=0.25*modifier, node="flowers:tulip"},
{chance=0.20*modifier, node="flowers:chrysanthemum_green"},
{chance=0.20*modifier, node="flowers:geranium"},
{chance=0.20*modifier, node="flowers:viola"},
{chance=0.05*modifier, node="flowers:tulip_black"},
})
end --if cat==all
end --if flowers
end --add_dec_flowers
function realms.add_dec_mushrooms(biomein,modifier) --can add a cat to this later if needed
if type(biomein)=="string" then biome=realms.biome[biomein]
else biome=biomein
end --if type(biomein)
if modifer==nil or modifier==0 then modifier=1 end
realms.add_decoration(biome,
{
{chance=0.05*modifier,node="realms:mushroom_white"},
{chance=0.01*modifier,node="realms:mushroom_milkcap"},
{chance=0.01*modifier,node="realms:mushroom_shaggy_mane"},
{chance=0.01*modifier,node="realms:mushroom_parasol"},
{chance=0.005*modifier,node="realms:mushroom_sulfer_tuft"},
})
if flowers then --if the flowers mod is available
realms.add_decoration(biome,
{
{chance=0.05*modifier, node="flowers:mushroom_brown"},
{chance=0.05*modifier, node="flowers:mushroom_red"},
})
end --if flowers
end --add_dec_flowers
--********************************
function realms.register_biome(biome)
if realms.biome[biome.name]~=nil then
minetest.log("realms.register_biome-> ***WARNING!!!*** duplicate biome being registered! biome.name="..biome.name)
end
realms.biome[biome.name]=biome
--set defaults
if biome.depth_top==nil then biome.depth_top=1 end
if biome.node_filler==nil then biome.node_filler="default:dirt" end
if biome.depth_filler==nil then biome.depth_filler=3 end
if biome.node_stone==nil then biome.node_stone="default:stone" end
--turn the node names into node numbers
--minetest.log("*** biome.name="..biome.name)
biome.node_dust = realms.get_content_id(biome.node_dust)
biome.node_top = realms.get_content_id(biome.node_top)
biome.node_filler = realms.get_content_id(biome.node_filler)
biome.node_stone = realms.get_content_id(biome.node_stone)
biome.node_water_top = realms.get_content_id(biome.node_water_top)
biome.node_riverbed = realms.get_content_id(biome.node_riverbed)
--will have to do the same thing for the dec.node entries, but we do that below
--now deal with the decorations (this is different from the way minetest does its biomes)
realms.calc_biome_dec(biome)
minetest.log("realms-> biome registered for: "..biome.name)
end --register_biome
--********************************
function realms.voronoi_sort(a,b)
if a.dist==b.dist and a.y_min~=nil and b.y_min~=nil then return a.y_min<b.y_min
else return a.dist<b.dist
end --if
end --realms.voronoi_sort
realms.vboxsz=20
--********************************
function realms.register_biomemap(biomemap)
minetest.log("realms.register_biomemap "..biomemap.name.." ["..biomemap.typ.."]")
if realms.biomemap[biomemap.name]~=nil then
minetest.log("realms.register_biomemap-> ***WARNING!!!*** duplicate biome map being registered! biomemap.name="..biomemap.name)
end
realms.biomemap[biomemap.name]=biomemap
if biomemap.typ=="VORONOI" then
--voronoi diagrams have some nice advantages
--BUT, I dont know of any simple solution for finding the closest point in a list
--so, I'm cheating. We split the voronoi graph into lots of little boxes, calculate
--the distance to every heat,humid point in the list FROM THE CENTER OF THE BOX
--and then store that in a 2d array.
--now, when we get our noise, we just calculate which box the noise point is in, and
--then use the list calculated from the center of that box. It will not be completely
--accurate, of course, but it should be good enough, and a lot faster than brute force
biomemap.voronoi={}
local vboxsz=realms.vboxsz
--minetest.log("voronoi -> vboxsz="..vboxsz)
for heat=0,vboxsz-1 do
biomemap.voronoi[heat]={}
for humid=0,vboxsz-1 do
biomemap.voronoi[heat][humid]={}
local cx=(heat/vboxsz)+(1/(vboxsz*2))
local cz=(humid/vboxsz)+(1/(vboxsz*2))
--minetest.log("voronoi-> heat="..heat.." humid="..humid.." cx="..cx.." cz="..cz)
for i,v in ipairs(biomemap.list) do
--v=biomemap which contains v.biome, v.heat_point, v_humidity_point
--this is just a temporary place to store distance, it will be disposed of later
v.biome.dist=luautils.distance2d(cx,cz, v.heat_point/100,v.humidity_point/100)
--minetest.log("voronoi-> distance="..v.biome.dist.." to "..v.biome.name.." ("..v.heat_point..","..v.humidity_point..")")
table.insert(biomemap.voronoi[heat][humid], v.biome) --we insert the actual biome not the biomemap
--minetest.log(" "..v.biome.dist.." "..v.biome.name)
end --for biommap.list
--now biomemap.voronoi[heat][humid] is a list of all the biomes in the biomemap, with dist
--we need to sort them.
table.sort(biomemap.voronoi[heat][humid], realms.voronoi_sort)
if biomemap.voronoi[heat][humid][1].count==nil then biomemap.voronoi[heat][humid][1].count=1
else biomemap.voronoi[heat][humid][1].count=biomemap.voronoi[heat][humid][1].count+1
end
local b1=biomemap.voronoi[heat][humid][1]
--minetest.log("voronoi["..heat.."]["..humid.."][1] -> dist="..b1.dist.." count="..b1.count.." : "..b1.name)
--minetest.log("-----after sort")
--for i,v in ipairs(biomemap.voronoi[heat][humid]) do minetest.log(" "..v.dist.." "..v.name) end
end --for humid
end --for heat
--now, dispose of those dist variables you put into the biome so that no one thinks they have meaning.
for i,v in ipairs(biomemap.list) do
v.biome.dist=nil
--minetest.log("voronoi analysis-> "..v.biome.count.." : "..v.biome.name)
local c=v.biome.count
if c==nil then c=0 end
minetest.log("voronoi analysis-> "..c.." : "..v.biome.name)
v.biome.count=nil
end
elseif biomemap.typ=="MATRIX" then
--convert alternates from strings to direct links to the biomes
--we could do this in register biome, but doing it here means we dont have to worry
--about the order of the biomes
--the reason for this? With a voronoi map, if one biome is unavailble because of y_min/y_max restrictions
--you just take the next closest distance heat/humidity point. BUT, with a matrix type of biome map,
--you can NOT have an empty spot on the matrix. So we provide a list of alternate biomes if we provide
--a y_min/y_max.
--this ends up working almost identical to the voronoi map because what is usually done with the voronoi
--is to provide alternate biomes with the exact same heat/humidity point and different y_min/y_max limits
minetest.log("realms.register_biomemap-> starting alternate scan for "..biomemap.name)
--biomemap.biome is a table in the form of biomemap.biome[heat][humid]
for i1,v1 in ipairs(biomemap.biome) do --loop through biomemap.biome[heat]
minetest.log(" heat index["..i1.."]")
for i2,v2 in ipairs(v1) do --loop through biomemap.biome[heat][humid] (this gives us the actual biome)
minetest.log(" humid index["..i2.."] "..v2.name)
--only proceed if alternates exists, and if it is a list of strings (has not already been converted into actual biome links)
if v2.alternates~=nil and type(v2.alternates[1])=="string" then
for i3,v3 in ipairs(v2.alternates) do --loop through biomemap[heat][humid].alternates
biomemap.biome[i1][i2].alternates[i3]=realms.biome[v3] --turn string name into actual biome
minetest.log(" "..v2.name..".alternates["..i3.."]="..biomemap.biome[i1][i2].alternates[i3].name)
end --for i3,v3
end --if v2.alternates
end --for i2,v2
end --for i1,v1
end --if biomemap.typ
minetest.log("realms-> biomemap registered for: "..biomemap.name)
end --register_biomemap
--********************************
function realms.randomize_depth(depth,variation,noise)
if depth<3 then return depth
else
local d=depth-(depth*variation)+(depth*variation*math.abs(noise))
return d
end--if depth
end --reandomize_depth
--[[
function realms.randomize_depth(depth,variation,noise,x,z,minp,chunk_size)
if depth<3 then return depth
else
local nixz=luautils.xzcoords_to_flat(x,z, minp, chunk_size)
--minetest.log("randomize_depth-> depth="..depth.." variation="..variation.." noise="..luautils.var_or_nil(noise))
--return depth-(depth*variation)+(depth*variation*math.abs(noise[nixz]))
local d=depth-(depth*variation)+(depth*variation*math.abs(noise[nixz]))
--minetest.log("randomize_depth-> depth="..depth.." variation="..variation.." nixz="..nixz.." noise="..noise[nixz].." d="..d)
return d
end--if depth
end --reandomize_depth
]]
--********************************
function realms.gen_realms(chunk_minp, chunk_maxp, seed)
local r=0
local doit=false
repeat
r=r+1
if luautils.check_overlap(realm[r].parms.realm_minp, realm[r].parms.realm_maxp, chunk_minp,chunk_maxp)==true then doit=true end
until r==realm.count or doit==true
if doit==false then return end --dont waste cpu
--This actually initializes the LVM. Since realms allows multiple overlapping
--map gens to run, we can save cpu by getting the vm once at the begining,
--passing it to each rmg (realms map gen) as it runs, and saving after
local vm, emin, emax = minetest.get_mapgen_object("voxelmanip")
local area = VoxelArea:new{MinEdge=emin, MaxEdge=emax}
vm:get_data(data)
vm:get_param2_data(vmparam2)
local mts = {} --mts array stores schematics
--add a schematic to this table with: table.insert(parms.mts,{pos,schematic}) (shouldnt matter if table or file, but dont forget the position!)
--the schematics will be written to the chunk after all other manipulation is done
--we do it this way because minetest.place_schematic writes to the map, not the vm area, so it gets messed up
--when the vm is saved after all the realms run.
--and place_schematic_vmanip does nothing if you are writing to the area, it has to be run after 'set data' and before any of: 'set lighting', 'calc lighting', 'write to map'.
--https://minetest.org/forum/viewtopic.php?f=47&t=4668&start=2340
--idea for using table from https://forum.minetest.net/viewtopic.php?f=47&t=18259
local lsys = {} --lsys array stores lsystem entries same as mts stores schematics, and for the same reason
--share is used to pass data between rmgs working on the same chunk
local share={}
--r already equals one that matches, so start there
--could just do the match here automatically and skip the overlap check, then start at r+1?
local rstart=r
local first=0
for r=rstart,realm.count,1 do
local parms=realm[r].parms
if luautils.check_overlap(parms.realm_minp, parms.realm_maxp, chunk_minp,chunk_maxp)==true then
if first==0 then
minetest.log("======== realms-> gen_realms chunk minp="..pts(chunk_minp).." maxp="..pts(chunk_maxp))
first=1
end --first
--minetest.log("realms-> gen_realms r="..r.." rmg="..luautils.var_or_nil(realm[r].rmg)..
-- " realm minp="..pts(parms.realm_minp).." maxp="..pts(parms.realm_maxp))
--minetest.log(" sealevel="..parms.sealevel.." chunk minp="..pts(chunk_minp).." maxp="..pts(chunk_maxp))
--rmg[realm[r].rmg](realm[r].parms.realm_minp,realm[r].parms.realm_maxp, realm[r].parms.sealevel, chunk_minp,chunk_maxp, 0)
parms.chunk_minp=chunk_minp
parms.chunk_maxp=chunk_maxp
parms.isect_minp, parms.isect_maxp = luautils.box_intersection(parms.realm_minp,parms.realm_maxp, parms.chunk_minp,parms.chunk_maxp)
parms.isectsize2d = luautils.box_sizexz(parms.isect_minp,parms.isect_maxp)
parms.isectsize3d = luautils.box_size(parms.isect_minp,parms.isect_maxp)
parms.minposxz = {x=parms.isect_minp.x, y=parms.isect_minp.z}
parms.share=share
parms.area=area
parms.data=data
parms.vmparam2=vmparam2
parms.vm=vm --I dont know if the map gen needs this, but just in case, there it is.
parms.mts=mts --for storing schematics to be written before vm is saved to map
parms.lsys=lsys
parms.chunk_seed=seed --the seed that was passed to realms for this chunk
--minetest.log("realms-> r="..r)
minetest.log(" >>>realms-> gen_realms r="..r.." rmg="..luautils.var_or_nil(realm[r].rmg).." isect "..pts(parms.isect_minp).."-"..pts(parms.isect_maxp))
realms.rmg[realm[r].rmg](parms)
if parms.area~=area then minetest.log("***realms.init-> WARNING parms.area~=area!!!") end
share=parms.share --save share to be used in next parms (user might have changed pointer)
end --if overlap
end--for
--Wrap things up and write back to map, send data back to voxelmanip
--(by saving here we avoid multiple save and pulls in overlapping realm map gens)
minetest.log(" ---realms-> saving area "..luautils.range_to_str(chunk_minp,chunk_maxp))
vm:set_data(data)
vm:set_param2_data(vmparam2)
--apply any schematics that were set (see comments above where parms.mts is defined)
--generator should have placed schematics using: table.insert(parms.mts,{pos,schematic})
--now we loop through them and know that mts[i][i]=pos and mts[i][2]=schematic
--need to modify to let user specify is placement should be random or not.
for i = 1, #mts do
minetest.place_schematic_on_vmanip(vm, mts[i][1], mts[i][2], "random", nil, true) --true means force replace other nodes
end
--calc lighting
vm:set_lighting({day=0, night=0})
vm:calc_lighting()
--write it to world
vm:write_to_map()
for i = 1, #lsys do
minetest.log("decorate->spawning lsystem tree at ("..pts(lsys[i][1])..")")
minetest.spawn_tree(lsys[i][1],lsys[i][2])
end --for
end -- gen_realms
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_layer_barrier.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_flatland.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_very_simple.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_2dMap.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_mesas.lua")
--dofile(minetest.get_modpath("realms").."/realms_map_generators/bg_basic_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bf_basic_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_caves.lua")
--dofile(minetest.get_modpath("realms").."/realms_map_generators/bf_odd_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tg_stupid_islands.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bf_generic.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bd_basic_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bd_odd_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bm_basic_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bm_mixed_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bd_default_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bm_default_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bm_mesas_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/bm_shattered_biomes.lua")
dofile(minetest.get_modpath("realms").."/realms_map_generators/tf_generic_2dMap_loop.lua")
minetest.register_on_generated(realms.gen_realms)
realms.read_realms_config()
| 32,129
|
PowerOlive/fractured
|
--Example1.lua
--
--Simplest possible example of using IAP Badger to purchase an IAP.
---------------------------------
--
-- IAP Badger initialisation
--
---------------------------------
--Load IAP Badger
local iap = require("iap_badger")
--Create the catalogue
local catalogue = {
--Information about the product on the app stores
products = {
--removeAds is the product identifier.
--Always use this identifier to talk to IAP Badger about the purchase.
removeAds = {
--A list of product names or identifiers specific to apple's App Store or Google Play.
productNames = { apple="remove_ads", google="REMOVE_BANNER", amazon="Banner_Remove"},
--The product type
productType = "non-consumable"
}
}
}
--This table contains all of the options we need to specify in this example program.
local iapOptions = {
--The catalogue generated above
catalogue=catalogue,
}
--Initialise IAP badger
iap.init(iapOptions)
--Called when the relevant app store has completed the purchase
--Make a record of the purchase using whatever method you like
local function purchaseListener(product )
print "Purchase made"
end
---------------------------------
--
-- Main game code
--
---------------------------------
iap.purchase("removeAds", purchaseListener)
| 1,432
|
happymongoose/iap_badger
|
local turtle = require "turtle"
local utils = {}
function utils.selectItem(name)
for i=1,16 do
turtle.select(i)
local data = turtle.getItemDetail()
if data ~= nil then
if string.find(data.name, name) then
return i;
end
end
end
return 0
end
function utils.selectItemEqual(name)
for i=1,16 do
turtle.select(i)
local data = turtle.getItemDetail()
if data ~= nil then
if data.name == name then
return i;
end
end
end
return 0
end
function utils.selectTorch()
for i=1,16 do
turtle.select(i)
local data = turtle.getItemDetail()
if data ~= nil then
if string.find(data.name, "torch") then
return i;
end
end
end
return 0
end
function utils.checkCollectIfLavaInFront()
local success, data = turtle.inspect()
if success then
if string.find(data.name, "lava") then
local ret = utils.selectItemEqual("bucket")
if ret ~= 0 then
turtle.place()
end
end
end
end
function utils.refuelSmart()
local needsFuel = turtle.getFuelLevel() + 3000 - turtle.getFuelLimit()
if needsFuel < 0 then
for i=1,16 do
turtle.select(i)
local data = turtle.getItemDetail()
if data ~= nil then
if string.find(data.name, "coal") then
print("refuling")
turtle.refuel()
end
end
end
end
end
function utils.cleanUp(ignore)
for i=1,16 do
turtle.select(i)
local data = turtle.getItemDetail()
if data ~= nil then
if string.find(data.name, "ore") == nil then
if utils.isSelectedToBeIgnored(ignore) == 0 then
turtle.drop()
end
end
end
end
end
function utils.isBedrockBelow()
local success, data = turtle.inspectDown()
if success then
if string.find(data.name, "bedrock") then
return true
end
end
return false
end
function utils.createChestAndDrop()
turtle.up()
turtle.digUp()
turtle.dig()
turtle.forward()
turtle.digUp()
turtle.back()
utils.placeChest()
ignore = {"chest", "torch", "bucket"}
utils.dropItemsToChestIgnore(ignore)
turtle.back()
turtle.down()
turtle.forward()
end
function utils.placeChest()
local x = utils.selectItem("chest")
if x ~= 0 then
turtle.place()
print("Chest placed")
end
end
function utils.isSelectedToBeIgnored(ignore)
local data = turtle.getItemDetail()
for key,value in pairs(ignore) do
if data ~= nil then
if string.find(data.name, value) then
return 1
end
end
end
return 0
end
-- t = {foo = "bar", [123] = 456}
-- t = {"chest", "torch"}
function utils.dropItemsToChestIgnore(ignore)
for i=1,16 do
turtle.select(i)
if utils.isSelectedToBeIgnored(ignore) == 0 then
turtle.drop()
end
end
end
function utils.hasFullSlots()
for i=1,16 do
if turtle.getItemCount(i) == 64 then
return true
end
end
return false;
end
function utils.hasFullSlotsIgnore(ignore)
for i=1,16 do
if turtle.getItemCount(i) == 64 then
turtle.select(i)
if utils.isSelectedToBeIgnored(ignore) == 0 then
return true
end
end
end
return false;
end
function utils.refuelFromAnySlot()
local needsFuel = turtle.getFuelLevel() + 3000 - turtle.getFuelLimit()
if needsFuel < 0 then
for i=1,16 do
turtle.select(i)
turtle.refuel()
end
end
end
function utils.isSugarCane()
local success, data = turtle.inspect()
if success then
if string.find(data.name, "sugar_cane") then
return true
end
end
return false
end
return utils
| 3,781
|
alexejsailer/mock-turtle-api-computer-craft
|
class "TronConfig"
TronConfig.Dev = false
TronConfig.Defaults = {
Radius = 10,
MaxRadius = 400,
Vehicles = {
{
model_id = 43
}
},
MinPlayers = 2,
MaxPlayers = 8
}
TronConfig.Maps = {
{
name = "Блюдо",
position = Vector3(6922.432129, 718.890442, 1037.218994),
radius = 35,
maxRadius = 150,
maxPlayer = 16
},
{
name = "Пляж Бездорожья",
position = Vector3(12361.725, 204, -4705.848),
maxRadius = 800,
vehicles = { -- Offroad vehicles
{
model_id = 11,
template = "FullyUpgraded"
},
{
model_id = 61
},
{
model_id = 90
}
},
maxPlayers = 12,
props = { -- Pillar of barrels
{
position = Vector3(12361.725, 202, -4705.848),
angle = Angle(),
model = "34x09.flz/go001-a.lod",
collision = "34x09.flz/go001_lod1-a_col.pfx"
},
{
position = Vector3(12361.725, 203, -4705.848),
angle = Angle(),
model = "34x09.flz/go001-a.lod",
collision = "34x09.flz/go001_lod1-a_col.pfx"
},
{
position = Vector3(12361.725, 204, -4705.848),
angle = Angle(),
model = "34x09.flz/go001-a.lod",
collision = "34x09.flz/go001_lod1-a_col.pfx"
},
{
position = Vector3(12361.725, 205, -4705.848),
angle = Angle(),
model = "34x09.flz/go001-a.lod",
collision = "34x09.flz/go001_lod1-a_col.pfx"
},
{
position = Vector3(12361.725, 206, -4705.848),
angle = Angle(),
model = "34x09.flz/go001-a.lod",
collision = "34x09.flz/go001_lod1-a_col.pfx"
}
}
},
{
name = "Ледник",
position = Vector3(16254, 201, 4727),
maxRadius = 180,
vehicles = { -- Offroad vehicles
{
model_id = 43,
}
},
maxPlayers = 12,
props = { -- Pillar of barrels
{
position = Vector3(16254, 200, 4727),
angle = Angle(),
model = "f2m07.ice.flz/key028_02-i.lod",
collision = "f2m07.ice.flz/key028_02_lod1-i_col.pfx"
}
}
},
{
name = "Дрифт Остров",
position = Vector3(9877.809, 204, 8118.64),
vehicles = { -- ATVs!
{
model_id = 11,
template = "FullyUpgraded",
tone2 = Color.White -- Okay overriding tones is kinda cool, just don't override tone1
}
},
maxPlayers = 10
},
{
name = "Пустынная гора",
position = Vector3(-9067, 587, 4197),
radius = 5,
maxRadius = 120,
vehicles = { -- ATVs!
{
model_id = 11,
template = "FullyUpgraded",
tone2 = Color.White -- Okay overriding tones is kinda cool, just don't override tone1
}
},
maxPlayers = 5
},
{
name = "Озеро",
-- position = Vector3(-76.311607, 202.039856, 6425.246582),
position = Vector3(5047.809082, 202.096558, 2640.722656),
radius = 4,
maxRadius = 250,
maxPlayers = 4,
vehicles = {
{
model_id = 80
}
}
},
{
name = "Храм",
position = Vector3(14278.492188, 204.469284, -9626.247070),
radius = 5,
maxRadius = 120,
maxPlayers = 5,
vehicles = { -- Dirt bikes
{
model_id = 61
},
{
model_id = 90
}
}
},
{
name = "Watch Out For That Tree",
position = Vector3(4620.187988, 205.466141, -12525.660156),
radius = 10,
maxRadius = 1000,
maxPlayers = 8,
vehicles = { -- Dirt bikes
{
model_id = 61
},
{
model_id = 90
}
}
},
{
name = "Dunia",
position = Vector3(-14879.807617, 204.398346, -8963.131836),
radius = 10,
maxRadius = 500,
maxPlayers = 8,
vehicles = { -- Dirt bikes
{
model_id = 61
},
{
model_id = 90
}
}
},
{
name = "Падающие Башни",
position = Vector3(-498.362152, 800, -12066.586914),
radius = 50,
maxRadius = 75,
props = {
{
position = Vector3(-493.171906, 790.709412, -12114.683594),
angle = Angle(1.445133, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-487.435822, 790.709412, -12113.588867),
angle = Angle(1.319469, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-481.882111, 790.709412, -12111.784180),
angle = Angle(1.193805, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-476.598358, 790.709412, -12109.297852),
angle = Angle(1.068141, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-471.667908, 790.709412, -12106.168945),
angle = Angle(0.942478, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-467.168457, 790.709412, -12102.447266),
angle = Angle(0.816814, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-463.171021, 790.709412, -12098.190430),
angle = Angle(0.691150, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-459.738647, 790.709412, -12093.465820),
angle = Angle(0.565486, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-456.925446, 790.709412, -12088.348633),
angle = Angle(0.439823, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-454.775787, 790.709412, -12082.918945),
angle = Angle(0.314159, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-453.323547, 790.709412, -12077.262695),
angle = Angle(0.188496, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-452.591675, 790.709412, -12071.469727),
angle = Angle(0.062832, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-452.591675, 790.709412, -12065.629883),
angle = Angle(-0.062832, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-453.323547, 790.709412, -12059.836914),
angle = Angle(-0.188496, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-454.775787, 790.709412, -12054.180664),
angle = Angle(-0.314159, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-456.925446, 790.709412, -12048.750977),
angle = Angle(-0.439823, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-459.738678, 790.709412, -12043.633789),
angle = Angle(-0.565487, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-463.171021, 790.709412, -12038.909180),
angle = Angle(-0.691150, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-467.168457, 790.709412, -12034.652344),
angle = Angle(-0.816814, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-471.667908, 790.709412, -12030.930664),
angle = Angle(-0.942478, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-476.598358, 790.709412, -12027.801758),
angle = Angle(-1.068141, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-481.882111, 790.709412, -12025.315430),
angle = Angle(-1.193805, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-487.435822, 790.709412, -12023.510742),
angle = Angle(-1.319469, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-493.171906, 790.709412, -12022.416016),
angle = Angle(-1.445133, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-498.999908, 790.709412, -12022.049805),
angle = Angle(-1.570796, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-504.827911, 790.709412, -12022.416016),
angle = Angle(-1.696460, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-510.563995, 790.709412, -12023.510742),
angle = Angle(-1.822124, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-516.117676, 790.709412, -12025.315430),
angle = Angle(-1.947788, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-521.401489, 790.709412, -12027.801758),
angle = Angle(-2.073451, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-526.331909, 790.709412, -12030.930664),
angle = Angle(-2.199115, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-530.831360, 790.709412, -12034.652344),
angle = Angle(-2.324779, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-534.828796, 790.709412, -12038.909180),
angle = Angle(-2.450442, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-538.261169, 790.709412, -12043.633789),
angle = Angle(-2.576106, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-541.074341, 790.709412, -12048.750977),
angle = Angle(-2.701770, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-543.224060, 790.709412, -12054.180664),
angle = Angle(-2.827433, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-544.676270, 790.709412, -12059.836914),
angle = Angle(-2.953097, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-545.408142, 790.709412, -12065.629883),
angle = Angle(-3.078761, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-545.408142, 790.709412, -12071.469727),
angle = Angle(3.078761, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-544.676270, 790.709412, -12077.262695),
angle = Angle(2.953097, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-543.224060, 790.709412, -12082.918945),
angle = Angle(2.827433, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-541.074341, 790.709412, -12088.348633),
angle = Angle(2.701770, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-538.261169, 790.709412, -12093.465820),
angle = Angle(2.576106, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-534.828796, 790.709412, -12098.190430),
angle = Angle(2.450442, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-530.831360, 790.709412, -12102.447266),
angle = Angle(2.324779, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-526.331909, 790.709412, -12106.168945),
angle = Angle(2.199115, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-521.401428, 790.709412, -12109.297852),
angle = Angle(2.073451, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-516.117676, 790.709412, -12111.784180),
angle = Angle(1.947787, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-510.563995, 790.709412, -12113.588867),
angle = Angle(1.822124, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-504.827911, 790.709412, -12114.683594),
angle = Angle(1.696460, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-498.999908, 790.709412, -12115.049805),
angle = Angle(1.570796, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
}
}
},
{
name = "Двойной купол",
position = Vector3(-6756.504395, 339.996552, -3717.548340),
radius = 15,
maxRadius = 55,
props = {
{
position = Vector3(-6754.307129, 337.897400, -3748.884766),
angle = Angle(-1.633628, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6752.368652, 337.897400, -3748.701416),
angle = Angle(-1.696460, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6750.444824, 337.897400, -3748.396729),
angle = Angle(-1.759292, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6748.544434, 337.897400, -3747.971924),
angle = Angle(-1.822124, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6746.674316, 337.897400, -3747.428711),
angle = Angle(-1.884956, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6744.841797, 337.897400, -3746.769043),
angle = Angle(-1.947787, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6743.054688, 337.897400, -3745.995605),
angle = Angle(-2.010619, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6741.319824, 337.897400, -3745.111328),
angle = Angle(-2.073451, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6739.643555, 337.897400, -3744.120117),
angle = Angle(-2.136283, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6738.032227, 337.897400, -3743.025146),
angle = Angle(-2.199115, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6736.493652, 337.897400, -3741.831543),
angle = Angle(-2.261947, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6735.033203, 337.897400, -3740.543701),
angle = Angle(-2.324779, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6733.655762, 337.897400, -3739.166748),
angle = Angle(-2.387610, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6732.367676, 337.897400, -3737.705811),
angle = Angle(-2.450443, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6731.174316, 337.897400, -3736.166992),
angle = Angle(-2.513274, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6730.080078, 337.897400, -3734.556396),
angle = Angle(-2.576106, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6729.088379, 337.897400, -3732.880127),
angle = Angle(-2.638937, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6728.204590, 337.897400, -3731.145020),
angle = Angle(-2.701770, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6727.431152, 337.897400, -3729.357666),
angle = Angle(-2.764601, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6726.771484, 337.897400, -3727.525391),
angle = Angle(-2.827433, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6726.227539, 337.897400, -3725.655029),
angle = Angle(-2.890265, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.802734, 337.897400, -3723.754639),
angle = Angle(-2.953097, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.498047, 337.897400, -3721.831299),
angle = Angle(-3.015929, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.315430, 337.897400, -3719.892334),
angle = Angle(-3.078761, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.253906, 337.897400, -3717.945801),
angle = Angle(3.141593, 0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.315430, 337.897400, -3715.999268),
angle = Angle(3.078761, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.498047, 337.897400, -3714.060303),
angle = Angle(3.015929, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6725.802734, 337.897400, -3712.136963),
angle = Angle(2.953097, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6726.227539, 337.897400, -3710.236572),
angle = Angle(2.890265, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6726.771484, 337.897400, -3708.366211),
angle = Angle(2.827433, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6727.431152, 337.897400, -3706.533936),
angle = Angle(2.764601, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6728.204590, 337.897400, -3704.746582),
angle = Angle(2.701770, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6729.088379, 337.897400, -3703.011475),
angle = Angle(2.638937, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6730.080078, 337.897400, -3701.335205),
angle = Angle(2.576106, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6731.174316, 337.897400, -3699.724609),
angle = Angle(2.513274, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6732.367676, 337.897400, -3698.185791),
angle = Angle(2.450443, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6733.655762, 337.897400, -3696.724854),
angle = Angle(2.387610, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6735.033203, 337.897400, -3695.347900),
angle = Angle(2.324779, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6736.493652, 337.897400, -3694.060059),
angle = Angle(2.261947, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6738.032227, 337.897400, -3692.866455),
angle = Angle(2.199115, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6739.643555, 337.897400, -3691.771484),
angle = Angle(2.136283, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6741.319824, 337.897400, -3690.780273),
angle = Angle(2.073451, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6743.054688, 337.897400, -3689.895996),
angle = Angle(2.010619, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6744.841797, 337.897400, -3689.122559),
angle = Angle(1.947787, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6746.674316, 337.897400, -3688.462891),
angle = Angle(1.884956, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6748.544434, 337.897400, -3687.919678),
angle = Angle(1.822124, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6750.444824, 337.897400, -3687.494873),
angle = Angle(1.759292, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6752.368652, 337.897400, -3687.190186),
angle = Angle(1.696460, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6754.307129, 337.897400, -3687.006836),
angle = Angle(1.633628, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6756.253906, 337.897400, -3686.945801),
angle = Angle(1.570796, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6758.200684, 337.897400, -3687.006836),
angle = Angle(1.507964, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6760.139160, 337.897400, -3687.190186),
angle = Angle(1.445133, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6762.062988, 337.897400, -3687.494873),
angle = Angle(1.382301, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6763.963379, 337.897400, -3687.919678),
angle = Angle(1.319469, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6765.833496, 337.897400, -3688.462891),
angle = Angle(1.256637, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6767.666016, 337.897400, -3689.122559),
angle = Angle(1.193805, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6769.453125, 337.897400, -3689.895996),
angle = Angle(1.130973, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6771.187988, 337.897400, -3690.780273),
angle = Angle(1.068141, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6772.864258, 337.897400, -3691.771484),
angle = Angle(1.005310, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6774.475586, 337.897400, -3692.866211),
angle = Angle(0.942478, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6776.014160, 337.897400, -3694.060059),
angle = Angle(0.879646, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6777.474609, 337.897400, -3695.347900),
angle = Angle(0.816814, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6778.852051, 337.897400, -3696.724854),
angle = Angle(0.753982, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6780.140137, 337.897400, -3698.185791),
angle = Angle(0.691150, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6781.333496, 337.897400, -3699.724609),
angle = Angle(0.628318, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6782.427734, 337.897400, -3701.335205),
angle = Angle(0.565487, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6783.419434, 337.897400, -3703.011475),
angle = Angle(0.502655, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6784.303223, 337.897400, -3704.746582),
angle = Angle(0.439823, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6785.076660, 337.897400, -3706.533936),
angle = Angle(0.376991, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6785.736328, 337.897400, -3708.366211),
angle = Angle(0.314159, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6786.280273, 337.897400, -3710.236572),
angle = Angle(0.251327, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6786.705078, 337.897400, -3712.136963),
angle = Angle(0.188496, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6787.009766, 337.897400, -3714.060303),
angle = Angle(0.125664, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6787.192383, 337.897400, -3715.999268),
angle = Angle(0.062832, 0.000000, -0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6787.253906, 337.897400, -3717.945801),
angle = Angle(0.000000, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6787.192383, 337.897400, -3719.892334),
angle = Angle(-0.062832, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6787.009766, 337.897400, -3721.831299),
angle = Angle(-0.125664, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6786.705078, 337.897400, -3723.754639),
angle = Angle(-0.188496, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6786.280273, 337.897400, -3725.655029),
angle = Angle(-0.251327, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6785.736328, 337.897400, -3727.525146),
angle = Angle(-0.314159, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6785.076660, 337.897400, -3729.357666),
angle = Angle(-0.376991, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6784.303223, 337.897400, -3731.145020),
angle = Angle(-0.439823, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6783.419434, 337.897400, -3732.880127),
angle = Angle(-0.502655, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6782.427734, 337.897400, -3734.556396),
angle = Angle(-0.565487, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6781.333496, 337.897400, -3736.166992),
angle = Angle(-0.628318, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6780.140137, 337.897400, -3737.705811),
angle = Angle(-0.691150, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6778.852051, 337.897400, -3739.166748),
angle = Angle(-0.753982, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6777.474609, 337.897400, -3740.543701),
angle = Angle(-0.816814, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6776.014160, 337.897400, -3741.831543),
angle = Angle(-0.879646, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6774.475586, 337.897400, -3743.025146),
angle = Angle(-0.942478, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6772.864258, 337.897400, -3744.120117),
angle = Angle(-1.005310, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6771.187988, 337.897400, -3745.111328),
angle = Angle(-1.068141, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6769.453125, 337.897400, -3745.995605),
angle = Angle(-1.130973, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6767.666016, 337.897400, -3746.769043),
angle = Angle(-1.193805, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6765.833496, 337.897400, -3747.428711),
angle = Angle(-1.256637, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6763.963379, 337.897400, -3747.971924),
angle = Angle(-1.319469, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6762.062988, 337.897400, -3748.396729),
angle = Angle(-1.382301, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6760.139160, 337.897400, -3748.701416),
angle = Angle(-1.445133, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6758.200684, 337.897400, -3748.884766),
angle = Angle(-1.507964, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
},
{
position = Vector3(-6756.253906, 337.897400, -3748.945801),
angle = Angle(-1.570796, -0.000000, 0.000000),
model = "17x48.fl/go666-b.lod",
collision = "17x48.fl/go666_lod1-b_col.pfx"
}
}
}
}
| 36,170
|
Hallkezz/KoastFreeroam-2021
|
space = box.schema.space.create('tweedledum')
i0 = space:create_index('primary', { type = 'tree', parts = {1, 'num'}, unique = true })
i1 = space:create_index('i1', { type = 'tree', parts = {2, 'num'}, unique = false })
i2 = space:create_index('i2', { type = 'tree', parts = {3, 'num'}, unique = false })
i3 = space:create_index('i3', { type = 'tree', parts = {4, 'str', 5, 'str'}, unique = false })
i4 = space:create_index('i4', { type = 'tree', parts = {7, 'str', 6, 'str'}, unique = false })
i5 = space:create_index('i5', { type = 'tree', parts = {9, 'num'}, unique = false })
i6 = space:create_index('i6', { type = 'tree', parts = {7, 'str', 6, 'str', 4, 'str', 5, 'str', 9, 'num'}, unique = true })
space:insert{0, 0, 100, 'Joe', 'Sixpack', 'Drinks', 'Amstel', 'bar', 2000}
space:insert{1, 1, 200, 'Joe', 'Sixpack', 'Drinks', 'Heineken', 'bar', 2001}
space:insert{2, 2, 200, 'Joe', 'Sixpack', 'Drinks', 'Carlsberg', 'bar', 2002}
space:insert{3, 3, 300, 'Joe', 'Sixpack', 'Drinks', 'Corona Extra', 'bar', 2003}
space:insert{4, 4, 300, 'Joe', 'Sixpack', 'Drinks', 'Stella Artois', 'bar', 2004}
space:insert{5, 5, 300, 'Joe', 'Sixpack', 'Drinks', 'Miller Genuine Draft', 'bar', 2005}
space:insert{6, 6, 400, 'John', 'Smoker', 'Hits', 'A Pipe', 'foo', 2006}
space:insert{7, 7, 400, 'John', 'Smoker', 'Hits', 'A Bong', 'foo', 2007}
space:insert{8, 8, 400, 'John', 'Smoker', 'Rolls', 'A Joint', 'foo', 2008}
space:insert{9, 9, 400, 'John', 'Smoker', 'Rolls', 'A Blunt', 'foo', 2009}
-- In non-unique indexes select output order is undefined,
-- so it's better to additionally sort output to receive same order every time.
function sort_cmp(a, b) return a[1] < b[1] and true or false end
function sort(t) table.sort(t, sort_cmp) return t end
space.index['primary']:get{1}
sort(space.index['i1']:select{2})
sort(space.index[2]:select({300}))
#space.index['i3']:select({'Joe', 'Sixpack'})
#space.index['i3']:select('John')
#space.index['i4']:select('A Pipe')
{sort(space.index['i4']:select{'Miller Genuine Draft', 'Drinks'})}
sort(space.index['i5']:select{2007})
sort(space.index[6]:select{'Miller Genuine Draft', 'Drinks'})
space:delete{6}
space:delete{7}
space:delete{8}
space:delete{9}
space:insert{6, 6ULL, 400ULL, 'John', 'Smoker', 'Hits', 'A Pipe', 'foo', 2006}
space:insert{7, 7ULL, 400ULL, 'John', 'Smoker', 'Hits', 'A Bong', 'foo', 2007}
space:insert{8, 8ULL, 400ULL, 'John', 'Smoker', 'Rolls', 'A Joint', 'foo', 2008}
space:insert{9, 9ULL, 400ULL, 'John', 'Smoker', 'Rolls', 'A Blunt', 'foo', 2009}
sort(space.index['i1']:select{6ULL})
sort(space.index['i1']:select{6})
sort(space.index['i2']:select(400ULL))
sort(space.index['i2']:select(400))
sort(space:select{})
-- Test incorrect keys - supplied key field type does not match index type
-- https://bugs.launchpad.net/tarantool/+bug/1072624
space:insert{'', 1, 2, '', '', '', '', '', 0}
space:insert{'xxxxxxxx', 1, 2, '', '', '', '', '', 0}
space:insert{1, '', 2, '', '', '', '', '', 0}
space:insert{1, 'xxxxxxxxxxx', 2, '', '', '', '', '', 0}
space:drop()
sort = nil
sort_cmp = nil
| 3,051
|
gridgentoo/Tarantool.Lua.Net
|
--- 客户端模块基础类, Client Module Base Class
-- @module ClientBase, Client-side
-- @copyright Lilith Games, Avatar Team
-- @author Yuancheng Zhang
local ClientBase = class('ClientBase')
function ClientBase:GetSelf()
return self
end
--- 加载的时候运行的代码
function ClientBase:InitDefault(_module)
-- print(string.format('[ClientBase][%s] InitDefault()', self.name))
-- 初始化默认监听事件
EventUtil.LinkConnects(localPlayer.C_Event, _module, self)
end
--- Debug模式下打印日志
-- self.debug 针对模块本身的debug开关
-- FrameworkConfig.DebugMode 框架中的全局debug开关
function ClientBase:Log(...)
if self.debug and FrameworkConfig.DebugMode then
print(string.format('[%s]', self.name), ...)
end
end
return ClientBase
| 701
|
endaye/social-island
|
EditorDisableShout = EditorDisableShout or class(MissionScriptEditor)
function EditorDisableShout:create_element()
self.super.create_element(self)
self._element.class = "ElementDisableShout"
self._element.values.elements = {}
self._element.values.disable_shout = true
end
function EditorDisableShout:_build_panel()
self:_create_panel()
self:BuildElementsManage("elements", nil, {"ElementSpawnCivilian", "ElementSpawnEnemyDummy"})
self:BooleanCtrl("disable_shout")
end
| 479
|
MiamiCenterPL/BeardLib-Editor
|
----
-- Handles console functionality.
--
-- Currently doesn't do much except having a helper which extends a `ConsoleScreen` to add new word
-- prediction dictionaries (auto-complete) to the console input field:
--
-- SDK.Console.AddWordPredictionDictionaries({
-- { delim = "SDK.", num_chars = 0, words = {
-- "Config",
-- "Console",
-- "Constant",
-- "Debug",
-- "DebugUpvalue",
-- "Dump",
-- "Entity",
-- "FrontEnd",
-- "Input",
-- "Method",
-- "ModMain",
-- "PersistentData",
-- "Player",
-- "Remote",
-- "RPC",
-- "Test",
-- "Thread",
-- "World",
-- } },
-- })
--
-- Now after entering "SDK." into the console input, you will get your auto-complete.
--
-- **Source Code:** [https://github.com/dstmodders/dst-mod-sdk](https://github.com/dstmodders/dst-mod-sdk)
--
-- @module SDK.Console
-- @see SDK
--
-- @author [Depressed DST Modders](https://github.com/dstmodders)
-- @copyright 2020
-- @license MIT
-- @release 0.1
----
local Console = {}
local SDK
--- General
-- @section general
--- Adds word prediction dictionaries.
-- @tparam table dictionaries
function Console.AddWordPredictionDictionaries(dictionaries)
SDK.env.AddClassPostConstruct("screens/consolescreen", function(self, ...)
for _, dictionary in pairs(dictionaries) do
if type(dictionary) == "table" then
self.console_edit:AddWordPredictionDictionary(dictionary)
elseif type(dictionary) == "function" then
self.console_edit:AddWordPredictionDictionary(dictionary(self, ...))
end
end
end)
end
--- Lifecycle
-- @section lifecycle
--- Initializes.
-- @tparam SDK sdk
-- @treturn SDK.Console
function Console._DoInit(sdk)
SDK = sdk
return SDK._DoInitModule(SDK, Console, "Console")
end
return Console
| 2,013
|
dstmodders/dst-mod-sdk
|
local fs = require('efmls-configs.fs')
local formatter = 'autopep8'
local command = string.format('%s -', fs.executable(formatter))
return {
formatCommand = command,
formatStdin = true,
}
| 194
|
lucax88x/efmls-configs-nvim
|
-- array_a
print("array_a[0] = "..array_a[1])
print("array_a[50] = "..array_a[50])
print("array_a[51] = "..array_a[51])
print("array_a[100] = "..array_a[100])
print("==============================================")
-- map_a
print("map_a[10.2] = "..map_a[10.2])
print("map_a[10.3] = "..map_a[20.3])
print("==============================================")
print("map_b.B_KEY_1 = "..map_b.B_KEY_1)
print("map_b.B_KEY_2 = "..map_b.B_KEY_2)
print("map_b.B_KEY_3 = "..map_b.B_KEY_3)
-- table_array
print("==============================================")
table_array={}
table_array[1]=88880
table_array[2]=88881
table_array[3]=88885
table_array[4]=88886
table_array[5]=88888
table_array[6]=88889
table_array[7]=88899
table_array[8]=88999
table_array[9]=89999
table_array[10]=99999
table_map={}
table_map[121]=111.1111
table_map[222]=222.2222
| 841
|
sailzeng/zcelib
|
function Server_StartGame(game, standing)
local SUPPLYLIMITMULT = 30
local defaultBonuses = game.Map.Bonuses
local overriddenBonuses = game.Settings.OverriddenBonuses
local publicGameData = Mod.PublicGameData
publicGameData.supplyLimitData = {}
publicGameData.whiteList = {} --Array of player IDs for whom attrition is nullified
local whiteListBonuses = {} --Array of bonus IDs that, if controlled by a player, nullify attrition for that player globally
local whiteBonusCount = 1
for bonusID, bonusDetails in pairs(defaultBonuses) do
publicGameData.supplyLimitData[bonusID] = bonusDetails.Amount * SUPPLYLIMITMULT
if bonusDetails.Name == "The March of the White Walkers" then
whiteListBonuses[whiteBonusCount] = bonusDetails
whiteBonusCount = whiteBonusCount + 1
end
end
for bonusID, _ in pairs(overriddenBonuses) do
publicGameData.supplyLimitData[bonusID] = game.Map.Bonuses[bonusID].Amount * SUPPLYLIMITMULT
if game.Map.Bonuses[bonusID].Name == "The March of the White Walkers" then
whiteListBonuses[whiteBonusCount] = game.Map.Bonuses[bonusID]
whiteBonusCount = whiteBonusCount + 1
end
end
local cur = 1
for _, bonusDetails in pairs(whiteListBonuses) do
for _, terrID in pairs(bonusDetails.Territories) do
if not standing.Territories[terrID].IsNeutral then
publicGameData.whiteList[cur] = standing.Territories[terrID].OwnerPlayerID
cur = cur + 1
end
end
end
Mod.PublicGameData = publicGameData
end
| 1,510
|
achance6/WLattrition
|
local ChangeHistoryService = game:GetService("ChangeHistoryService")
local TextService = game:GetService("TextService")
local HttpService = game:GetService("HttpService")
local RunService = game:GetService("RunService")
local Selection = game:GetService("Selection")
if (not RunService:IsStudio()) then warn("PropertiesMod only works in Studio") return end
if RunService:IsRunMode() then warn("PropertiesMod only works in Edit mode") return end
---
local root = script.Parent
local includes = root:WaitForChild("includes")
local defaultEditors = root:WaitForChild("default_editors")
local defaultExtensions = root:WaitForChild("default_extensions")
local RobloxAPI = require(includes:WaitForChild("RobloxAPI"))
local EditorUtilities = require(includes:WaitForChild("EditorUtilities"))
local Widget = require(includes:WaitForChild("PropertiesWidget"))
local Themer = require(includes:WaitForChild("Themer"))
local t = require(includes:FindFirstChild("t"))
---
local DEFAULT_SETTINGS = {
Config = {
CacheDuration = 7 * 86400,
-- 7 days
ShowNotScriptableProperties = true,
ShowDeprecatedProperties = false,
ShowHiddenProperties = false,
PreloadClasses = "Common",
-- Common, All, or None,
EditorColumnWidth = 110,
RowHeight = 26,
TextSize = 14,
},
Cache = {
LastFetchTime = 0,
},
EditorPreferences = {},
PropertyCategoryOverrides = {},
CategoryStateMemory = {},
}
local EDITOR_LIB = {
Themer = Themer,
}
local T_MAP = {
bool = "boolean",
float = "number",
double = "number",
int64 = "integer",
int = "integer"
}
local API
local APIData
local APILib
local APIOperator
local loadedEditors = {
["*"] = EditorUtilities.ConstructEditors(defaultEditors:WaitForChild("fallback"))[1],
}
local cachedPluginObjects = {}
local pluginSettings = DEFAULT_SETTINGS
--plugin:GetSetting("PropertiesMod") and HttpService:JSONDecode(plugin:GetSetting("PropertiesMod")) or DEFAULT_SETTINGS
-- SelectionChanged that doesn't spam that much
-- https://devforum.roblox.com/t/weird-selectionchanged-behavior/22024/2
-- Credit to Fractality
local SelectionChanged
do
local selectionChanged = Instance.new("BindableEvent")
local d0, d1 = true, true
RunService.Heartbeat:Connect(function()
d0, d1 = true, true
end)
Selection.SelectionChanged:Connect(function()
if d0 then
d0 = false
selectionChanged:Fire()
elseif d1 then
d1 = false
RunService.Heartbeat:Wait()
selectionChanged:Fire()
end
end)
SelectionChanged = selectionChanged.Event
end
---
local function purgeDuplicates(tab)
if (#tab <= 1) then return end
local x = 1
repeat
for i = #tab, x + 1, -1 do
if (tab[i] == tab[x]) then
table.remove(tab, i)
end
end
x = x + 1
until (x >= #tab)
end
local function loadExtension(module)
local extension = require(module)
local apiExtensions = extension.API
local behaviourExtensions = extension.Behaviours
APIData:Extend(apiExtensions or {})
APIOperator:ExtendCustomBehaviours(behaviourExtensions or {})
end
local function getEditorsForFilter(filter)
local matchingEditors = {}
for editorName, editor in pairs(loadedEditors) do
if editor.Filters[filter] then
matchingEditors[#matchingEditors + 1] = editorName
end
end
return matchingEditors
end
--[[
Determines an editor to be used for a property
@param string The class name
@param string The property name
@return string The name of the editor
--]]
local function getEditorForProperty(className, propertyName)
local matchingEditors
local propertyData = APIData.Classes[className].Properties[propertyName]
local propertyValueType = propertyData.ValueType
local category = propertyValueType.Category
local name = propertyValueType.Name
-- Property-specific editor > Property data-type editor > *
-- 1. Get editors for this specific property
local propertyNameFilter = "Property:" .. Widget.GetPropertyNormalName(className, propertyName)
matchingEditors = getEditorsForFilter(propertyNameFilter)
local editorPreference = pluginSettings.EditorPreferences[propertyNameFilter]
if (#matchingEditors == 1) then
return matchingEditors[1]
elseif (#matchingEditors > 1) then
return matchingEditors[1]
-- for now, just return the first item
-- in the future, preferences should be incorporated
end
-- 2. Get editors for the property's data type
local propertyTypeFilter
if (category == "Primitive") then
if ((name ~= "int") and (name ~= "int64")) then
propertyTypeFilter = category .. ":" .. name
else
propertyTypeFilter = "Primitive:int"
end
elseif ((category == "DataType") or (category == "Enum")) then
propertyTypeFilter = category .. ":" .. name
end
matchingEditors = getEditorsForFilter(propertyTypeFilter)
if (#matchingEditors == 1) then
return matchingEditors[1]
elseif (#matchingEditors > 1) then
return matchingEditors[1]
end
-- 3. Use the fallback editor
return "*"
end
local function getSafeSelection()
local selection = Selection:Get()
local filteredSelection = {}
for i = 1, #selection do
local obj = selection[i]
local success, isValidClassName = pcall(function()
-- 1. Query one of the object's properties to see if it passes the security check
-- 2. Check the class name to make sure it isn't blank (because that's a thing I guess)
return (obj.ClassName ~= "")
end)
if (success and isValidClassName) then
filteredSelection[#filteredSelection + 1] = obj
end
end
return filteredSelection
end
local function loadEditor(className, propertyName)
local editorId = getEditorForProperty(className, propertyName)
if (not editorId) then return end
local editor = loadedEditors[editorId]
local uniqueId = editor.UniqueId
local normalName = Widget.GetPropertyNormalName(className, propertyName)
local propertyData = APIData.Classes[className].Properties[propertyName]
if propertyData.Tags.NotScriptable then return end
local propertyValueChangedConnections = {}
local propertyValueUpdatedEvent = Instance.new("BindableEvent")
local function getHomogeneousValue()
local selection = getSafeSelection()
if (#selection <= 0) then return end
local filteredSelection = {}
for i = 1, #selection do
local obj = selection[i]
if obj:IsA(className) then
filteredSelection[#filteredSelection + 1] = obj
end
end
if (#filteredSelection <= 0) then
return
elseif (#filteredSelection == 1) then
return APIOperator:GetProperty(filteredSelection[1], propertyName, className)
end
local control = APIOperator:GetProperty(filteredSelection[1], propertyName, className)
for i = 1, #filteredSelection do
local obj = filteredSelection[i]
if (APIOperator:GetProperty(obj, propertyName, className) ~= control) then return end
end
return control
end
local updatingMode = "write"
local function setSelectionPropertyCallback(value)
if (updatingMode == "no_updates") then return end
local selection = getSafeSelection()
if (updatingMode == "write") then
ChangeHistoryService:SetWaypoint("PropertiesMod.BeforeSet:" .. normalName)
end
for i = 1, #selection do
local obj = selection[i]
if obj:IsA(className) then
obj[propertyName] = value
end
end
if (updatingMode == "write") then
ChangeHistoryService:SetWaypoint("PropertiesMod.AfterSet:" .. normalName)
end
propertyValueUpdatedEvent:Fire(getHomogeneousValue())
end
local setSelectionProperty
do
-- local propertyData = APIData.Classes[className].Properties[propertyName]
local propertyValueType = propertyData.ValueType
local category = propertyValueType.Category
local name = propertyValueType.Name
if (category == "Primitive") then
setSelectionProperty = t.wrap(setSelectionPropertyCallback, T_MAP[name] and t[T_MAP[name]] or t[name])
elseif (category == "DataType") then
setSelectionProperty = t.wrap(
setSelectionPropertyCallback,
function(value) return typeof(value) == ((name ~= "Content") and name or "string") end
)
elseif (category == "Enum") then
setSelectionProperty = t.wrap(setSelectionPropertyCallback, t.enum(Enum[name]))
end
end
local selectionChanged = SelectionChanged:Connect(function()
local selection = Selection:Get()
for i = 1, #propertyValueChangedConnections do
propertyValueChangedConnections[i]:Disconnect()
end
propertyValueChangedConnections = {}
for i = 1, #selection do
local obj = selection[i]
if (obj:IsA(className) and propertyData.Native) then
propertyValueChangedConnections[#propertyValueChangedConnections + 1] = obj:GetPropertyChangedSignal(propertyName):Connect(function()
propertyValueUpdatedEvent:Fire(getHomogeneousValue())
end)
end
end
propertyValueUpdatedEvent:Fire(getHomogeneousValue())
end)
local main = {
Display = Widget.PropertyRows[normalName]:FindFirstChild("Editor"),
PropertyNormal = normalName,
CreateDockWidgetPluginGui = function(pluginGuiId, dockWidgetPluginGuiInfo)
local pluginGuiName = "PropertiesMod.PluginGuis:" .. uniqueId .. ":" .. pluginGuiId
local cachedPluginGui = cachedPluginObjects[pluginGuiName]
if (not cachedPluginGui) then
cachedPluginObjects[pluginGuiName] = plugin:CreateDockWidgetPluginGui(pluginGuiName, dockWidgetPluginGuiInfo)
return cachedPluginObjects[pluginGuiName]
else
return cachedPluginGui
end
end,
CreatePluginAction = function(...) return plugin:CreatePluginAction(...) end,
CreatePluginMenu = function(...) return plugin:CreatePluginMenu(...) end,
GetSetting = function(settingName)
return plugin:GetSetting("PropertiesMod.EditorSettings:" .. uniqueId .. ":" .. settingName)
end,
SetSetting = function(settingName, newValue)
plugin:SetSetting("PropertiesMod.EditorSettings:" .. uniqueId .. ":" .. settingName, newValue)
end,
GetConfigSetting = function(settingName)
return pluginSettings.Config[settingName]
end,
Update = setSelectionProperty,
GetUpdatingMode = function() return updatingMode end,
SetUpdatingMode = function(newUpdatingMode)
if ((newUpdatingMode == "write") or (newUpdatingMode == "preview") or (newUpdatingMode == "no_updates")) then
updatingMode = newUpdatingMode
end
end,
GetPropertyValue = getHomogeneousValue,
PropertyValueUpdated = propertyValueUpdatedEvent.Event,
_PropertyValueUpdatedEvent = propertyValueUpdatedEvent,
_SelectionChangedEvent = selectionChanged,
}
editor.Constructor(main, EDITOR_LIB, propertyData)
propertyValueUpdatedEvent:Fire(getHomogeneousValue())
end
local function selectionChanged()
Widget.ResetScrollPosition()
Widget.ResetCategoryVisibility()
Widget.ResetRowVisibility()
local selection = getSafeSelection()
if (#selection <= 0) then return end
local newColumnWidth = 0
-- local rowsToAdd = {}
-- deal with performance issues later
for i = 1, #selection do
local obj = selection[i]
local properties = APILib:GetProperties(obj.ClassName)
for className, classProperties in pairs(properties) do
for j = 1, #classProperties do
local propertyName = classProperties[j]
local propertyCategory = APIData.Classes[className].Properties[propertyName].Category
local normalName = Widget.GetPropertyNormalName(className, propertyName)
local textWidth = TextService:GetTextSize(propertyName, pluginSettings.Config.TextSize, Enum.Font.SourceSans, Vector2.new()).X
if (textWidth > newColumnWidth) then newColumnWidth = textWidth end
if Widget.PropertyRows[normalName] then
Widget.SetRowVisibility(normalName, true)
else
Widget.AddRow(className, propertyName, true)
-- rowsToAdd[#rowsToAdd + 1] = {className, propertyName, true}
loadEditor(className, propertyName)
end
Widget.SetCategoryVisibility(propertyCategory, true)
end
end
end
--[[
if (#rowsToAdd > 0) then
Widget.AddRows(rowsToAdd)
end
--]]
Widget.SetPropertyNameColumnWidth(newColumnWidth + 24 + 10)
end
--- Load API
do
local lastFetchTime = pluginSettings.Cache.LastFetchTime
local cacheDuration = pluginSettings.Config.CacheDuration
local rawAPIData
if ((tick() - lastFetchTime) >= cacheDuration) then
-- wait for HttpEnabled to do something, I guess
wait()
print("[PropertiesMod] Fetching the latest API, please wait...")
print("[PropertiesMod] Fetching from https://raw.githubusercontent.com/CloneTrooper1019/Roblox-Client-Tracker/roblox/API-Dump.json")
local success, data = pcall(function() return HttpService:GetAsync("https://raw.githubusercontent.com/CloneTrooper1019/Roblox-Client-Tracker/roblox/API-Dump.json") end)
if (not success) then
warn("[PropertiesMod] Could not get API data, got error: " .. data)
return
end
rawAPIData = HttpService:JSONDecode(data)
pluginSettings.Cache.Data = rawAPIData
print("[PropertiesMod] Successfully loaded data")
else
rawAPIData = pluginSettings.Cache.Data
print("[PropertiesMod] Loaded cached data")
end
API = RobloxAPI.new(rawAPIData, true)
APIData = API.Data
APILib = API.Library
APIOperator = API.Operator
end
if (not pluginSettings.Config.ShowNotScriptableProperties) then
APIData:RemoveNotScriptableProperties()
end
if (not pluginSettings.Config.ShowDeprecatedProperties) then
APIData:RemoveDeprecatedMembers()
end
if (not pluginSettings.Config.ShowHiddenProperties) then
APIData:RemoveHiddenProperties()
end
APIData:RemoveRobloxMembers()
APIData:RemoveLocalUserSecurityMembers()
APIData:MarkNotAccessibleSecurityPropertiesAsReadOnly()
for _, extension in pairs(defaultExtensions:GetChildren()) do
loadExtension(extension)
end
-- BasePart/CenterOfMass is disabled, so it's being removed until it's enabled
APIData.Classes.BasePart.Properties.CenterOfMass = nil
-- Instance/RobloxLocked cannot be accessed, but isn't marked in the API as such
APIData.Classes.Instance.Properties.RobloxLocked = nil
Widget.Init(plugin, pluginSettings, {
APIData = APIData,
APILib = APILib
})
-- Load Editors
local function addEditor(editor)
local uniqueId = editor.UniqueId
if (uniqueId == "fallback") then return end
-- todo: check stuff here
loadedEditors[uniqueId] = editor
--[[
local uniqueId = editor.UniqueId
if (uniqueId == "editor.$native.fallback") then return end
local filters = editor.Filters
for i = 1, #filters do
local filter = filters[i]
if string.match(filter, "instance:") then
warn("Instance editors are not supported")
else
if (not loadedEditors[filter]) then
loadedEditors[filter] = editor
-- print("loaded editor " .. uniqueId)
else
if (pluginSettings.FilterPreferences[filter] == uniqueId) then
loadedEditors[filter] = editor
-- print("loaded editor " .. uniqueId)
end
end
end
end
--]]
end
do
for _, editorBase in pairs(defaultEditors:GetChildren()) do
local editors = EditorUtilities.ConstructEditors(editorBase)
for _, editor in pairs(editors) do
addEditor(editor)
end
end
end
-- Preload Classes
do
local classes
if (pluginSettings.Config.PreloadClasses == "All") then
classes = APIData.Classes
elseif (pluginSettings.Config.PreloadClasses == "Common") then
classes = require(includes:WaitForChild("CommonClasses"))
end
-- local rowsToAdd = {}
if classes then
for className in pairs(classes) do
local properties = APILib:GetImmediateProperties(className)
for i = 1, #properties do
local propertyName = properties[i]
Widget.AddRow(className, propertyName, false)
-- rowsToAdd[#rowsToAdd + 1] = {className, propertyName, true}
loadEditor(className, propertyName)
end
end
end
end
-- init
local selectionConnection = SelectionChanged:Connect(selectionChanged)
plugin.Unloading:Connect(function()
selectionConnection:Disconnect()
Widget.Unload()
plugin:SetSetting("PropertiesMod", HttpService:JSONEncode(pluginSettings))
print("Cleaned up PropertiesMod")
end)
selectionChanged()
| 17,858
|
Blupo/PropertiesMod
|
--[[
Desc: User Interface Manager (Singleton)
Author: SerDing
Since: 2018-08-14 15:41:03
Last Modified time: 2018-08-14 15:41:03
Docs:
* Manage all panels
* Handle input from mouse and virtual buttons.
]]
local _Vector2 = require("utils.vector2")
local _MATH = require("engine.math")
local _INPUT = require("engine.input") ---@type Engine.Input
local _Mouse = require("engine.input.mouse")
local _GRAPHICS = require("engine.graphics")
local _Color = require("engine.graphics.config.color")
local _RESOURCE = require("engine.resource")
local _CAMERA = require("system.scene.camera")
local _Stack = require("core.stack")
local _Panel = require("system.gui.panels.panel")
local _CONFIG = require("setting")
---@class UiManager
---@field protected _panelTable table<string, string>
---@field protected _panels GUI.Panel[] @panel list
---@field protected _topPanel GUI.Panel
---@field protected _persistentPanel GUI.Panel
---@field protected _dragWidget GUI.Widgets.Base
local _UiManager = {}
local this = _UiManager
local emptyPanel = _Panel.New("empty")
local easeInAnim = {
color = _Color.New(255, 255, 255, 0),
easeInSpeed = 0.1,
from = 0,
to = 255,
positiveStopRange = 2.0,
negativeStopRange = 5.0,
isRunning = false,
direction = 1,
}
local mathAbs = math.abs
---@param persistentPanel string
function _UiManager.Init(persistentPanel)
this._panelTable = _RESOURCE.LoadUiData("panels")
this._panels = {}
this._topPanel = emptyPanel
this._persistentPanel = emptyPanel
this._stack = _Stack.New(10)
this._scale = _Vector2.New(_CAMERA._scale.x / 1.3, _CAMERA._scale.y / 1.3)
this._lastMousePosition = _Vector2.New(_Mouse.GetScaledMousePosition())
this._dragWidget = nil
this._dragOffset = _Vector2.New(0, 0)
--local font = love.graphics.newFont("resource/font/simsun.ttc", 16)
--local font = love.graphics.newFont("resource/font/simsun_bitmap_fnt/simsun12.fnt")
local fontSize = math.floor(this._scale.x * 12)
local font = love.graphics.newFont("resource/font/notosans/normal.otf", fontSize)
love.graphics.setFont(font)
Log.Debug("fontsize:", fontSize)
for key, value in pairs(this._panelTable) do
this.AddPanel(key, require(value).New())
end
if persistentPanel then
this.Open(persistentPanel)
this._persistentPanel = this._topPanel
end
_INPUT.Register(_UiManager)
_INPUT.mouse:AddListener(_UiManager)
end
function _UiManager.Draw()
_GRAPHICS.Push()
_GRAPHICS.Scale(this._scale:Get())
this._persistentPanel:Draw()
if this._topPanel and this._topPanel ~= this._persistentPanel then
--_GRAPHICS.SetColor(0, 0, 0, 200)
--_GRAPHICS.DrawRect("fill", 0, 0, _GRAPHICS.GetDimension())
--_GRAPHICS.ResetColor()
if easeInAnim.isRunning then
local nowAlpha = easeInAnim.color:Get("alpha")
local absAlphaDist = mathAbs(nowAlpha - easeInAnim.to)
if easeInAnim.direction == 1 and absAlphaDist > easeInAnim.positiveStopRange then
easeInAnim.from = _MATH.Lerp(easeInAnim.from, easeInAnim.to, easeInAnim.easeInSpeed)
elseif easeInAnim.direction == -1 and absAlphaDist > easeInAnim.negativeStopRange then
easeInAnim.from = _MATH.Lerp(easeInAnim.from, easeInAnim.to, easeInAnim.easeInSpeed)
else
easeInAnim.isRunning = false
end
easeInAnim.color:Set(255, 255, 255, easeInAnim.from)
this._topPanel.root:SetRenderValue("color", easeInAnim.color:Get())
if easeInAnim.direction == -1 and easeInAnim.isRunning == false then
this._Close()
end
end
if this._topPanel ~= this._persistentPanel then
this._topPanel:Draw()
end
end
_GRAPHICS.Pop()
end
--- open a panel
---@param name string
---@param anim boolean
function _UiManager.Open(name, anim)
if this._stack:Size() < this._stack:Capacity() then
this._stack:Push(this.GetPanel(name))
this._topPanel = this._stack:GetTopE()
this._topPanel:OnEnable()
if anim then
easeInAnim.direction = 1
easeInAnim.to = 255
easeInAnim.isRunning = true
this._topPanel.root:SetRenderValue("color", easeInAnim.color:Get())
end
end
end
--- close current panel
function _UiManager.Close()
if this._stack:Size() > 1 and easeInAnim.isRunning == false then
easeInAnim.direction = -1
easeInAnim.to = 0
easeInAnim.isRunning = true
this._topPanel.root:SetRenderValue("color", easeInAnim.color:Get())
this._topPanel:OnDisable()
--local closeThread = coroutine.create(this._Close)
end
end
function _UiManager._Close()
this._stack:Pop()
this._topPanel = this._stack:GetTopE()
end
---@param name string
---@param panel GUI.Panel
function _UiManager.AddPanel(name, panel)
this._panels[name] = panel
end
---@param name string
function _UiManager.GetPanel(name)
return this._panels[name]
end
function _UiManager.GetWidget(panelName, widgetName)
return this._panels[panelName]:GetWidgetById(widgetName)
end
---@param name string
function _UiManager.OnOff(name)
if this._topPanel.name == name then
this.Close()
else
this.Open(name, true)
end
end
---@param x float
---@param y float
---@param button int @left:1, middle:2, right:3.
---@param istouch boolean
function _UiManager.OnMousePress(_, x, y, button, istouch)
if button == 1 and not easeInAnim.isRunning then
---@param w GUI.Widgets.Base
local function HandleEvent(w)
if w:CheckPoint(x, y) then
w:MousePressed(button, x - w.x, y - w.y)
if _CONFIG.debug.uidrag then
this._dragWidget = w
this._dragOffset:Set(x - w.x, y - w.y)
end
end
end
this._topPanel:DoForWidgets(HandleEvent)
end
end
---@param x float
---@param y float
---@param button int @left:1, middle:2, right:3.
---@param istouch boolean
function _UiManager.OnMouseRelease(_, x, y, button, istouch)
if button == 1 and not easeInAnim.isRunning then
---@param w GUI.Widgets.Base
local function HandleEvent(w)
if w:CheckPoint(x, y) then
w:MouseReleased(button, x - w.x, y - w.y)
this._dragWidget = nil
else
w.mousePressed = false
end
end
this._topPanel:DoForWidgets(HandleEvent)
end
end
---@param x float
---@param y float
---@param dx float
---@param dy float
function _UiManager.OnMouseMove(_, x, y, dx, dy)
---@param w GUI.Widgets.Base
local function HandleEvent(w)
local lastIsIn = w:CheckPoint(this._lastMousePosition:Get())
local nowIsIn = w:CheckPoint(x, y)
if not lastIsIn and nowIsIn then
w:MouseEntered()
elseif lastIsIn and not nowIsIn then
w:MouseExited()
end
end
this._topPanel:DoForWidgets(HandleEvent)
this._lastMousePosition:Set(x, y) -- update last mouse position
if this._dragWidget then
local sx, sy, sz = this._dragWidget:GetRenderValue("position", true)
this._dragWidget:SetRenderValue("position", sx + dx, sy + dy, sz)
end
end
function _UiManager.HandleAction(_, action, state)
if state == EInput.STATE.PRESSED then
if action == "main-ui" then
this.OnOff("inventory")
end
end
if state == EInput.STATE.RELEASED then
end
end
function _UiManager.HandleAxis(_, axis, value)
end
return _UiManager
| 7,703
|
SerDing/Gear-of-Fate
|
local mod = foundation.new_module("foundation_node_sounds", "1.0.1")
mod:require("node_sounds.lua")
foundation.com.node_sounds = foundation.com.NodeSoundsRegistry:new()
| 171
|
IceDragon200/mt-foundation
|
local DSL = "podman"
local DEBUGGING = false --> Toggle DEBUG() calls
local HOST = false --> Toggle --network host mode
local domain = os.getenv("PODMAN_DOMAIN") or "home.arpa"
local creds = os.getenv("PODMAN_CREDS")
local systemd_unit_pre = {
[===[
[Unit]
Description=__CNAME__ Container
Wants=network.target
After=network-online.target]===],
}
local systemd_unit_start = {
[===[
[Service]
Environment=PODMAN_SYSTEMD_UNIT=%n
EnvironmentFile=-/etc/podman.env/%p
EnvironmentFile=-/etc/podman.env/%p@%i
Restart=on-failure
RestartSec=5
Type=notify
NotifyAccess=all
KillMode=mixed
SystemCallArchitectures=native
MemoryDenyWriteExecute=yes
LockPersonality=yes
NoNewPrivileges=yes
RemoveIPC=yes
DevicePolicy=closed
ProtectClock=yes
RestrictRealtime=yes
RestrictSUIDSGID=yes
RestrictAddressFamilies=~AF_INET6
ExecStopPost=/usr/bin/podman rm -i -v -f __CNAME__
ExecStart=/usr/bin/podman run --name __CNAME__ \
--security-opt seccomp=/etc/podman.seccomp/__CNAME__.json \
--security-opt apparmor=unconfined \
--security-opt label=disable \
--no-hosts \
--rm \
--replace \
--sdnotify conmon \
--network __NETWORK__ \
--hostname __NAME__ \
--cpu-shares __SHARES__ \
--cpuset-cpus __CPUS__ \
--memory __MEM__ \
--cap-drop all \]===],
}
-- Last line in systemd_unit[1] is correct.
local schema = {
service_ip = "/%s/ip", --> string
service_ports = "/%s/ports", --> list{string}
}
fs.mkdir("/etc/podman.etcdb")
local bitcask = require("bitcask")
local kv_running = bitcask.open("/etc/podman.etcdb/running")
local kv_service = bitcask.open("/etc/podman.etcdb/service")
local lopper = require("lopper")
local json = require("json")
local util = require("util")
local type = type
local OK = function(msg, tbl)
tbl._module = DSL
return lopper.ok(msg, tbl)
end
local WARN = function(msg, tbl)
tbl._module = DSL
return lopper.warn(msg, tbl)
end
local DEBUG = function(msg, tbl)
if DEBUGGING then
tbl._module = DSL
return lopper.debug(msg, tbl)
end
end
local ASSERT = function(ret, msg, tbl)
if ret == nil then
tbl._module = DSL
kv_running:close()
kv_service:close()
return lopper.panic(msg, tbl)
end
end
local podman = exec.ctx("podman")
local get_id = function(n)
local try = util.retry_f(podman)
local r, so, se = try({
"inspect",
"--format",
"json",
n,
})
ASSERT(r, "BUG? Unable to find container.", {
fn = "get_id()",
stdout = so,
stderr = se,
command = "podman inspect",
name = n,
})
local t = json.decode(so)
return t[1]["Id"]
end
local get_volume = function(n)
local ret, so, se = podman({
"volume",
"inspect",
"--all",
})
ASSERT(ret, "No such volume or failure listing volumes.", {
fn = "get_volume()",
command = "volume inspect",
stdout = so,
stderr = se,
})
local j = json.decode(so)
local found = {}
if n then
for _, v in ipairs(j) do
if v.Name == n then
return v.Mountpoint
end
end
return nil
else
for _, v in ipairs(j) do
found[v.Name] = v.Mountpoint
end
return found
end
end
local volume = function(vt)
local found = get_volume()
for x, y in pairs(vt) do
if not found[x] then
local ret, so, se = podman({ "volume", "create", x })
ASSERT(ret, "Host problem? Unable to create volume.", {
fn = "volume()",
command = "volume create",
stdout = so,
stderr = se,
})
end
local mountpoint = get_volume(x)
local sh = exec.ctx("sh")
if type(y) == "table" then
for _, cmd in ipairs(y) do
local ret, so, se = sh({ "-c", cmd:gsub("__MOUNTPOINT__", mountpoint) })
ASSERT(ret, "Failure executing volume command in systemd module.", {
fn = "volume()",
command = "volume ls",
stdout = so,
stderr = se,
})
end
end
end
end
local update_hosts = function()
local running = kv_running:keys()
local dns_config = get_volume("sys_dns-config")
local hosts = {}
for _, srv in ipairs(running) do
if srv ~= "sys_dns" then
local ip = kv_service:get(schema.service_ip:format(srv))
hosts[#hosts + 1] = ("%s %s.%s %s"):format(ip, srv, domain, srv)
end
end
hosts[#hosts + 1] = ""
local hosts_file = table.concat(hosts, "\n")
ASSERT(
fs.write(dns_config .. "/hosts", hosts_file),
"Unable to write system HOSTS file",
{
fn = "update_hosts()",
}
)
end
local Reserve_IDMAP = function(id)
id = id or lopper.id
local n = 2001234560
local max = 2147483647
local kv_idmap = bitcask.open("/etc/podman.etcdb/idmap")
local key, ok
repeat
key = tostring(n)
if not kv_idmap:has(key) then
ok = kv_idmap:put(key, id)
else
n = n + 65537
end
until ok or n > max
kv_idmap:close()
ASSERT((n > max), "Reached maximum possible allocation. Clean up allocation database.", {
fn = "reserve_idmap()",
idmap = tostring(n),
})
OK("Reserved idmap allocation.", {
range = key .. "-" .. tostring(n+65536),
mark = id,
})
return key
end
local Release_IDMAP = function(key)
local n = tonumber(key)
local kv_idmap = bitcask.open("/etc/podman.etcdb/idmap")
local r = kv_idmap:delete(key)
kv_idmap:close()
OK("Released idmap allocation.", {
range = key .. "-" .. tostring(n+65536),
})
return r
end
local Running = function(direct)
if not direct then
return kv_running:keys()
end
-- Not from the etcdb but directly from podman
local r, so, se = podman({ "ps", "-a", "--format", "json" })
ASSERT(r, "Failure running podman command.", {
fn = "running()",
command = "podman ps",
stdout = so,
stderr = se,
})
local ret = json.decode(so)
local names = {}
for _, c in ipairs(ret) do
if c["State"] == "running" then
for _, n in ipairs(c["Names"]) do
names[#names + 1] = n
end
end
end
return names
end
local Ports = function(srv)
-- From etcdb
local ports = kv_service:get(schema.service_ports:format(srv))
local ret = json.decode(ports)
ASSERT((type(ret) == "table"), "BUG? The etcdb path did not return a valid value.", {
returned = ports,
decoded = ret,
})
end
local Get_Volume = get_volume
local stop = function(T)
-- Does removal from kv_running etcdb and updates dns hosts.
local c = T.reg.cname
local systemctl = exec.ctx("systemctl")
local so, se
systemctl({ "disable", "--no-block", "--now", c })
local is_inactive = function()
_, so, se = systemctl({ "is-active", c })
if so == "inactive\n" then
return true
else
return nil, so, se
end
end
local cmd = util.retry_f(is_inactive, 10)
ASSERT(cmd(), "Failed stopping container. Still up.", {
fn = "stop()",
command = "systemctl is-active",
name = c,
stdout = so,
stderr = se,
})
if HOST then
if kv_running:has(c) then
local try = util.retry_f(kv_running.delete)
local deleted = try(kv_running, c)
kv_running:close()
ASSERT(deleted, "Host problem? Unable to remove container from etcdb/running.", {
fn = "stop()",
name = c,
})
end
update_hosts()
end
OK("Stopped container(service).", {
name = c,
})
end
local start = function(T, stats)
local c = T.reg.cname
fs.mkdir("/var/log/podman") -- Checked in the next mkdir()
local logdir = "/var/log/podman/" .. lopper.id
if not fs.isdir(logdir) then
ASSERT(fs.mkdir(logdir), "BUG? Unable to create logging directory.", {
fn = "start()",
directory = logdir,
})
end
local journalctl = exec.ctx("journalctl")
local cursor
do
local r, so, se = journalctl({"-u", c, "-o", "json", "-n", "1"})
ASSERT(r, "BUG? Unable to get cursor from journalctl.", {
name = c,
fn = "start()",
command = "journalctl",
stdout = so,
stderr = se,
})
local t = json.decode(so)
if type(t) == "table" then
cursor = t["__CURSOR"]
end
end
local systemctl = exec.ctx("systemctl")
local so, se
systemctl({"daemon-reload"})
systemctl({ "start", c })
local is_active = function()
_, so, se = systemctl({ "is-active", c })
if so == "active\n" then
return true
else
return nil, so, se
end
end
local data
if not stats then
local cmd = util.retry_f(is_active, 10)
ASSERT(cmd(), "Failed starting container. Check the unit journal.", {
fn = "start()",
command = "systemctl is-active",
name = c,
stdout = so,
stderr = se,
})
data = { name = c }
else
repeat
until is_active()
local s = {
cpu = {},
mem = {},
pids = {},
}
local x, y, z, pids
local r, jo
r, jo = podman({
"stats",
"--format",
"json",
"--no-stream",
c,
})
do
local tt = 0
repeat
tt = tt + 1
x = json.decode(jo)
until type(x) == "table" or tt == 10
if tt == 10 then
ASSERT(nil, "BUG? Did not return a valid output.", {
fn = "start()",
name = c,
command = "podman stats",
})
end
end
while r and is_active() do
x = json.decode(jo)
if y ~= x[1]["cpu_percent"] then
y = x[1]["cpu_percent"]
s.cpu[#s.cpu+1]= y
end
if z ~= x[1]["mem_percent"] then
z = x[1]["mem_percent"]
s.mem[#s.mem+1]= z
end
if pids ~= x[1]["pids"] then
pids = x[1]["pids"]
s.pids[#s.pids+1]= pids
end
r, jo = podman({
"stats",
"--format",
"json",
"--no-stream",
c,
})
os.sleep(stats)
end
data = {
name = c,
cpu = s.cpu,
mem = s.mem,
pids = s.pids,
}
end
do
local jargs = {"-o", "json-pretty", "-u", c}
if cursor then
jargs[#jargs+1] = ("--after-cursor=%s"):format(cursor)
end
local _, go = journalctl(jargs)
local _, to = systemctl({"status", "-o", "json-pretty", c})
--> No error checking, we do not want to interfere with a finished run.
fs.write(("%s/%s.journal.json"):format(logdir, c), go)
fs.write(("%s/%s.status.json"):format(logdir, c), to)
fs.write(("%s/%s.output.json"):format(logdir, c), json.encode(data))
end
OK("Started container(service).", data)
end
local podman_interpolate = function(A)
local systemctl = exec.ctx("systemctl")
if A.param.NETWORK == "host" then
systemctl({
"disable",
"--no-block",
"--now",
("%s.service"):format(A.param.NAME),
})
end
local fname
if A.param.NETWORK == "host" then
fname = ("/etc/systemd/system/%s.service"):format(A.param.NAME)
elseif A.param.NETWORK == "private" then
fname = ("/etc/systemd/system/%s.pod.service"):format(A.param.NAME)
else
fname = ("/etc/systemd/system/%s.service"):format(A.reg.cname)
end
local unit, changed
if not A.param.ROOT then
unit, changed = A.reg.unit:gsub("__ID__", A.reg.id)
-- Should only match once.
ASSERT((changed == 1), "Unable to interpolate image ID.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.reg.id,
})
else
unit = A.reg.unit
end
unit, changed = unit:gsub("__NAME__", A.param.NAME)
ASSERT((changed > 1), "Unable to interpolate name.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.param.NAME,
})
unit, changed = unit:gsub("__CNAME__", A.reg.cname)
ASSERT((changed == 4), "Unable to interpolate container name.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.reg.name,
})
if unit:contains("__IP__") then
unit, changed = unit:gsub("__IP__", A.param.IP)
ASSERT((changed >= 1), "Unable to interpolate IP.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.param.IP,
})
end
unit, changed = unit:gsub("__CPUS__", A.param.CPUS)
-- Should only match once.
ASSERT((changed == 1), "Unable to interpolate --cpuset-cpus.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.param.CPUS,
})
unit, changed = unit:gsub("__MEM__", A.param.MEM)
-- Should only match once.
ASSERT((changed == 1), "Unable to interpolate --memory.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.param.MEM,
})
unit, changed = unit:gsub("__SHARES__", A.param.SHARES)
-- Should only match once.
ASSERT((changed == 1), "Unable to interpolate --cpu-shares.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.param.SHARES,
})
unit, changed = unit:gsub("__NETWORK__", A.reg.network)
-- Should only match once.
ASSERT((changed == 1), "Unable to interpolate --network.", {
fn = "podman_interpolate() -> string.gsub()",
changed = false,
to = A.reg.network,
})
ASSERT(fs.write(fname, unit), "Unable to write unit.", {
fn = "podman_interpolate() -> fs.write()",
file = fname,
})
end
local id = function(u, t)
local r, so, se = podman({
"images",
"--format",
"json",
})
ASSERT(r, "Host problem? Unable to list images.", {
fn = "id()",
command = "podman images",
stdout = so,
stderr = se,
})
local j = json.decode(so)
_, u = util.path_split(u)
local name = ("/%s:%s"):format(u, t)
for i = 1, #j do
if table.find(j[i].Names, name) then
return j[i].Id
end
end
return nil, "Container image not found."
end
local pull = function(u, t)
local pt = {
"pull",
"--tls-verify",
("%s:%s"):format(u, t),
}
if creds then
table.insert(pt, 2, creds)
table.insert(pt, 2, "--creds")
end
local r, so, se = podman(pt)
ASSERT(r, "Network or host problem? Unable to pull image.", {
fn = "pull()",
command = "podman pull",
url = u,
tag = t,
stdout = so,
stderr = se,
})
end
local Config = function(p)
local M = {}
M.start = start
M.stop = stop
local param = {
NAME = "Unit name.",
BASE = "Base unit.",
URL = "Image URL.",
TAG = "Image tag.",
CPUS = "Pin container to CPU(s). Argument to podman --cpuset-cpus.",
MEM = "Memory limit. Argument to podman --memory.",
ARGS = "(table) Arguments to any function hooks.",
IP = "Assigned IP for container",
SHARES = "CPU share. Argument to podman --cpu-shares.",
ENVIRONMENT = "(table) or JSON file(string) for environment variables.",
NETWORK = "private network name.",
CMD = "Command line to container.",
IDMAP = "uid gid range.",
ROOT = "Root directory hierarchy of a container.",
always_update = "Boolean flag, if `true` always pull the image.",
}
M.param = {} --> from user
M.reg = {} --> generated
for k in pairs(p) do
ASSERT(param[k], "Invalid parameter given.", {
fn = "config()",
parameter = k,
})
M.param[k] = p[k]
end
M.param.MEM = M.param.MEM or "512m"
M.param.ARGS = M.param.ARGS or {}
M.param.CPUS = M.param.CPUS or "1"
M.param.IP = M.param.IP or "127.0.0.1"
M.param.SHARES = M.param.SHARES or "1024"
M.param.NETWORK = M.param.NETWORK or "host"
DEBUG("Figuring out container name and network mode...", {})
if type(M.param.NETWORK) == "table" then
M.reg.netdata = util.shallowcopy(M.param.NETWORK)
M.param.NETWORK = "isolated"
end
if M.param.NETWORK ~= "host" and M.param.NETWORK ~= "private" and M.param.NETWORK ~= "isolated" then
M.reg.network = ("container:%s"):format(get_id(M.param.NETWORK .. ".pod"))
M.reg.cname = ("%s.%s"):format(M.param.NETWORK, M.param.NAME)
elseif M.param.NETWORK == "private" or M.param.NETWORK == "isolated" then
local netns = ("/var/run/netns/%s"):format(M.param.NAME)
ASSERT((fs.isdir(netns) == nil), "Network namespace already exists. Use another name.", {
fn = "config()",
name = M.param.NAME,
})
M.reg.network = "ns:" .. netns
M.reg.cname = ("%s.pod"):format(M.param.NAME)
else
HOST = true
M.reg.network = M.param.NETWORK
M.reg.cname = M.param.NAME
end
DEBUG("Processing ENVIRONMENT parameter...", {})
if M.param.ENVIRONMENT and type(M.param.ENVIRONMENT) == "string" then
local js = json.decode(fs.read(M.param.ENVIRONMENT))
ASSERT((type(js) == "table"), "Invalid JSON.", {
fn = "config()",
file = M.param.ENVIRONMENT,
returned = js,
})
M.param.ENVIRONMENT = js
end
if M.param.ENVIRONMENT and next(M.param.ENVIRONMENT) then
local password = require("password")
for k, v in pairs(M.param.ENVIRONMENT) do
if (k:upper()):contains("PASSWORD") then
if password.strength(v) < 4 then
WARN("Weak password!!", {
password = v
})
end
end
end
end
DEBUG("Generating systemd unit...", {})
local systemd = {}
do
local reqtry, modul
if M.param.BASE then
reqtry, modul = pcall(require, "systemd." .. M.param.BASE)
else
reqtry, modul = pcall(require, "systemd." .. M.param.NAME)
end
if reqtry == true then
systemd = modul
end
end
do
local instance
if next(M.param.ARGS) then
instance = systemd(M.param.ARGS)
else
instance = systemd
end
DEBUG("Generating seccomp profile...", {})
do
fs.mkdir("/etc/podman.seccomp")
local fn = ("/etc/podman.seccomp/%s.json"):format(M.reg.cname)
local default = require("seccomp")
if instance.allow and next(instance.allow) then
for _, syscall in ipairs(instance.allow) do
table.filter(default.syscalls[1]["names"], syscall)
end
end
local seccomp = json.encode(default)
ASSERT(fs.write(fn, seccomp), "Host problem? Unable to write seccomp profile.", {
fn = "config()",
filename = fn,
})
end
if instance.volumes and next(instance.volumes) then
volume(instance.volumes)
end
if instance.ports and next(instance.ports) then
local kx, ky = kv_service:put(
schema.service_ports:format(M.param.NAME),
json.encode(instance.ports)
)
ASSERT(kx, "Host problem? Unable to add ports to etcdb.", {
fn = "config()",
error = ky,
})
end
if instance.unit then
M.reg.unit = instance.unit
else
local si = util.shallowcopy(systemd_unit_pre)
local su = util.shallowcopy(systemd_unit_start)
if instance.capabilities and next(instance.capabilities) then
for _, c in ipairs(instance.capabilities) do
su[#su + 1] = ([[--cap-add %s \]]):format(c)
end
end
if M.param.ENVIRONMENT then
for k, v in pairs(M.param.ENVIRONMENT) do
su[#su + 1] = ([[-e "%s=%s" \]]):format(k, v)
end
end
if instance.mounts and next(instance.mounts) then
for k, v in pairs(instance.mounts) do
su[#su + 1] = ([[--volume %s:%s \]]):format(k, v)
end
end
if M.param.NETWORK == "isolated" or M.param.NETWORK == "private" then
su[#su + 1] = [[--dns none \]]
elseif M.param.NETWORK == "host" then
su[#su + 1] = [[--dns 127.255.255.53 \]]
end
if M.param.IDMAP then
local idmap = [[--uidmap 0:%s:65536 --gidmap 0:%s:65536 \]]
su[#su + 1] = idmap:format(M.param.IDMAP, M.param.IDMAP)
end
instance.cmd = instance.cmd or ""
M.param.CMD = M.param.CMD or instance.cmd
if not M.param.ROOT then
su[#su + 1] = ("__ID__ %s"):format(M.param.CMD)
else
su[#su + 1] = ("--rootfs %s %s"):format(M.param.ROOT, M.param.CMD)
end
if M.param.NETWORK == "host" and M.param.IP ~= "127.0.0.1" then
local n = M.param.NAME
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip link add dev %s type dummy"):format(n)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip link set dev %s mtu 65536"):format(n)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip addr add %s dev %s"):format(M.param.IP, n)
su[#su + 1] = ("ExecStopPost=/usr/sbin/ip link del dev %s"):format(n)
elseif M.param.NETWORK == "private" then
local n = M.param.NAME
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns add %s"):format(n)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns exec %s ip link set lo up"):format(n)
su[#su + 1] = ("ExecStopPost=/usr/sbin/ip netns del %s"):format(n)
elseif M.param.NETWORK == "isolated" then
local nm = M.param.NAME
local pa = M.reg.netdata.interface
local de = M.reg.netdata.gateway or ""
local ip = M.reg.netdata.address
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns add %s"):format(nm)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip link add link %s lan0 type macvlan mode bridge"):format(pa)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip link set lan0 netns %s"):format(nm)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns exec %s ip link set lan0 up"):format(nm)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns exec %s ip link set lo up"):format(nm)
if ip ~= "dhcp" then
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns exec %s ip addr add %s dev lan0"):format(nm, ip)
su[#su + 1] = ("ExecStartPre=/usr/sbin/ip netns exec %s ip route add default via %s dev lan0"):format(nm, de)
end
su[#su + 1] = ("ExecStopPost=/usr/sbin/ip netns del %s"):format(nm)
else
local nm = M.param.NETWORK
si[#si + 1] = ("BindsTo=%s.pod.service"):format(nm)
si[#si + 1] = ("After=%s.pod.service"):format(nm)
si[#si + 1] = ("PartOf=%s.pod.service"):format(nm)
end
su[#su + 1] = ""
su[#su + 1] = "[Install]"
su[#su + 1] = "WantedBy=multi-user.target"
su[#su + 1] = ""
local sifin = table.concat(si, "\n")
local sufin = table.concat(su, "\n")
M.reg.unit = sifin .. "\n\n" .. sufin
end
end
DEBUG("Pulling image if needed...", {})
if not M.param.ROOT then
M.reg.id = id(M.param.URL, M.param.TAG)
if M.param.always_update or not M.reg.id then
pull(M.param.URL, M.param.TAG)
M.reg.id = id(M.param.URL, M.param.TAG)
end
end
DEBUG("Assigning IP...", {})
if M.param.IP and M.param.NETWORK == "host" then
local r = exec.command("ip", { "link", "show", M.param.NAME })
ASSERT((r == nil), "BUG? Device already exists.", {
fn = "config()",
command = "ip link show",
name = M.param.NAME,
})
local kx, ky = kv_service:put(schema.service_ip:format(M.param.NAME), M.param.IP)
ASSERT(kx, "Host problem? Unable to add ip to etcdb.", {
fn = "config()",
error = ky,
})
end
DEBUG("Generating systemd unit...", {})
podman_interpolate(M)
ASSERT(fs.isfile("/etc/systemd/system/" .. M.reg.cname .. ".service"), "BUG? Failed to generate unit.", {
fn = "config()",
unit = M.reg.cname .. ".service"
})
DEBUG("Start or exit depending of type of container...", {})
if M.param.NETWORK == "host" then
local systemctl = exec.ctx("systemctl")
do
local r, so, se
r, so, se = systemctl({
"enable",
"--no-block",
"--now",
("%s.service"):format(M.param.NAME),
})
ASSERT(r, "Unable to start service. Check the unit journal.", {
fn = "config()",
command = "systemctl enable",
service = M.param.NAME,
stdout = so,
stderr = se,
})
end
local is_active = function()
local _, so, se = systemctl({ "is-active", M.param.NAME })
if so == "active\n" then
return true
else
return nil, so, se
end
end
do
local cmd = util.retry_f(is_active, 10)
local r, so, se = cmd()
ASSERT(r, "Failed starting container. Check the unit journal.", {
fn = "config()",
name = M.param.NAME,
stdout = so,
stderr = se,
})
end
do --> Record into etcdb
local kx, ky = kv_running:put(M.param.NAME, "ok")
ASSERT(kx, "Host problem? Unable to add service to etcdb.", {
fn = "config()",
error = ky,
})
end
if M.param.NAME ~= "sys_dns" then
update_hosts()
end
kv_running:close()
kv_service:close()
OK("Started systemd unit", {
name = M.param.NAME,
})
else
OK("Container setup done.", {
name = M.reg.cname,
network = M.param.NETWORK,
})
end
return M
end
return {
config = Config,
get_volume = Get_Volume,
ports = Ports,
running = Running,
reserve_idmap = Reserve_IDMAP,
release_idmap = Release_IDMAP,
}
| 22,928
|
tongson/lopper
|
--[[
© CloudSixteen.com do not share, re-distribute or modify
without permission of its author (kurozael@gmail.com).
Clockwork was created by Conna Wiles (also known as kurozael.)
http://cloudsixteen.com/license/clockwork.html
--]]
local COMMAND = Clockwork.command:New("RankDemote");
COMMAND.tip = "CmdRankDemote";
COMMAND.text = "CmdRankDemoteDesc";
COMMAND.arguments = 1;
COMMAND.optionalArguments = 1;
-- Called when the command has been run.
function COMMAND:OnRun(player, arguments)
local target = Clockwork.player:FindByID(arguments[1]);
if (!target) then
Clockwork.player:Notify(player, {"NotValidCharacter", arguments[1]});
return;
end;
local isForced = tobool(arguments[2]);
if (isForced) then
if (player:IsAdmin()) then
local lowestRank, rankTable = Clockwork.faction:GetLowestRank(target:GetFaction());
local targetRank, targetRankTable = Clockwork.player:GetFactionRank(target);
if (istable(rankTable) and targetRankTable.position and targetRankTable.position != rankTable.position) then
local rank, rankTable = target:GetFactionRank();
Clockwork.player:SetFactionRank(target, (Clockwork.faction:GetLowerRank(target:GetFaction(), rankTable)));
Clockwork.player:NotifyAll({"PlayerForceDemoted", player:Name(), target:Name(), (target:GetFactionRank())});
else
Clockwork.player:Notify(player, {"YouCannotDemotePlayer"})
end;
else
Clockwork.player:Notify(player, {"ForceDemoteAdminNeeded"});
end;
else
if (player:GetFaction() == target:GetFaction()) then
if (Clockwork.player:CanDemote(player, target)) then
local rank, rankTable = target:GetFactionRank();
Clockwork.player:SetFactionRank(target, (Clockwork.faction:GetLowerRank(target:GetFaction(), rankTable)));
Clockwork.player:NotifyAll({"PlayerDemotedPlayer", player:Name(), target:Name(), (target:GetFactionRank())});
else
Clockwork.player:Notify(player, {"DemotePermsNeeded"});
end;
else
Clockwork.player:Notify(player, {"DemoteFactionOnly"});
end;
end;
end;
COMMAND:Register();
| 2,053
|
xRJx/Clockwork-1
|
-- luacheck: globals ngx import
require 'lua-nucleo.import'
local resty_redis = require 'resty.redis'
--------------------------------------------------------------------------------
local redis
do
local conn
redis = function()
if conn then
return conn
end
conn = assert(resty_redis:new())
conn:set_timeout(1000) -- 1 second
assert(conn:connect('redis', 6379))
return conn
end
end
--------------------------------------------------------------------------------
return
{
redis = redis;
}
| 534
|
agladysh/highload2016
|
local constants = {}
constants.AUTH_URL = "https://roarn.space/api/studio/authenticate"
return constants
| 106
|
roarnpkg/plugin
|
module 'mock'
EnumGrowDirection = _ENUM_V{
'x',
'y'
}
CLASS: UIGridLayout ( UILayout )
:MODEL{
Field 'size' :type( 'vec2' ) :getset( 'Size' ) :meta{ decimals = 0 };
Field 'gridSize' :type( 'vec2' ) :getset( 'GridSize' );
Field 'growDirection' :enum( EnumGrowDirection );
'----';
Field 'margin' :type('vec4') :getset( 'Margin' );
Field 'spacingX' :getset( 'SpacingX' );
Field 'spacingY' :getset( 'SpacingY' );
}
registerComponent( 'UIGridLayout', UIGridLayout )
function UIGridLayout:__init()
self.gridWidth, self.gridHeight = 50, 50
self.width, self.height = -1, -1
self.spacingX, self.spacingY = 5, 5
self.growDirection = 'y'
end
function UIGridLayout:getSize()
return self.width, self.height
end
function UIGridLayout:setSize( w, h )
self.width, self.height = w, h
self:invalidate()
end
function UIGridLayout:setSpacingX( s )
self.spacingX = s
self:invalidate()
end
function UIGridLayout:getSpacingX()
return self.spacingX
end
function UIGridLayout:setSpacingY( s )
self.spacingY = s
self:invalidate()
end
function UIGridLayout:getSpacingY()
return self.spacingY
end
function UIGridLayout:getSpacing()
return self.spacingX, self.spacingY
end
function UIGridLayout:setSpacing( x, y )
x = x or 0
y = y or x
self.spacingX = x
self.spacingY = y
self:invalidate()
end
function UIGridLayout:calcSize( count )
local cols, rows = self.width, self.height
local gw, gh = self.gridWidth, self.gridHeight
local sx, sy = self:getSpacing()
local growDir = self.growDirection
local maxAvailableWidth, maxAvailableHeight = self:getMaxAvailableSize()
local availableWidth, availableHeight = self:getAvailableSize()
gw = gw
gh = gh
local availableCols = math.floor( ( availableWidth + sx )/ ( gw + sx ) )
local availableRows = math.floor( ( availableHeight + sy ) / ( gh + sy ) )
if cols <= 0 then
cols = availableCols
end
if rows <= 0 then
rows = availableRows
end
if cols <= 0 or rows <= 0 then return 0,0 end
if growDir == 'x' then
local cols1 = math.ceil( count/rows )
local maxCols =
maxAvailableWidth > 0 and math.floor( ( maxAvailableWidth + sx ) / ( gw + sx ) ) or -1
cols = maxCols > 0 and math.min( cols1, maxCols ) or cols1
elseif growDir == 'y' then
local rows1 = math.ceil( count/cols )
local maxRows =
maxAvailableHeight > 0 and math.floor( ( maxAvailableHeight + sy ) / ( gh + sy ) ) or -1
rows = maxRows > 0 and math.min( rows1, maxRows ) or rows1
else
return w, h
end
return cols, rows
end
function UIGridLayout:getGridSize()
return self.gridWidth, self.gridHeight
end
function UIGridLayout:setGridSize( w, h )
self.gridWidth, self.gridHeight = w, h
self:invalidate()
end
function UIGridLayout:onUpdate()
local owner = self:getOwner()
local info = owner:getLayoutableChildInfo()
local count = #info
--calculate grid
local cols, rows = self:calcSize( count )
local gw, gh = self:getGridSize()
local sx, sy = self:getSpacing()
local i = 1
local marginL, marginT, marginR, marginB = self:getMargin()
for y = 1, rows do
local py = ( y - 1 ) * ( gh + sy ) + marginT
for x = 1, cols do
local px = ( x - 1 ) * ( gw + sx ) + marginL
if i > count then return end
local entry = info[ i ]
local widget = entry.widget
local minW, minH = widget:getMinSize()
local w = math.max( minW, gw )
local h = math.max( minH, gh )
info.targetWidth = w
info.targetHeight = h
widget:setLoc( px ,py )
widget:setSize( w, h, false, true )
i = i + 1
end
end
end
| 3,494
|
tommo/mock
|
-- (Public domain.)
-- This texmfcnf.lua file should contain only your personal changes from the
-- original texmfcnf.lua (for example, as chosen in the installer).
--
-- That is, if you need to make changes to texmfcnf.lua, put your custom
-- settings in this file, which is .../texlive/YYYY/texmfcnf.lua, rather than
-- the distributed file (.../texlive/YYYY/texmf-dist/web2c/texmfcnf.lua).
-- And include *only* your changed values, not a copy of the whole thing!
return {
content = {
variables = {
OSFONTDIR = "$SystemRoot/fonts//;$LOCALAPPDATA/Microsoft/Windows/Fonts//",
},
},
}
| 605
|
waqas4afzal/LatexUrduBooksTools
|
local cjson = require "cjson"
describe("operations protocol", function()
local build_request
local operation
local config
local params
local snapshot
setup(function()
snapshot = assert:snapshot()
assert:set_parameter("TableFormatLevel", -1)
build_request = require("resty.aws.request.build")
end)
teardown(function()
build_request = nil
package.loaded["resty.aws"] = nil
package.loaded["resty.aws.request.build"] = nil
snapshot:revert()
end)
before_each(function()
operation = {
name = "AssumeRole",
http = {
method = "POST",
requestUri = "/hello/{InstanceId}"
},
input = {
type = "structure",
locationName = "mainXmlElement", -- only for rest-xml protocol
xmlNamespace = { -- only for rest-xml protocol
uri = "cool-name-space"
},
required = {
"RoleArn",
"RoleSessionName"
},
members = {
-- uri location
InstanceId = {
type = "string",
location = "uri",
locationName = "InstanceId"
},
-- querystring location
UserId = {
type = "string",
location = "querystring",
locationName = "UserId"
},
-- header location
Token = {
type = "string",
location = "header",
locationName = "X-Sooper-Secret"
},
-- members without location
RoleArn = {
type = "string",
},
RoleSessionName = {
type = "string",
},
subStructure = {
locationName = "someSubStructure",
type = "structure",
members = {
hello = {
type = "string",
},
world = {
type = "string",
},
}
},
subList = {
type = "list",
member = {
type = "integer",
locationName = "listELement"
}
}
}
}
}
config = {
apiVersion = "2011-06-15",
--endpointPrefix = "sts",
signingName = "sts",
globalEndpoint = "sts.amazonaws.com",
--protocol = "query",
serviceAbbreviation = "AWS STS",
serviceFullName = "AWS Security Token Service",
serviceId = "STS",
signatureVersion = "v4",
uid = "sts-2011-06-15",
xmlNamespace = "https://sts.amazonaws.com/doc/2011-06-15/"
}
params = {
RoleArn = "hello",
RoleSessionName = "world",
InstanceId = "42",
UserId = "Arthur Dent",
Token = "towel",
subStructure = {
hello = "the default hello thinghy",
world = "the default world thinghy"
},
subList = { 1, 2 ,3}
}
end)
it("errors on a bad protocol", function()
config.protocol = "shake hands"
assert.has.error(function()
build_request(operation, config, params)
end, "Bad config, field protocol is invalid, got: 'shake hands'")
end)
it("query: params go into query table", function()
config.protocol = "query"
params.subList = nil
params.subStructure = nil
local request = build_request(operation, config, params)
assert.same({
headers = {
["X-Sooper-Secret"] = "towel",
["X-Amz-Target"] = "sts.AssumeRole",
},
method = 'POST',
path = '/hello/42',
query = {
RoleArn = 'hello',
RoleSessionName = 'world',
UserId = "Arthur Dent",
}
}, request)
end)
it("rest-json: querystring, uri, header and body params", function()
config.protocol = "rest-json"
local request = build_request(operation, config, params)
if request and request.body then
-- cannot reliably compare non-canonicalized json, so decode to Lua table
request.body = assert(cjson.decode(request.body))
end
assert.same({
headers = {
["X-Sooper-Secret"] = "towel",
["Content-Length"] = 152,
["Content-Type"] = "application/x-amz-json-1.0",
["X-Amz-Target"] = "sts.AssumeRole",
},
method = 'POST',
path = '/hello/42',
body = {
subStructure = {
hello = "the default hello thinghy",
world = "the default world thinghy",
},
subList = { 1,2,3 },
RoleArn = "hello",
RoleSessionName = "world",
},
query = {
UserId = "Arthur Dent",
}
}, request)
end)
it("json: querystring, uri, header and body params", function()
config.protocol = "json"
local request = build_request(operation, config, params)
if request and request.body then
-- cannot reliably compare non-canonicalized json, so decode to Lua table
request.body = assert(cjson.decode(request.body))
end
assert.same({
headers = {
["X-Sooper-Secret"] = "towel",
["Content-Length"] = 152,
["Content-Type"] = "application/x-amz-json-1.0",
["X-Amz-Target"] = "sts.AssumeRole",
},
method = 'POST',
path = '/hello/42',
body = {
subStructure = {
hello = "the default hello thinghy",
world = "the default world thinghy",
},
subList = { 1,2,3 },
RoleArn = "hello",
RoleSessionName = "world",
},
query = {
UserId = "Arthur Dent",
}
}, request)
end)
it("rest-xml: querystring, uri, header and body params", function()
config.protocol = "rest-xml"
local request = build_request(operation, config, params)
if request and request.body then
-- cannot reliably compare non-canonicalized json, so decode to Lua table
request.body = assert(require("pl.xml").parse(request.body))
local to_lua = function(t)
-- convert LOM to comparable Lua table
for i, v in ipairs(t) do
if type(v) == "table" and v.tag then
t[v.tag] = v
v.tag = nil
t[i] = nil
if type(v.attr) == "table" and not next(v.attr) then
-- delete empty attr table
v.attr = nil
end
end
end
end
to_lua(request.body)
to_lua(request.body.someSubStructure)
end
assert.same({
headers = {
["X-Sooper-Secret"] = "towel",
["Content-Length"] = 424,
["Content-Type"] = "application/xml",
["X-Amz-Target"] = "sts.AssumeRole",
},
method = 'POST',
path = '/hello/42',
body = {
RoleArn = {
[1] = 'hello' },
RoleSessionName = {
[1] = 'world' },
attr = {
xmlns = 'cool-name-space' },
someSubStructure = {
hello = {
[1] = 'the default hello thinghy' },
world = {
[1] = 'the default world thinghy' } },
subList = {
[1] = {
[1] = '1',
attr = {},
tag = 'listELement' },
[2] = {
[1] = '2',
attr = {},
tag = 'listELement' },
[3] = {
[1] = '3',
attr = {},
tag = 'listELement' } },
tag = 'mainXmlElement' },
query = {
UserId = "Arthur Dent",
}
}, request)
end)
pending("ec2: querystring, uri, header and body params", function()
config.protocol = "ec2"
assert.has.error(function()
build_request(operation, config, params)
end, "protocol 'ec2' not implemented yet")
end)
end)
| 7,680
|
kweedagama/lua-resty-aws
|
-- Copyright (c) 2021 <dev@brigid.jp>
-- This software is released under the MIT License.
-- https://opensource.org/licenses/mit-license.php
function love.conf(t)
t.gammacorrect = true
t.window.resizable = true
t.window.highdpi = true
end
| 246
|
brigid-jp/brigid-core
|
local moduleInfo = {
name = "customCommandsMessageSenderExternalWidget",
desc = "API helper for external widgets using the module",
author = "PepeAmpere",
date = "2017-02-13",
license = "MIT",
}
-- @description public API for anyone who wants to inject or edit custom commands via own widget
local newSendCustomMessage = {
["RegisterCustomCommand"] = function(commandDescription)
-- mandatory
if (commandDescription == nil or type(commandDescription) ~= "table") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription]") end
if (commandDescription.type == nil or type(commandDescription.type) ~= "number") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.type]") end
if (commandDescription.name == nil or type(commandDescription.name ) ~= "string") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.name]") end
if (commandDescription.cursor == nil or type(commandDescription.cursor) ~= "string") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.cursor]") end
if (commandDescription.action == nil or type(commandDescription.action) ~= "string") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.action]") end
if (commandDescription.tooltip == nil or type(commandDescription.tooltip) ~= "string") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.tooltip]") end
if (commandDescription.hidden == nil or type(commandDescription.hidden) ~= "boolean") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.hidden]") end
-- NOTA UI mandatory
if (commandDescription.UIoverride == nil or type(commandDescription.UIoverride) ~= "table") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.UIoverride]") end
-- optional for Spring
if (commandDescription.texture ~= nil and type(commandDescription.texture) ~= "string") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.texture]") end
if (commandDescription.queueing ~= nil and type(commandDescription.queueing) ~= "boolean") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.queueing]") end
if (commandDescription.disabled ~= nil and type(commandDescription.disabled) ~= "boolean") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.disabled]") end
if (commandDescription.showUnique ~= nil and type(commandDescription.showUnique) ~= "boolean") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.showUnique]") end
if (commandDescription.onlyTexture ~= nil and type(commandDescription.onlyTexture) ~= "boolean") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.onlyTexture]") end
if (commandDescription.params ~= nil and type(commandDescription.params) ~= "table") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [RegisterCustomCommand] with wrong parameter for [commandDescription.params]") end
-- optional
if (commandDescription.whitelist ~= nil and type(commandDescription.whitelist) ~= "table") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [registerCustomCommand] with wrong parameter for [commandDescription.whitelist]") end
commandDescription["subject"] = "RegisterCustomCommand"
message.SendRules(commandDescription)
end,
["DeregisterCustomCommand"] = function(commandName)
if (commandName == nil or type(commandName) ~= "string") then Spring.Echo("[" .. moduleInfo.name .. "]" .. "WARNING: Attempt to send message [DeregisterCustomCommand] with wrong parameter for [commandName]") end
local newMessage = {
subject = "DeregisterCustomCommand",
name = commandName,
}
message.SendRules(newMessage)
end,
}
-- END OF MODULE DEFINITIONS --
-- update global structures
message.AttachCustomSender(newSendCustomMessage, moduleInfo)
| 4,986
|
spring1944/submodule-customCommands
|
--[[
Copyright 2021 Todd Austin
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at:
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License.
DESCRIPTION
Library file to handle all UPnP description retrieval-related routines.
** This code significantly based on Samsung SmartThings sample LAN drivers; credit to Patrick Barrett **
--]]
local xmlparse = require 'UPnP.xmlparse'
local util = require 'UPnP.upnpcommon'
local cosock = require "cosock"
local socket = require "cosock.socket"
local http = cosock.asyncify "socket.http"
--local http = require "socket.http"
http.TIMEOUT = 3
local ltn12 = require "ltn12"
local log = require "log"
-- This function removes lines beginning with '#' which can be present in Sonos device description XML
local function scrubXML(data)
local retdata = data
local index1 = data:find('\n%s*#', 1)
if index1 then
local index2 = data:find('\n', index1 + 1, 'plaintext')
if index2 then
print (string.format('Rogue data removed: <<%s>>', string.sub(data, index1 + 1, index2 - 1)))
local part1 = string.sub(data, 1, index1)
local part2 = string.sub(data, index2 + 1)
retdata = scrubXML(part1 .. part2)
else
print ('FATEL ERROR: could not find end of line')
end
end
return retdata
end
local function getXML(targeturl)
if targeturl == nil then
log.error ('[upnp] No XML URL provided')
return nil
end
-- HTTP GET the XML File
log.debug ('[upnp] XML request URL= ', targeturl)
local responsechunks = {}
local body,status,headers = http.request{
url = targeturl,
sink = ltn12.sink.table(responsechunks)
}
local response = table.concat(responsechunks)
if status == nil then
log.warn("[upnp] HTTP request for XML seems to have timed out: ", targeturl)
return nil
end
-- vvvvvvvvvvvvvvvv TODO: errors are coming back as literal string "[string "socket"]:1239: closed"
-- instead of just "closed", so do a `find` for the error
if string.find(status, "closed") then
-- ^^^^^^^^^^^^^^^^
log.warn ("[upnp] Socket closed unexpectedly, try parsing anyway")
-- this workaround is required because device didn't send the required zero-length chunk
-- at the end of its `Text-Encoding: Chunked` HTTP message, it just closes the socket,
-- so ignore closed errors
elseif status ~= 200 then
log.warn (string.format("[upnp] HTTP XML request to %s failed with error code %s", targeturl, tostring(status)))
return nil
end
if response ~= nil then
return xmlparse.parseXML(scrubXML(response))
else
log.error ('[upnp] Nil response from description request to ' .. targeturl)
end
end
local function getServiceDescription(devobj, serviceID)
if serviceID then
local serviceinfo = util.scan_for_service(devobj, serviceID)
if serviceinfo then
if string.match(serviceinfo.SCPDURL, '^/', 1) then
targetURL = devobj.URLBase .. serviceinfo.SCPDURL
else
targetURL = devobj.URLBase .. '/' .. serviceinfo.SCPDURL
end
return getXML(targetURL)
else
log.error ('[upnp] Invalid Service ID provided for fetching service description')
end
else
log.error ('[upnp] Missing Service ID parameter for fetching service description')
end
return nil
end
return {
getXML = getXML,
getServiceDescription = getServiceDescription,
}
| 3,881
|
FreeMasen/edge_landevmon
|
-- Generated by CSharp.lua Compiler
local System = System
local SlipeClientGui
local SlipeMtaDefinitions
System.import(function (out)
SlipeClientGui = Slipe.Client.Gui
SlipeMtaDefinitions = Slipe.MtaDefinitions
end)
System.namespace("Slipe.Client.Gui", function (namespace)
-- <summary>
-- Represents a Cegui button
-- </summary>
namespace.class("Button", function (namespace)
local __ctor1__, __ctor2__
__ctor1__ = function (this, element)
SlipeClientGui.GuiElement.__ctor__(this, element)
end
-- <summary>
-- Create a new button
-- </summary>
__ctor2__ = function (this, position, dimensions, content, relative, parent)
local default = parent
if default ~= nil then
default = default:getMTAElement()
end
__ctor1__(this, SlipeMtaDefinitions.MtaClient.GuiCreateButton(position.X, position.Y, dimensions.X, dimensions.Y, content, relative, default))
end
return {
__inherits__ = function (out)
return {
out.Slipe.Client.Gui.GuiElement
}
end,
__ctor__ = {
__ctor1__,
__ctor2__
},
__metadata__ = function (out)
return {
methods = {
{ ".ctor", 0x106, __ctor1__, out.Slipe.MtaDefinitions.MtaElement },
{ ".ctor", 0x506, __ctor2__, System.Numerics.Vector2, System.Numerics.Vector2, System.String, System.Boolean, out.Slipe.Client.Gui.GuiElement }
},
class = { 0x6, System.new(out.Slipe.Shared.Elements.DefaultElementClassAttribute, 2, 12 --[[ElementType.GuiButton]]) }
}
end
}
end)
end)
| 1,620
|
DezZolation/trains
|
if not minetest.settings:get_bool("creative_mode") then
minetest.register_item(":", {
type = "none",
wield_image = "wieldhand.png",
wield_scale = {x=1,y=1,z=2.5},
tool_capabilities = {
full_punch_interval = 0.9,
max_drop_level = 0,
groupcaps = {
crumbly = {times={[2]=3.00, [3]=1.50}, uses=0, maxlevel=1},
snappy = {times={[3]=1.80}, uses=0, maxlevel=1},
oddly_breakable_by_hand = {times={[1]=3.50,[2]=2.00,[3]=0.70}, uses=0}
},
damage_groups = {fleshy=1},
}
})
end
-- Bone tools
minetest.register_tool("ws_core:knife_bone", {
description = "Bone Knife",
inventory_image = "ws_knife_bone.png",
tool_capabilities = {
full_punch_interval = 1.2,
max_drop_level=0,
groupcaps={
snappy = {times={[3]=1.00}, uses=15, maxlevel=1},
choppy = {times={[2]=4.00, [3]=3.00}, uses=8, maxlevel=1},
},
damage_groups = {fleshy=2},
},
groups = {knife = 1},
sound = {breaks = "default_tool_breaks"},
on_place = strip_bark,
})
minetest.register_tool("ws_core:hatchet_bone", {
description = "Bone Hatchet",
inventory_image = "ws_hatchet_bone.png",
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=0,
groupcaps={
choppy = {times={[2]=2.50, [3]=1.50}, uses=15, maxlevel=1},
},
damage_groups = {fleshy=2},
},
groups = {hatchet = 1},
sound = {breaks = "default_tool_breaks"},
})
-- Scrap metal tools
minetest.register_tool("ws_core:knife_scrap", {
description = "Scrap Knife",
inventory_image = "ws_knife_scrap.png",
tool_capabilities = {
full_punch_interval = 1.2,
max_drop_level=0,
groupcaps={
snappy = {times={[3]=0.70}, uses=50, maxlevel=1},
choppy = {times={[2]=3.00, [3]=2.00}, uses=25, maxlevel=1},
},
damage_groups = {fleshy=2},
},
groups = {knife = 1},
sound = {breaks = "default_tool_breaks"},
on_place = strip_bark,
})
minetest.register_tool("ws_core:hatchet_scrap", {
description = "Scrap Hatchet",
inventory_image = "ws_hatchet_scrap.png",
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=0,
groupcaps={
choppy = {times={[2]=2.00, [3]=1.00}, uses=50, maxlevel=1},
},
damage_groups = {fleshy=2},
},
groups = {hatchet = 1},
sound = {breaks = "default_tool_breaks"},
})
minetest.register_tool("ws_core:shovel_scrap", {
description = "Scrap Shovel",
inventory_image = "ws_shovel_scrap.png",
tool_capabilities = {
full_punch_interval = 1.0,
max_drop_level=0,
groupcaps={
crumbly = {times={[2]=2.00, [3]=1.00}, uses=50, maxlevel=1},
},
damage_groups = {fleshy=2},
},
groups = {shovel = 1},
sound = {breaks = "default_tool_breaks"},
})
minetest.register_tool("ws_core:pick_scrap", {
description = "Scrap Pickaxe",
inventory_image = "ws_pickaxe_scrap.png",
tool_capabilities = {
full_punch_interval = 1.2,
max_drop_level=0,
groupcaps={
cracky = {times={[2]=4.00, [3]=2.50}, uses=30, maxlevel=1},
},
damage_groups = {fleshy=2},
},
groups = {pickaxe = 1},
sound = {breaks = "default_tool_breaks"},
})
| 3,092
|
oilboi/WasteLands_Survival
|
ChatTypeInfo = {}
ChatTypeInfo.SYSTEM = {}
-- MessageFrame
DEFAULT_CHAT_FRAME = {}
function DEFAULT_CHAT_FRAME:AddMessage(msg)
print(msg)
end
function DEFAULT_CHAT_FRAME:SetMaxLines()
end
-- Lua API
unpack = table.unpack
tinsert = table.insert
format = string.format
-- why is WoW so backwards
function string.split(delim, input)
delim = delim or "%s"
local t = {}
for str in string.gmatch(input, "[^"..delim.."]+") do
table.insert(t, str)
end
return unpack(t)
end
-- SharedXML\Mixin.lua
function Mixin(object, ...)
for i = 1, select("#", ...) do
local mixin = select(i, ...)
for k, v in pairs(mixin) do
object[k] = v
end
end
return object
end
-- where ... are the mixins to mixin
function CreateFromMixins(...)
return Mixin({}, ...)
end
Enum = {
-- CurrencyConstantsDocumentation.lua CurrencyConsts
PlayerCurrencyFlagsDbFlags = {
IgnoreMaxQtyOnload = 1,
Reuse1 = 2,
InBackpack = 4,
UnusedInUI = 8,
Reuse2 = 16,
}
}
| 961
|
Ketho/WowpediaDoc
|
object_tangible_quest_imperial_itp_kaja_spy_data_terminal = object_tangible_quest_imperial_shared_itp_kaja_spy_data_terminal:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_imperial_itp_kaja_spy_data_terminal, "object/tangible/quest/imperial/itp_kaja_spy_data_terminal.iff")
| 287
|
V-Fib/FlurryClone
|
local func = function(p, uv)
local before = os.time()
local async
async = uv.new_async(function(a, b, c)
p('in async notify callback')
p(a, b, c)
uv.close(async)
end)
local args = {500, 'string', nil, false, 5, "helloworld", async}
local unpack = unpack or table.unpack
uv.new_thread(function(num, s, null, bool, five, hw, asy)
local uv2 = require 'luv'
uv2.async_send(asy, 'a', true, 250)
uv2.sleep(1000)
end, unpack(args)):join()
local elapsed = (os.time() - before) * 1000
assert(elapsed >= 1000, "elapsed should be at least delay ")
end
func(print, vim.loop)
| 608
|
Keith994/navigator.lua
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.