content stringlengths 5 1.05M |
|---|
object_tangible_collection_rare_pistol_kashyyyk_stalker = object_tangible_collection_shared_rare_pistol_kashyyyk_stalker:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_rare_pistol_kashyyyk_stalker, "object/tangible/collection/rare_pistol_kashyyyk_stalker.iff") |
--[[================================
Advanced includes
This file for shared side!
Made by SkyAngeLoL
================================]]--
--[[=====
includeCL("lua/myaddon/client_file.lua") - for client side
includeSH("lua/myaddon/shared_file.lua") - for shared sides
includeSV("lua/myaddon/server_file.lua") - for server side
includeRSFolder("lua/myaddon") - loading all files from folder with tags "cl_" , "sv_" and other...
=====]]--
fastincludes = {}
fastincludes.Debug = false
MsgC(Color(0, 255, 0, 255), "[GLua+] ") MsgC(Color(200, 200, 200), "fastincludes.lua\n")
function fastincludes.DebugPrint(txt, tab)
if not fastincludes.Debug then return end
print("[Debug]"..string.rep("\t", tab or 1), txt)
end
--[[=================
Single file
=================]]--
function fastincludes.includeCL(file, time_dl)
if SERVER then
AddCSLuaFile(file)
else --if CLIENT then
if time_dl and time_dl ~= 0 then
timer.Simple(time_dl, function()
include(file)
end)
else
include(file)
end
end
fastincludes.DebugPrint("To client - "..file) // For printing on both sides
end
function fastincludes.includeSH(file, time_dl)
if SERVER then
AddCSLuaFile(file)
end
if time_dl and time_dl ~= 0 then
timer.Simple(time_dl, function()
include(file)
end)
else
include(file)
end
fastincludes.DebugPrint("To shared - "..file)
end
function fastincludes.includeSV(file, time_dl)
if SERVER then
if time_dl and time_dl ~= 0 then
timer.Simple(time_dl, function()
include(file)
end)
else
include(file)
end
fastincludes.DebugPrint("To server - "..file)
end
end
--[[=============
Folders
=============]]--
function fastincludes.includeCLFolder(folder, zone, r)
local Files, Folders = file.Find(folder.."/*.lua", zone or "LUA")
if #Files == 0 then return false, "folder is empty" end
fastincludes.DebugPrint("Find "..#Files.." files in client folder "..folder, 0)
for k, v in pairs(Files) do
fastincludes.includeCL(folder.."/"..v)
end
if r then
for k, v in pairs(Folders) do
fastincludes.includeCLFolder(folder.."/"..v, zone, true)
end
end
return true, "true", Files
end
function fastincludes.includeSHFolder(folder, zone, r)
local Files, Folders = file.Find(folder.."/*.lua", zone or "LUA")
if #Files == 0 then return false, "folder is empty" end
fastincludes.DebugPrint("Find "..#Files.." files in shared folder "..folder, 0)
for k, v in pairs(Files) do
fastincludes.includeSH(folder.."/"..v)
end
if r then
for k, v in pairs(Folders) do
fastincludes.includeSHFolder(folder.."/"..v, zone, true)
end
end
return true, "true", Files
end
function fastincludes.includeSVFolder(folder, zone, r)
local Files, Folders = file.Find(folder.."/*.lua", zone or "LUA")
if #Files == 0 then return false, "folder is empty" end
fastincludes.DebugPrint("Find "..#Files.." files in server folder "..folder, 0)
for k, v in pairs(Files) do
fastincludes.includeSV(folder.."/"..v)
end
if r then
for k, v in pairs(Folders) do
fastincludes.includeSVFolder(folder.."/"..v, zone, true)
end
end
return true, "true", Files
end
function fastincludes.includeRSFolder(folder, zone, r)
local Files, Folders = file.Find(folder.."/*.lua", zone or "LUA")
if #Files == 0 then return false, "folder is empty" end
fastincludes.DebugPrint("Find "..#Files.." files in folder "..folder, 0)
for k, v in pairs(Files) do
if string.Left(v, 3) == "cl_" then
fastincludes.includeCL(folder.."/"..v)
elseif string.Left(v, 3) == "sv_" then
fastincludes.includeSV(folder.."/"..v)
else
fastincludes.includeSH(folder.."/"..v)
end
end
if r then
for k, v in pairs(Folders) do
fastincludes.includeRSFolder(folder.."/"..v, zone, true)
end
end
return true, "true", Files
end
--[[=============
Globals
=============]]
includeCL = fastincludes.includeCL
includeSH = fastincludes.includeSH
includeSV = fastincludes.includeSV
includeCLFolder = fastincludes.includeCLFolder
includeSHFolder = fastincludes.includeSHFolder
includeSVFolder = fastincludes.includeSVFolder
includeRSFolder = fastincludes.includeRSFolder
|
--[[By: @V3N0M_Z]]
--Variables initialization
local userInputService = game:GetService("UserInputService")
local chain = require(script.Parent:WaitForChild("Chain"))
local mouse = plugin:GetMouse()
local activeChain
--Display initialization
local coreGui = game:GetService("CoreGui")
if coreGui:FindFirstChild("CMD+") then
coreGui:FindFirstChild("CMD+"):Destroy()
end
local pluginDisplay = coreGui:FindFirstChild("CMD+") or Instance.new("ScreenGui")
pluginDisplay.Parent = coreGui
pluginDisplay.Name = "CMD+"
local imposterFrame = pluginDisplay:FindFirstChild("Imposter") or Instance.new("Frame")
imposterFrame.Parent = pluginDisplay
imposterFrame.Name = "Imposter"
imposterFrame.BackgroundTransparency = 1
imposterFrame.Size = UDim2.new(1, 0, 1, 0)
--Toolbar initialization
local pluginToolbar = plugin:CreateToolbar("CMD+")
local primaryButton = pluginToolbar:CreateButton("CMD+", " ", "rbxassetid://7737708078", "")
--Plugin action initialization
local pluginAction = plugin:CreatePluginAction("CMD+", "CMD+", "Open CMD+", "rbxassetid://7737708078", true)
local function createChain(cmd)
if activeChain then
activeChain:Dispose()
return
end
if activeChain then return end
activeChain = true
plugin:Activate(true)
primaryButton:SetActive(true)
activeChain = chain.new(plugin, pluginDisplay, cmd)
activeChain._provocations.Destroyed.OnInvoke = function()
plugin:Deactivate()
primaryButton:SetActive(false)
activeChain = nil
end
end
--Events
pluginAction.Triggered:Connect(createChain)
primaryButton.Click:Connect(createChain)
--Key shorcuts
local commands = {}
local function getCommands()
for _, command in ipairs(script.Parent:WaitForChild("Commands"):GetChildren()) do
command = require(command)
if command.metadata.shortcut then
commands[command.metadata.id] = command
end
end
if game:GetService("ServerStorage"):FindFirstChild("CMD+") then
for _, command in ipairs(game:GetService("ServerStorage")["CMD+"]:GetChildren()) do
command = require(command)
if command.metadata.shortcut then
commands[command.metadata.id] = command
end
end
end
end
getCommands()
userInputService.InputBegan:Connect(function(input)
local keysPressed = userInputService:GetKeysPressed()
if not activeChain and keysPressed then
for command, data in pairs(commands) do
if #keysPressed == #data.metadata.shortcut then
local equal = true
for _, key in ipairs(keysPressed) do
if not table.find(data.metadata.shortcut, key.KeyCode) then
equal = false
end
end
if equal then
return createChain(command)
end
end
end
end
end)
local refreshButton = pluginToolbar:CreateButton("CMD+:Refresh", " ", "rbxassetid://7974159081", "")
refreshButton.Click:Connect(function()
commands = {}
getCommands()
end) |
local Arena, super = Class(Object)
function Arena:init(x, y, shape)
super:init(self, x, y)
self:setOrigin(0.5, 0.5)
self.color = {0, 0.75, 0}
self.bg_color = {0, 0, 0}
self.x = math.floor(self.x)
self.y = math.floor(self.y)
self.collider = ColliderGroup(self)
self.line_width = 4 -- must call setShape again if u change this
self:setShape(shape or {{0, 0}, {142, 0}, {142, 142}, {0, 142}})
self.sprite = ArenaSprite(self)
self:addChild(self.sprite)
self.mask = ArenaMask(1, 0, 0, self)
self:addChild(self.mask)
end
function Arena:setSize(width, height)
self:setShape{{0, 0}, {width, 0}, {width, height}, {0, height}}
end
function Arena:setShape(shape)
self.shape = Utils.copy(shape, true)
self.processed_shape = Utils.copy(shape, true)
local min_x, min_y, max_x, max_y
for _,point in ipairs(self.shape) do
min_x, min_y = math.min(min_x or point[1], point[1]), math.min(min_y or point[2], point[2])
max_x, max_y = math.max(max_x or point[1], point[1]), math.max(max_y or point[2], point[2])
end
for _,point in ipairs(self.shape) do
point[1] = point[1] - min_x
point[2] = point[2] - min_y
end
self.width = max_x - min_x
self.height = max_y - min_y
self.processed_width = self.width
self.processed_height = self.height
self.left = math.floor(self.x - self.width/2)
self.right = math.floor(self.x + self.width/2)
self.top = math.floor(self.y - self.height/2)
self.bottom = math.floor(self.y + self.height/2)
self.triangles = love.math.triangulate(Utils.unpackPolygon(self.shape))
self.border_line = {Utils.unpackPolygon(Utils.getPolygonOffset(self.shape, self.line_width/2))}
local edges = Utils.getPolygonEdges(self.shape)
self.clockwise = Utils.isPolygonClockwise(edges)
self.area_collider = PolygonCollider(self, Utils.copy(shape, true))
self.collider.colliders = {}
for _,v in ipairs(edges) do
table.insert(self.collider.colliders, LineCollider(self, v[1][1], v[1][2], v[2][1], v[2][2]))
end
end
function Arena:setBackgroundColor(r, g, b, a)
self.bg_color = {r, g, b, a or 1}
end
function Arena:getBackgroundColor()
return self.bg_color
end
function Arena:getCenter()
return self:getRelativePos(self.width/2, self.height/2)
end
function Arena:getTopLeft() return self:getRelativePos(0, 0) end
function Arena:getTopRight() return self:getRelativePos(self.width, 0) end
function Arena:getBottomLeft() return self:getRelativePos(0, self.height) end
function Arena:getBottomRight() return self:getRelativePos(self.width, self.height) end
function Arena:getLeft() local x, y = self:getTopLeft(); return x end
function Arena:getRight() local x, y = self:getBottomRight(); return x end
function Arena:getTop() local x, y = self:getTopLeft(); return y end
function Arena:getBottom() local x, y = self:getBottomRight(); return y end
function Arena:onAdd(parent)
self.sprite:setScale(0, 0)
self.sprite.alpha = 0.5
self.sprite.rotation = math.pi
local center_x, center_y = self:getCenter()
local afterimage_timer = 0
local afterimage_count = 0
Game.battle.timer:during(15/30, function(dt)
afterimage_timer = Utils.approach(afterimage_timer, 15, DTMULT)
local real_progress = afterimage_timer / 15
self.sprite:setScale(real_progress, real_progress)
self.sprite.alpha = 0.5 + (0.5 * real_progress)
self.sprite.rotation = (math.pi) * (1 - real_progress)
while afterimage_count < math.floor(afterimage_timer) do
afterimage_count = afterimage_count + 1
local progress = afterimage_count / 15
local afterimg = ArenaSprite(self, center_x, center_y)
afterimg:setOrigin(0.5, 0.5)
afterimg:setScale(progress, progress)
afterimg:fadeOutAndRemove()
afterimg.background = false
afterimg.alpha = 0.6 - (0.5 * progress)
afterimg.rotation = (math.pi) * (1 - progress)
parent:addChild(afterimg)
afterimg:setLayer(self.layer + (1 - progress))
end
end, function()
self.sprite:setScale(1)
self.sprite.alpha = 1
self.sprite.rotation = 0
end)
end
function Arena:onRemove(parent)
local orig_sprite = ArenaSprite(self, self:getCenter())
orig_sprite:setOrigin(0.5, 0.5)
parent:addChild(orig_sprite)
orig_sprite:setLayer(self.layer)
local afterimage_timer = 0
local afterimage_count = 0
Game.battle.timer:during(15/30, function(dt)
afterimage_timer = Utils.approach(afterimage_timer, 15, DTMULT)
local real_progress = 1 - (afterimage_timer / 15)
orig_sprite:setScale(real_progress, real_progress)
orig_sprite.alpha = 0.5 + (0.5 * real_progress)
orig_sprite.rotation = (math.pi) * (1 - real_progress)
while afterimage_count < math.floor(afterimage_timer) do
afterimage_count = afterimage_count + 1
local progress = 1 - (afterimage_count / 15)
local afterimg = ArenaSprite(self, orig_sprite.x, orig_sprite.y)
afterimg:setOrigin(0.5, 0.5)
afterimg:setScale(progress, progress)
afterimg:fadeOutAndRemove()
afterimg.background = false
afterimg.alpha = 0.6 - (0.5 * progress)
afterimg.rotation = (math.pi) * (1 - progress)
parent:addChild(afterimg)
afterimg:setLayer(self.layer + (1 - progress))
end
end, function()
orig_sprite:remove()
end)
end
function Arena:update(dt)
if not Utils.equal(self.processed_shape, self.shape, true) then
self:setShape(self.shape)
elseif self.processed_width ~= self.width or self.processed_height ~= self.height then
self:setSize(self.width, self.height)
end
super:update(self, dt)
local soul = Game.battle.soul
if soul and Game.battle.soul.collidable then
Object.startCache()
local angle_diff = self.clockwise and -(math.pi/2) or (math.pi/2)
for _,line in ipairs(self.collider.colliders) do
local angle
while soul:collidesWith(line) do
if not angle then
local x1, y1 = self:getRelativePos(line.x, line.y, Game.battle)
local x2, y2 = self:getRelativePos(line.x2, line.y2, Game.battle)
angle = Utils.angle(x1, y1, x2, y2)
end
Object.uncache(soul)
soul:setPosition(
soul.x + (math.cos(angle + angle_diff)),
soul.y + (math.sin(angle + angle_diff))
)
end
end
Object.endCache()
end
end
function Arena:drawMask()
love.graphics.push()
self.sprite:preDraw()
self.sprite:drawBackground()
self.sprite:postDraw()
love.graphics.pop()
end
function Arena:draw()
super:draw(self)
if DEBUG_RENDER and self.collider then
self.collider:draw(0, 0, 1)
end
end
return Arena |
function error_handler(err_msg)
err_msg = debug.traceback(err_msg)
log_error(err_msg)
end
|
local config = vim.o
local colors = require('colors')
local vars = require('vars')
local default_theme = { fg = colors.secondary, bg = colors.bg1 }
require('lualine').setup {
options = {
icons_enabled = true,
theme = {
normal = {
a = { fg = colors.primary, bg = colors.bg1 },
b = default_theme,
c = default_theme,
x = default_theme,
y = default_theme,
z = default_theme
},
inactive = {
a = default_theme,
b = default_theme,
c = default_theme,
x = default_theme,
y = default_theme,
z = default_theme
}
},
component_separators = { left = '', right = '' },
section_separators = { left = '', right = '' },
disabled_filetypes = { 'NvimTree' },
always_divide_middle = true
},
sections = {
lualine_a = { { 'mode' } },
lualine_b = {
{ 'branch', icon = '' },
{
'diagnostics',
colored = false,
always_visible = true,
sources = { 'nvim_lsp' },
sections = { 'error', 'warn' },
symbols = {
error = vars.signs.error .. ' ',
warn = vars.signs.warn .. ' '
}
}
},
lualine_c = {},
lualine_x = {},
lualine_y = {},
lualine_z = {
{ 'location' },
function()
local mode = config.expandtab == true and 'Space' or 'Tab'
local count = config.expandtab == true and config.shiftwidth or
config.tabstop
return mode .. ':' .. count
end,
{ 'encoding' },
{ 'fileformat', icons_enabled = false },
{ 'filetype', colored = false }
}
},
inactive_sections = {
lualine_a = {},
lualine_b = {},
lualine_c = {},
lualine_x = {},
lualine_y = {},
lualine_z = {}
},
tabline = {}
}
|
numb = math.random(9);
broj = numb * 10^(ITEM + 2)
if (ITEM == 1) then
broj = broj + 1
end
if (ITEM == 2) then
broj = broj - numb * 10^ITEM
end
if (ITEM == 3) then
broj = broj - 1
end
if (ITEM == 5) then
broj = numb * (10^(ITEM - 1) - 10)
end
prethodnik = broj - 1
sledbenik = broj + 1
|
local MaskedLogSoftMax, parent = torch.class('nn.MaskedLogSoftMax', 'nn.Module')
function MaskedLogSoftMax:__init(dimension)
parent.__init(self)
self.dimension = dimension
self.gradInput = {self.gradInput, self.gradInput.new()}
self.soft_modules = {}
end
function MaskedLogSoftMax:updateOutput(input)
local t_raw = input[1]
local sizes = input[2]
assert(t_raw:dim() == 3)
assert(t_raw:size(1) == sizes:size(1))
local sizes_max = sizes:max()
local t = t_raw:size(3) == sizes_max and t_raw or t_raw:view(t_raw:size(1), -1, sizes_max)
self.output:resizeAs(t):zero()
for i = 1, t:size(1) do
local soft_module = self.soft_modules[i]
if soft_module == nil then
self.soft_modules[i] = nn.LogSoftMax():cuda()
soft_module = self.soft_modules[i]
end
if sizes[i] ~= 0 then
local output = soft_module:forward(t[{i, {}, {1, sizes[i]}}])
self.output[{i, {}, {1, sizes[i]}}]:copy( output )
end
end
return self.output
end
function MaskedLogSoftMax:updateGradInput(input, gradOutput)
local t_raw = input[1]
local sizes = input[2]
local sizes_max = sizes:max()
local t = t_raw:size(3) == sizes_max and t_raw or t_raw:view(t_raw:size(1), -1, sizes_max)
self.gradInput[1]:resizeAs(t):zero()
self.gradInput[2]:resize(sizes:size()):zero()
for i = 1, t:size(1) do
local soft_module = self.soft_modules[i]
if sizes[i] ~= 0 then
local grad = soft_module:backward(t[{i, {}, {1, sizes[i]}}], gradOutput[{i, {}, {1, sizes[i]}}])
self.gradInput[1][{i, {}, {1, sizes[i]}}]:copy(grad)
end
end
if t_raw:size(3) ~= sizes_max then self.gradInput[1]:resizeAs(t_raw) end
return self.gradInput
end
function MaskedLogSoftMax:clearState()
self.gradInput[1]:set()
self.gradInput[2]:set()
self.output:set()
return self
end
|
local VoiceMat = surface.GetTextureID("voice/speaker4")
local VoiceMat2 = surface.GetTextureID("gui/gradient_up")
local VoiceEna = true
local insert = table.insert
local Remove = table.remove
local min = math.min
local x = ScrW()-310
function GM:PlayerStartVoice( ply )
ply.Rec = {}
ply.Talking = true
ply.LastTalkStart = CurTime()
end
function GM:PlayerEndVoice( ply )
ply.Rec = {}
ply.Talking = nil
end
local Time = CurTime()
hook.Add("Tick","RecVoice",function()
if (Time < CurTime()) then
for k,v in pairs( player.GetAll() ) do
if (v.Talking and v.LastTalkStart and v.LastTalkStart < CurTime()-0.1) then
local V = min(1,v:VoiceVolume())
insert(v.Rec,1,V)
if (#v.Rec >= 25) then
Remove(v.Rec,#v.Rec)
end
end
end
Time = CurTime()+0.02
end
end)
hook.Add("HUDPaint","_VoiceChatDraw",function()
local D = 0
for k,v in pairs( player.GetAll() ) do
if (v.Talking and v.LastTalkStart and v.LastTalkStart < CurTime()-0.1) then
local H = 400 + 50*D
D = D+1
DrawRect( x, H, 300, 45, MAIN_BLACKCOLOR )
for k,v in pairs(v.Rec) do
DrawTexturedRect( x+150+(150/25)*(k-1), H+45-40*v, 4, 40*v, MAIN_GREENCOLOR,VoiceMat2 )
DrawTexturedRect( x+150-(150/25)*k, H+45-40*v, 4, 40*v, MAIN_GREENCOLOR,VoiceMat2 )
end
DrawOutlinedRect( x, H, 300, 45, MAIN_TOTALBLACKCOLOR )
DrawTexturedRect( x+270, H+14, 16, 16, MAIN_TEXTCOLOR, VoiceMat )
DrawText( v:Nick(), "MZS_Font26", x+14, H+9, MAIN_TEXTCOLOR )
end
end
end) |
local M = {}
function M.config()
local ok, neorg = pcall(function()
return require("neorg")
end)
if not ok then
return
end
neorg.setup({
load = {
["core.defaults"] = {},
["core.keybinds"] = {},
["core.norg.concealer"] = {
config = {
icons = {
todo = {
enabled = true, -- Conceal TODO items
done = {
enabled = true, -- Conceal whenever an item is marked as done
icon = " ",
},
pending = {
enabled = true, -- Conceal whenever an item is marked as pending
icon = " ",
},
undone = {
enabled = true, -- Conceal whenever an item is marked as undone
icon = " ",
},
},
quote = {
enabled = true, -- Conceal quotes
icon = "∣",
},
heading = {
enabled = true, -- Enable beautified headings
-- Define icons for all the different heading levels
level_1 = {
enabled = true,
icon = "◉",
},
level_2 = {
enabled = true,
icon = "○",
},
level_3 = {
enabled = true,
icon = "✿",
},
level_4 = {
enabled = true,
icon = "•",
},
},
marker = {
enabled = true, -- Enable the beautification of markers
icon = "",
},
},
},
},
["core.integrations.treesitter"] = {
config = {
highlights = {
tag = {
-- The + tells neorg to link to an existing hl
begin = "+TSKeyword",
["end"] = "+TSKeyword",
name = "+TSKeyword",
parameters = "+TSType",
content = "+Normal",
comment = "+TSComment",
},
heading = {
["1"] = "+TSAttribute",
["2"] = "+TSLabel",
["3"] = "+TSMath",
["4"] = "+TSString",
},
error = "+TSError",
marker = { [""] = "+TSLabel", title = "+Normal" },
drawer = {
[""] = "+TSPunctDelimiter",
title = "+TSMath",
content = "+Normal",
},
escapesequence = "+TSType",
todoitem = {
[""] = "+TSCharacter",
pendingmark = "+TSNamespace",
donemark = "+TSMethod",
},
unorderedlist = "+TSPunctDelimiter",
quote = { [""] = "+TSPunctDelimiter", content = "+TSPunctDelimiter" },
},
},
},
["core.norg.dirman"] = { config = { workspaces = { notes = "~/neorg" } } },
["core.integrations.telescope"] = {},
},
})
end
return M
|
local g_VoteToRoom = {}
local g_RoomToVote = {}
local ISSUE_7364 = true
addEvent("onGameStop")
addEvent("onRoomMapStart")
local function onVoteFinish(optName)
local room = g_VoteToRoom[source]
if(not room) then return end
local mapHandle
if(optName == "Redo") then
mapHandle = getRoomMap(room)
end
local fMap = findMap(optName, false)
if fMap then
mapHandle = fMap
end
if(not mapHandle) then
local mapsList = getMapsList()
mapHandle = mapsList[math.random(1, #mapsList)]
end
startRoomMap(room, mapHandle)
end
local function onVoteDestroy()
local room = g_VoteToRoom[source]
if(not room) then return end
g_VoteToRoom[source] = nil
g_RoomToVote[room] = nil
--outputChatBox("onVoteDestroy")
end
function startVote(room)
if(g_RoomToVote[room]) then return end
local mapsTag = tostring(getElementData(room,"mapPatterns"))
local mapsByTag = findMapsByNameTag(mapsTag)
local opts = {}
if table.size(mapsByTag) <= 8 then
for i,map in pairs(mapsByTag) do
table.insert(opts,{getMapInfo(map,"name")})
end
else
local isSelect = {}
local totalMaps = table.size(mapsByTag)
repeat
local c = math.random(1,totalMaps)
if not isSelect[c] then
table.insert(opts,{getMapInfo(mapsByTag[c],"name")})
isSelect[c] = true
end
until #opts > 7
end
table.insert(opts,{"Redo"})
local info = {
title = "Select next map",
visibleTo = room}
local vote = createVote(info, opts)
g_RoomToVote[room] = vote
g_VoteToRoom[vote] = room
if(not ISSUE_7364) then
addEventHandler("onVoteFinish", vote, onVoteFinish, false) -- issue #7364
addEventHandler("onElementDestroy", vote, onVoteDestroy, false) -- issue #7364
end
end
local function onGameStop(reason)
local id = getElementID(source)
--outputDebugString("Game stop: "..id, 3)
if(reason ~= "mapchange") then
startVote(source)
end
end
local function onPlayerChangeRoom(room)
if(not room) then return end
local raceState = getElementData(room, "race.state")
if(getRoomPlayersCount(room) == 1) then
startVote(room)
end
end
local function onRoomMapStart()
local vote = g_RoomToVote[source]
if(vote) then
destroyElement(vote)
end
end
local function cleanupVoteBetweenMaps()
--outputChatBox("cleanupVoteBetweenMaps")
for room, vote in pairs(g_RoomToVote) do
destroyElement(vote)
end
--outputChatBox("cleanupVoteBetweenMaps end")
end
function initVoteBetweenMaps()
addEventHandler("onGameStop", g_Root, onGameStop)
addEventHandler("onPlayerChangeRoom", g_Root, onPlayerChangeRoom)
addEventHandler("onRoomMapStart", g_Root, onRoomMapStart)
addEventHandler("onResourceStop", g_Root, cleanupVoteBetweenMaps)
-- issue #7364
if(ISSUE_7364) then
addEventHandler("onVoteFinish", g_Root, onVoteFinish)
addEventHandler("onElementDestroy", g_Root, onVoteDestroy)
end
local rooms = getRooms()
for i, room in ipairs(rooms) do
local raceState = getElementData(room, "race.state")
if((raceState == "idle" or raceState == "stopped") and getRoomPlayersCount(room) > 0) then
startVote(room)
end
end
end
function table.size(tab)
local length = 0
for _ in pairs(tab) do length = length + 1 end
return length
end
|
Config = {
laptopal = vector3(1272.447, -1736.32, 51.629), -- Laptop Alma
} |
local SPUtil = require(game.ReplicatedStorage.Shared.SPUtil)
local SPDict = require(game.ReplicatedStorage.Shared.SPDict)
local SPUISystem = require(game.ReplicatedStorage.Shared.SPUISystem)
local CurveUtil = require(game.ReplicatedStorage.Shared.CurveUtil)
local CycleElementBase = require(game.ReplicatedStorage.Menu.CycleElementBase)
local DebugOut = require(game.ReplicatedStorage.Local.DebugOut)
local SPUIChildButton = {}
function SPUIChildButton:new(_uichild,_spui,_callback)
local self = CycleElementBase:new()
local _part = _uichild:get_child_part()
function self:get_part() return _part end
local _selected = false
local _selected_anim_t = SPUtil:rand_rangef(0,3.14*2)
local _trigger_scale_offset = 0
local _raise_trigger_element = false
local _enabled_anim_updatefn = nil
local _enabled_anim_t = 1
local _enabled = true
function self:cons()
self:layout()
end
function self:layout()
_uichild:layout()
self._native_size = _part.Size
self._size = self._native_size
end
function self:set_enabled_anim_updatefn(enabled_anim_updatefn)
_enabled_anim_updatefn = enabled_anim_updatefn
return self
end
function self:set_enabled(val,imm)
if val == false then
_selected = false
if imm == true then
_enabled_anim_t = 0
end
end
_enabled = val
return self
end
function self:set_visible(val)
if val == true then
_part.SurfaceGui.Enabled = true
else
_part.SurfaceGui.Enabled = false
end
self:set_enabled(val)
return self
end
local _rotation_amplitude = 2.5
function self:set_selected_rotation_amplitude(val)
_rotation_amplitude = val
return self
end
local _tar_scale = 1.25
function self:set_selected_tar_scale(val)
_tar_scale = val
return self
end
local _has_passive_anim = false
function self:set_passive_anim()
_has_passive_anim = true
return self
end
local _scale = 1
function self:set_scale(val)
_scale = val
return self
end
local __last_enabled_anim_t = -1
--[[Override--]] function self:update(dt_scale, _local_services)
local tar_scale = _scale
local tar_rotation = 0
if _selected == true then
tar_scale = tar_scale * _tar_scale
tar_rotation = math.sin(_selected_anim_t) * _rotation_amplitude
_selected_anim_t = CurveUtil:IncrementWrap(_selected_anim_t, 0.05 * dt_scale, math.pi * 2)
elseif _has_passive_anim == true then
tar_rotation = math.sin(_selected_anim_t) * _rotation_amplitude * 0.5
_selected_anim_t = CurveUtil:IncrementWrap(_selected_anim_t, 0.05 * dt_scale, math.pi * 2)
end
tar_scale = tar_scale + _trigger_scale_offset
_trigger_scale_offset = CurveUtil:Expt(
_trigger_scale_offset,
0,
CurveUtil:NormalizedDefaultExptValueInSeconds(0.5),
dt_scale
)
_uichild:set_scale(CurveUtil:Expt(
_uichild:get_scale(),
tar_scale,
CurveUtil:NormalizedDefaultExptValueInSeconds(0.5),
dt_scale
))
_uichild:set_rotation_z(CurveUtil:Expt(
_uichild:get_rotation().Z,
tar_rotation,
CurveUtil:NormalizedDefaultExptValueInSeconds(0.5),
dt_scale
))
if _enabled == true then
_enabled_anim_t = CurveUtil:Expt(_enabled_anim_t,1,CurveUtil:exptvsec(0.5),dt_scale)
else
_enabled_anim_t = CurveUtil:Expt(_enabled_anim_t,0,CurveUtil:exptvsec(0.5),dt_scale)
end
if __last_enabled_anim_t ~= _enabled_anim_t and _enabled_anim_updatefn ~= nil then
_enabled_anim_updatefn(_enabled, _enabled_anim_t)
end
__last_enabled_anim_t = _enabled_anim_t
self:layout()
end
--[[Override--]] function self:get_selected()
return _selected
end
--[[Override--]] function self:trigger_element(_local_services)
_local_services._input:clear_just_pressed_keys()
_callback()
_trigger_scale_offset = _trigger_scale_offset + 1
_raise_trigger_element = true
end
function self:did_raise_trigger_element()
local rtv = _raise_trigger_element
_raise_trigger_element = false
return rtv
end
--[[Override--]] function self:is_selectable()
return _enabled
end
--[[Override--]] function self:set_selected(_local_services, selected)
_selected = selected
end
--[[Override--]] function self:get_native_size()
return self._native_size
end
--[[Override--]] function self:get_size()
return self._size
end
--[[Override--]] function self:set_size(size)
self._size = size
_part.Size = Vector3.new(size.X,size.Y,0.2)
end
--[[Override--]] function self:get_pos()
return _part.Position
end
--[[Override--]] function self:get_sgui()
DebugOut:errf("SPUIButton get_sgui not implemented")
return nil
end
local _alpha = 1
function self:set_alpha(val)
_alpha = val
return self
end
function self:get_alpha() return _alpha end
self:cons()
return self
end
return SPUIChildButton
|
header_arr = { "Декадна", "јединица", "Дати", "број", "Заокругљени", " број" }
|
--
-- Copyright (c) 2012-2020 Daniele Bartolini and individual contributors.
-- License: https://github.com/dbartolini/crown/blob/master/LICENSE
--
local BULLET_DIR = (CROWN_DIR .. "3rdparty/bullet3/")
project "bullet"
kind "StaticLib"
language "C++"
includedirs {
BULLET_DIR .. "src",
}
configuration {}
defines {
"BT_THREADSAFE=0",
"BT_USE_TBB=0",
"BT_USE_PPL=0",
"BT_USE_OPENMP=0",
"B3_DBVT_BP_SORTPAIRS=0",
"DBVT_BP_SORTPAIRS=0",
}
configuration { "linux-*" }
buildoptions {
"-Wno-unused-parameter",
"-Wno-unused-variable",
"-Wno-unused-but-set-variable",
"-Wno-unused-function",
"-Wno-sign-compare",
"-Wno-type-limits",
"-Wno-parentheses",
"-Wno-maybe-uninitialized",
}
buildoptions_cpp {
"-Wno-reorder",
}
configuration { "vs*" }
buildoptions {
"/wd4267",
"/wd4244",
"/wd4305",
}
configuration {}
files {
BULLET_DIR .. "src/BulletCollision/**.cpp",
BULLET_DIR .. "src/BulletDynamics/**.cpp",
BULLET_DIR .. "src/BulletSoftBody/*.cpp",
BULLET_DIR .. "src/LinearMath/**.cpp",
}
removefiles {
BULLET_DIR .. "src/BulletCollision/Gimpact/**.h",
BULLET_DIR .. "src/BulletCollision/Gimpact/**.cpp",
BULLET_DIR .. "src/BulletDynamics/Vehicle/**.h",
BULLET_DIR .. "src/BulletDynamics/Vehicle/**.cpp",
BULLET_DIR .. "src/BulletSoftBody/**.h",
BULLET_DIR .. "src/BulletSoftBody/**.cpp",
}
configuration {}
|
local assert = require "luassert"
local Petrinet = require "petrinet"
describe ("Petri nets", function ()
it ("can be created", function ()
local petrinet = Petrinet ()
assert.are.equal (getmetatable (petrinet), Petrinet)
end)
it ("can create a place with an implicit marking", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place {}
assert.are.equal (getmetatable (petrinet.p), Petrinet.Place)
assert.are.equal (petrinet.p.marking, 0)
end)
it ("can create a place with an explicit marking", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place { marking = 5 }
assert.are.equal (getmetatable (petrinet.p), Petrinet.Place)
assert.are.equal (petrinet.p.marking, 5)
end)
it ("can iterate over its places", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place { marking = 5 }
petrinet.q = petrinet:place { marking = 0 }
local places = {}
for _, place in petrinet:places () do
assert.are.equal (getmetatable (place), Petrinet.Place)
places [place] = true
end
assert.are.same (places, {
[petrinet.p] = true,
[petrinet.q] = true,
})
end)
it ("can create a transition", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place {}
petrinet.q = petrinet:place {}
petrinet.t = petrinet:transition {
petrinet.p - 1,
petrinet.q + 1,
}
assert.are.equal (getmetatable (petrinet.t), Petrinet.Transition)
assert.are.equal (getmetatable (petrinet.t [1]), Petrinet.Arc)
assert.are.equal (getmetatable (petrinet.t [2]), Petrinet.Arc)
assert.are.equal (petrinet.t [1].place, petrinet.p)
assert.are.equal (petrinet.t [2].place, petrinet.q)
assert.are.equal (petrinet.t [1].valuation, 1)
assert.are.equal (petrinet.t [2].valuation, 1)
end)
it ("can iterate over its transitions", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place {}
petrinet.q = petrinet:place {}
petrinet.t = petrinet:transition {
petrinet.p - 1,
petrinet.q + 1,
}
petrinet.u = petrinet:transition {
petrinet.q - 1,
petrinet.p + 1,
}
local transitions = {}
for _, transition in petrinet:transitions () do
assert.are.equal (getmetatable (transition), Petrinet.Transition)
transitions [transition] = true
end
assert.are.same (transitions, {
[petrinet.t] = true,
[petrinet.u] = true,
})
end)
it ("can iterate over pre arcs", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place {}
petrinet.q = petrinet:place {}
petrinet.t = petrinet:transition {
petrinet.p - 1,
petrinet.q + 1,
}
local arcs = {}
for arc in petrinet.t:pre () do
assert.are.equal (getmetatable (arc), Petrinet.Arc)
arcs [#arcs+1] = true
end
assert.are.equal (#arcs, 1)
end)
it ("can iterate over post arcs", function ()
local petrinet = Petrinet ()
petrinet.p = petrinet:place {}
petrinet.q = petrinet:place {}
petrinet.t = petrinet:transition {
petrinet.p - 1,
petrinet.q + 1,
}
local arcs = {}
for arc in petrinet.t:post () do
assert.are.equal (getmetatable (arc), Petrinet.Arc)
arcs [#arcs+1] = true
end
assert.are.equal (#arcs, 1)
end)
it ("can load the example", function ()
local _ = require "petrinet.example"
end)
end)
|
local Euclidean, parent = torch.class('nn.Euclidean', 'nn.Module')
function Euclidean:__init(inputSize,outputSize)
parent.__init(self)
self.weight = torch.Tensor(inputSize,outputSize)
self.gradWeight = torch.Tensor(inputSize,outputSize)
-- state
self.gradInput:resize(inputSize)
self.output:resize(outputSize)
self:reset()
end
function Euclidean:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(1))
end
-- we do this so the initialization is exactly
-- the same than in previous torch versions
for i=1,self.weight:size(2) do
self.weight:select(2, i):apply(function()
return random.uniform(-stdv, stdv)
end)
end
end
function Euclidean:forward(input)
self.output:zero()
for i=1,self.weight:size(2) do
self.output[i]=input:dist(self.weight:select(2,i))
end
return self.output
end
function Euclidean:backward(input, gradOutput)
for i=1,self.weight:size(2) do
local gW=self.gradWeight:select(2,i)
gW:add(2*gradOutput[i],self.weight:select(2,i));
gW:add(-2*gradOutput[i],input);
end
self.gradInput:zero();
for i=1,self.weight:size(2) do
self.gradInput:add(2*gradOutput[i],input);
self.gradInput:add(-2*gradOutput[i],self.weight:select(2,i));
end
return self.gradInput
end
function Euclidean:zeroGradParameters()
self.gradWeight:zero()
end
function Euclidean:updateParameters(learningRate)
self.weight:add(-learningRate, self.gradWeight)
end
function Euclidean:write(file)
parent.write(self, file)
file:writeObject(self.weight)
file:writeObject(self.gradWeight)
end
function Euclidean:read(file)
parent.read(self, file)
self.weight = file:readObject()
self.gradWeight = file:readObject()
end
|
module 'mock'
---------------------------------------------------------------------
--Material
--------------------------------------------------------------------
CLASS: PhysicsMaterial ()
:MODEL{
Field 'tag' :string();
'----';
Field 'density';
Field 'restitution';
Field 'friction';
'----';
Field 'group' :int();
Field 'categoryBits' :int() :widget( 'bitmask16' );
Field 'maskBits' :int() :widget( 'bitmask16' );
'----';
Field 'isSensor' :boolean();
'----';
Field 'comment' :string();
}
function PhysicsMaterial:__init()
self.tag = false
self.density = 1
self.restitution = 0
self.friction = 0
self.isSensor = false
self.group = 0
self.categoryBits = 1
self.maskBits = 0xffffffff
self.comment = ''
end
function PhysicsMaterial:clone()
local m = PhysicsMaterial()
m.density = self.density
m.restitution = self.restitution
m.friction = self.friction
m.isSensor = self.isSensor
m.group = self.group
m.categoryBits = self.categoryBits
m.maskBits = self.maskBits
m.tag = self.tag
return m
end
--------------------------------------------------------------------
local DefaultMaterial = PhysicsMaterial()
function getDefaultPhysicsMaterial()
return DefaultMaterial
end
--------------------------------------------------------------------
local function loadPhysicsMaterial( node )
local data = mock.loadAssetDataTable( node:getObjectFile('def') )
local config = mock.deserialize( nil, data )
return config
end
registerAssetLoader( 'physics_material', loadPhysicsMaterial )
|
---------------------------------------------------------------------------------------------------
-- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0273-webengine-projection-mode.md
--
-- Description: Check HMI status transitions of WEB_VIEW application
--
-- Preconditions:
-- 1) SDL and HMI are started
-- 2) WebEngine App with WEB_VIEW HMI type is registered
-- 3) WebEngine App is in some state
--
-- Sequence:
-- 1) WebEngine App is moving to another state by one of the events:
-- App activation, App deactivation, Deactivation of HMI, User exit
-- a. SDL sends OnHMIStatus notification with appropriate value of 'hmiLevel' parameter
--
-- Particular behavior and value depends on initial state and event, and described in 'testCases' table below
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/WebEngine/commonWebEngine')
--[[ Test Configuration ]]
config.checkAllValidations = true
--[[ Local Constants ]]
local appSessionId = 1
local webEngineDevice = 1
--[[ Local Functions ]]
local function action(pActionName)
return common.userActions[pActionName]
end
local function doAction(pExpAppState)
pExpAppState.event.func()
common.checkHMIStatus(pExpAppState.event.name, appSessionId, pExpAppState)
end
--[[ Local Variables ]]
local testCases = {
[001] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" }
}},
[002] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[003] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "LIMITED", audio = "AUDIBLE", video = "NOT_STREAMABLE" }
}},
[004] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[005] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[006] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[007] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "LIMITED", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[008] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("exitApp"), hmiLvl = "NONE", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[009] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("exitApp"), hmiLvl = "NONE", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[010] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "LIMITED", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("exitApp"), hmiLvl = "NONE", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[011] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("exitApp"), hmiLvl = "NONE", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[012] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("exitApp"), hmiLvl = "NONE", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[013] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("exitApp"), hmiLvl = "NONE", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[014] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "LIMITED", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" }
}},
[015] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateApp"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}},
[016] = { appType = "WEB_VIEW", isMedia = true, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("activateHMI"), hmiLvl = "FULL", audio = "AUDIBLE", video = "NOT_STREAMABLE" }
}},
[017] = { appType = "WEB_VIEW", isMedia = false, state = {
[1] = { event = action("activateApp"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[2] = { event = action("deactivateHMI"), hmiLvl = "BACKGROUND", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" },
[3] = { event = action("activateHMI"), hmiLvl = "FULL", audio = "NOT_AUDIBLE", video = "NOT_STREAMABLE" }
}}
}
--[[ Scenario ]]
for n, tc in common.spairs(testCases) do
common.Title("TC[" .. string.format("%03d", n) .. "]: "
.. "[hmiType:" .. tc.appType .. ", isMedia:" .. tostring(tc.isMedia) .. "]")
common.Title("Preconditions")
common.Step("Clean environment", common.preconditions)
common.Step("Update WS Server Certificate parameters in smartDeviceLink.ini file", common.commentAllCertInIniFile)
common.Step("Add AppHMIType to preloaded policy table", common.updatePreloadedPT, { appSessionId, { tc.appType }})
common.Step("Start SDL, HMI", common.startWOdeviceConnect)
common.Step("Connect WebEngine device", common.connectWebEngine, { webEngineDevice, "WS" })
common.Step("Set App Config", common.setAppConfig, { appSessionId, tc.appType, tc.isMedia })
common.Step("Register App", common.registerAppWOPTU)
common.Title("Test")
for i = 1, #tc.state do
common.Step("Action:" .. tc.state[i].event.name .. ",hmiLevel:" .. tc.state[i].hmiLvl, doAction, { tc.state[i] })
end
common.Title("Postconditions")
common.Step("Clean sessions", common.cleanSessions)
common.Step("Stop SDL", common.postconditions)
end
|
data:extend({
{
type = "item-with-entity-data",
name = "atomic-locomotive",
icon = "__Atomic Locomotives__/graphics/icons/atomic-locomotive.png",
flags = {"goes-to-quickbar"},
subgroup = "transport",
order = "a[train-system]-fz[diesel-locomotive]",
place_result = "atomic-locomotive",
stack_size = 5
},
{
type = "item-with-entity-data",
name = "atomic-shuttle",
icon = "__Atomic Locomotives__/graphics/icons/atomic-locomotive.png",
flags = {"goes-to-quickbar"},
subgroup = "transport",
order = "a[train-system]-fz[diesel-locomotive]",
place_result = "atomic-shuttle",
stack_size = 5
}
}) |
---------------------------------------------------------------
-- Init.lua: Main frame creation, version checking, slash cmd
---------------------------------------------------------------
-- 1. Create the main frame and check all loaded settings.
-- 2. Validate compatibility with older versions.
-- 3. Create the slash handler function.
local addOn, db = ...
---------------------------------------------------------------
local NEWCALIBRATION, BINDINGSLOADED
---------------------------------------------------------------
-- Initialize addon tables
---------------------------------------------------------------
db.ICONS = {}
db.TEXTURE = {}
db.SECURE = {}
db.PANELS = {}
db.PLUGINS = {}
---------------------------------------------------------------
-- Popup functions
---------------------------------------------------------------
local function LoadDefaultBindings()
ConsolePortConfig:OpenCategory('Binds')
ConsolePortConfigContainerBinds:Default()
ConsolePort:CheckLoadedSettings()
end
local function LoadWoWmapper()
db.Settings.calibration = db.table.copy(WoWmapper.Keys)
for k, v in pairs(WoWmapper.Settings) do
db.Settings[k] = v
end
db.Settings.type = db.Settings.forceController or db.Settings.type
end
local function CancelPopup()
ConsolePort:ClearPopup()
end
---------------------------------------------------------------
function ConsolePort:LoadSettings()
local selectController --, newUser
-----------------------------------------------------------
-- Set/load addon settings
-----------------------------------------------------------
if not ConsolePortSettings then
selectController = true
ConsolePortSettings = self:GetDefaultAddonSettings()
end
db.Settings = ConsolePortSettings
db.Settings.calibration = db.Settings.calibration or {}
-----------------------------------------------------------
-- Load exported WoWmapper settings
-----------------------------------------------------------
if WoWmapper then
if ( not WoWmapper.Keys ) or ( not WoWmapper.Settings ) then
print('Calibration or settings table missing in WoWmapper export data.')
else
if db('wmupdate') or ( not db('calibration') ) then
db.Settings.wmupdate = nil
LoadWoWmapper()
else
local cs, ws = db.Settings, WoWmapper.Settings
local cb, wk = cs.calibration, WoWmapper.Keys
for k, v in pairs(cb) do
if wk[k] ~= v then
NEWCALIBRATION = true
break
end
end
for k, v in pairs(ws) do
if k ~= 'type' and cs[k] ~= v then
NEWCALIBRATION = true
break
end
end
end
selectController = false
end
end
-----------------------------------------------------------
-- Load controller splash if no preference exists
-----------------------------------------------------------
if selectController then
self:SelectController()
end
self:LoadLookup()
-----------------------------------------------------------
-- Set/load mouse settings
-----------------------------------------------------------
ConsolePortMouse = ConsolePortMouse or {
Events = self:GetDefaultMouseEvents();
Cursor = self:GetDefaultMouseCursor();
}
-----------------------------------------------------------
-- Add empty bindings popup for later use
-----------------------------------------------------------
StaticPopupDialogs['CONSOLEPORT_IMPORTBINDINGS'] = {
button1 = db.TUTORIAL.SLASH.ACCEPT,
button2 = db.TUTORIAL.SLASH.CANCEL,
showAlert = true,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3,
enterClicksFirstButton = true,
exclusive = true,
OnAccept = LoadDefaultBindings,
OnCancel = CancelPopup,
OnShow = function(self)
-- don't show the popup when selecting controller layout or calibrating.
if ( ConsolePortSplashFrame and ConsolePortSplashFrame:IsVisible() ) or
( ConsolePortCalibrationFrame and ConsolePortCalibrationFrame:IsVisible() ) then
self:Hide()
end
end,
}
-----------------------------------------------------------
-- Extra features
-----------------------------------------------------------
-- Use these frames in the virtual cursor stack
ConsolePortUIFrames = ConsolePortUIFrames or self:GetDefaultUIFrames()
-- Use this table to populate radial action bar
ConsolePortUtility = ConsolePortUtility or {}
-- Use this table to store UI module settings
ConsolePortUIConfig = ConsolePortUIConfig or {}
----------------------------------------------------------
db.UIStack = ConsolePortUIFrames
db.UIConfig = ConsolePortUIConfig
db.Mouse = ConsolePortMouse
----------------------------------------------------------
-- Load the calibration wizard if a button does not have a registered mock binding
----------------------------------------------------------
if self:CheckCalibration() then
self:CalibrateController()
end
----------------------------------------------------------
-- Load UI handle fade frames
----------------------------------------------------------
ConsolePortUIHandle:LoadFadeFrames()
----------------------------------------------------------
-- Create slash handler
----------------------------------------------------------
self:CreateSlashHandler()
----------------------------------------------------------
self.LoadSettings = nil
end
function ConsolePort:WMupdate()
StaticPopupDialogs['CONSOLEPORT_WMUPDATE'] = {
text = db.TUTORIAL.SLASH.WMUPDATE,
button1 = db.TUTORIAL.SLASH.ACCEPT,
button2 = db.TUTORIAL.SLASH.CANCEL,
showAlert = true,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3,
enterClicksFirstButton = true,
exclusive = true,
OnAccept = function()
db.Settings.wmupdate = true
ReloadUI()
end,
OnCancel = CancelPopup,
}
self:ShowPopup('CONSOLEPORT_WMUPDATE')
end
function ConsolePort:GetBindingSet(specID)
-----------------------------------------------------------
-- Set/load binding table
-----------------------------------------------------------
local specID = specID or GetSpecialization()
-- Flag bindings loaded so the settings checkup doesn't run this part.
BINDINGSLOADED = true
-- Assert the SV binding set container exists before proceeding
ConsolePortBindingSet = ConsolePortBindingSet or {}
-- BC: Convert old binding set paradigm to spec-specific
-- Check if set contains a string key, in which case it's using the
-- outdated binding format.
if type(next(ConsolePortBindingSet)) == 'string' then
ConsolePortBindingSet = {[specID] = ConsolePortBindingSet}
end
-- Assert the current specID is included in the set and that bindings exist,
-- else create the subset (and flag no bindings for the popup).
local set = ConsolePortBindingSet
set[specID] = set[specID] or db.table.copy(db.Bindings) or {}
-- return the current binding set and the specID
return set[specID], specID
end
function ConsolePort:CheckLoadedSettings()
local settings = ConsolePortSettings
if settings then
if settings.newController then
local popupData = StaticPopupDialogs['CONSOLEPORT_IMPORTBINDINGS']
popupData.text = db.TUTORIAL.SLASH.NEWCONTROLLER
self:ShowPopup('CONSOLEPORT_IMPORTBINDINGS')
settings.newController = nil
elseif NEWCALIBRATION and ( not settings.id or (WoWmapper and WoWmapper.Settings and (settings.id ~= WoWmapper.Settings.id)) ) then
NEWCALIBRATION = nil
settings.id = WoWmapper.Settings.id
StaticPopupDialogs['CONSOLEPORT_CALIBRATIONUPDATE'] = {
text = db.TUTORIAL.SLASH.CALIBRATIONUPDATE,
button1 = db.TUTORIAL.SLASH.ACCEPT,
button2 = db.TUTORIAL.SLASH.CANCEL,
showAlert = true,
timeout = 0,
whileDead = true,
hideOnEscape = true,
preferredIndex = 3,
enterClicksFirstButton = true,
exclusive = true,
OnAccept = function()
LoadWoWmapper()
ReloadUI()
end,
OnCancel = CancelPopup,
}
self:ShowPopup('CONSOLEPORT_CALIBRATIONUPDATE')
elseif BINDINGSLOADED and ( not db.Bindings or not next(db.Bindings) ) then
local popupData = StaticPopupDialogs['CONSOLEPORT_IMPORTBINDINGS']
popupData.text = db.TUTORIAL.SLASH.NOBINDINGS
self:ShowPopup('CONSOLEPORT_IMPORTBINDINGS')
end
end
end
function ConsolePort:CreateActionButtons()
for name in self:GetBindings() do
for modifier in self:GetModifiers() do
self:CreateSecureButton(name, modifier, self:GetUIControlKey(name))
end
end
self.CreateActionButtons = nil
end |
-- ============================================================================
-- Handle collision events during gameplay.
--
-- @param inEvent The event object describing the event.
-- ============================================================================
function gc:collision(inEvent)
-- All collisions involve the ship, so figure out what object it hit.
local colObj = inEvent.object1.objName;
if colObj == "ship" then
colObj = inEvent.object2.objName;
end
-- No collision events when the game isn't currently in the flying phase
-- UNLESS its with a "crash" object. It may look a bit strange, but we have
-- to do it this way to ensure that if the ship lands half on the pad and
-- half off that we register it as an explosion (without checking for "crash"
-- here we'll miss that case because when they land we're no longer in the
-- flying phase, so the first half of this statement would cause us to not
-- evaluate the rest of the logic and give the player a free pass basically).
if gc.phase ~= gc.PHASE_FLYING and colObj ~= "crash" then
return;
end
-- Handle the beginning of collision events only.
if inEvent.phase == "began" then
-- >>>>>>>>>> If collision is between the ship and anything that it can
-- crash with (top-level tile, ship, alien UFO, plasma ball).
if colObj == "crash" then
utils:log("gameCoreCollisionEvents", "Crash");
gc:showExplosion(gc.ship.sprite.x, gc.ship.sprite.y);
-- >>>>>>>>>> If they land on a pad, make sure their velocity is below the
-- crash threshold, otherwise mark them as landed.
elseif colObj == "pad" then
utils:log("gameCoreCollisionEvents", "Pad contact");
local vX, vY = gc.ship.sprite:getLinearVelocity();
if vX > 75 or vY > 75 then
-- Moving too fast, blow them up.
utils:log(
"gameCoreCollisionEvents",
"Pad crash (Too fast: vX(75)=" .. vX .. ", vY(75)=" .. vY .. ")"
);
gc:showExplosion(gc.ship.sprite.x, gc.ship.sprite.y);
else
-- Velocity is good, we're down!
utils:log("gameCoreCollisionEvents", "Safely landed");
gc.ship.sprite:setSequence("noThrust");
gc.ship.sprite:play();
gc.ship.thrustVertical = false;
gc.ship.thrustLeft = false;
gc.ship.thrustRight = false;
gc.phase = gc.PHASE_LANDED;
end
-- >>>>>>>>>> Entered the landing bay.
elseif colObj == "bay" then
utils:log("gameCoreCollisionEvents", "Entered landing bay");
-- Then transition to the new phase.
gc:stopAllActivity();
gc.phase = gc.PHASE_IN_BAY;
-- >>>>>>>>>> Oops, hit the colonist!
elseif colObj == "colonist" and gc.colonist.sprite.isVisible == true then
gc.sfx.screamChannel = audio.play(gc.sfx.scream);
-- Remove the colonist and reset for the next appearance. Oh yeah, and
-- subtract from the score.
gameData.score = gameData.score - 50;
if gameData.score < 0 then
gameData.score = 0;
end
gc.colonist.sprite.isVisible = false;
gc.colonist.appearCounter = 0;
-- >>>>>>>>>> Gasing up.
elseif colObj == "fuelPod" then
gc.sfx.fuelPodPickupChannel = audio.play(gc.sfx.fuelPodPickup);
gc:showMessage("Got Some Fuel");
-- Hide fuel pod.
gc.fuelPod.sprite.isVisible = false;
gc.fuelPod.sprite.x = -1000;
gc.fuelPod.sprite.y = -1000;
-- Add some gas.
gc.ship.fuel = gc.ship.fuel + 50;
if gc.ship.fuel > gc.fuelGauge.fill.width then
gc.ship.fuel = gc.ship.maxFuel;
end
gc.updateFuelGauge();
end
end -- End began.
end -- End touch().
-- ============================================================================
-- Shows an explosion at a specific location and then calls a callback
-- function when the animation completes.
--
-- @param inX X location of center of explosion.
-- @param inY Y location of center of explosion.
-- @param inCallback Function to call when explosion animation completes.
-- ============================================================================
function gc:showExplosion(inX, inY, inCallback)
utils:log("gameCoreCollisionEvents", "showExplosion()");
-- First, stop all current game activity.
gc.stopAllActivity();
-- Set the appropriate phase.
gc.phase = gc.EXPLODING;
-- Vibrate, if the device supports it.
system.vibrate();
-- Show the explosion and set up to call the specific callback function when
-- it completes.
gc.explosion.sprite.isVisible = true;
gc.explosion.sprite.x = inX;
gc.explosion.sprite.y = inY;
gc.explosion.sprite:setSequence("exploding");
gc.explosion.sprite:play();
gc.explosion.callback = inCallback;
gc.explosion.sprite:addEventListener("sprite",
function(inEvent)
if inEvent.target.sequence == "exploding" and
inEvent.phase == "ended"
then
gc.explosion.sprite.isVisible = false;
gc.phase = gc.PHASE_DEAD;
end
end
);
-- Also play our explosion sound.
gc.sfx.explosionChannel = audio.play(gc.sfx.explosion);
end -- End showExplosion().
-- ============================================================================
-- Updates the fuel gauge to reflect the current amount of ship fuel.
-- ============================================================================
function gc:updateFuelGauge()
-- Get rid of the old fill.
if gc.fuelGauge.fill ~= nil then
gc.fuelGauge.fill:removeSelf();
gc.fuelGauge.fill = nil;
end
-- Create a new fill if they have some gas left.
if gc.ship.fuel > 0 then
gc.fuelGauge.fill = display.newRect(
(gc.fuelGauge.shell.x - (gc.fuelGauge.shell.width / 2)) + 3,
(gc.fuelGauge.shell.y - (gc.fuelGauge.shell.height / 2)) + 3,
gc.ship.fuel, gc.fuelGauge.shell.height - 5
);
gc.fuelGauge.fill:setFillColor(255, 0, 0);
gc.gameDG:insert(gc.fuelGauge.fill);
end
end -- End updateFuelGauge().
|
--------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: DevIL2
project( "DevIL2" )
configuration( {} )
location( os.getenv( "PM5OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM5TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( {} )
kind( "SharedLib" )
configuration( {} )
links( { "OpenEXR", "jasper", "lcms2", "libjpeg", "libmng", "libpng", "libtiff", "squish", "zlib" } )
links( { "OpenEXR", "jasper", "lcms2", "libjpeg", "libmng", "libpng", "libtiff", "squish", "zlib" } )
configuration( {} )
defines( { "CMS_DLL", "HAVE_CONFIG_H", "JAS_DLL", "MNG_DLL", "MNG_USE_DLL" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"src-IL/include/altivec_common.h",
"src-IL/include/altivec_typeconversion.h",
"src-IL/include/il_alloc.h",
"src-IL/include/il_bits.h",
"src-IL/include/il_bmp.h",
"src-IL/include/il_dcx.h",
"src-IL/include/il_dds.h",
"src-IL/include/il_doompal.h",
"src-IL/include/il_dpx.h",
"src-IL/include/il_endian.h",
"src-IL/include/il_exr.h",
"src-IL/include/il_files.h",
"src-IL/include/il_gif.h",
"src-IL/include/il_hdr.h",
"src-IL/include/il_icns.h",
"src-IL/include/il_icon.h",
"src-IL/include/il_internal.h",
"src-IL/include/il_jp2.h",
"src-IL/include/il_jpeg.h",
"src-IL/include/il_lif.h",
"src-IL/include/il_manip.h",
"src-IL/include/il_mdl.h",
"src-IL/include/il_pal.h",
"src-IL/include/il_pcx.h",
"src-IL/include/il_pic.h",
"src-IL/include/il_pnm.h",
"src-IL/include/il_psd.h",
"src-IL/include/il_psp.h",
"src-IL/include/il_q2pal.h",
"src-IL/include/il_register.h",
"src-IL/include/il_rle.h",
"src-IL/include/il_sgi.h",
"src-IL/include/il_stack.h",
"src-IL/include/il_states.h",
"src-IL/include/il_targa.h",
"src-IL/include/il_utx.h",
"src-IL/include/il_vtf.h",
"src-IL/include/il_wdp.h",
"src-IL/include/rg_etc1.h",
"src-ILU/include/ilu_alloc.h",
"src-ILU/include/ilu_filter.h",
"src-ILU/include/ilu_internal.h",
"src-ILU/include/ilu_region.h",
"src-ILU/include/ilu_states.h",
"src-ILU/include/ilu_error/ilu_err-arabic.h",
"src-ILU/include/ilu_error/ilu_err-dutch.h",
"src-ILU/include/ilu_error/ilu_err-english.h",
"src-ILU/include/ilu_error/ilu_err-french.h",
"src-ILU/include/ilu_error/ilu_err-german.h",
"src-ILU/include/ilu_error/ilu_err-italian.h",
"src-ILU/include/ilu_error/ilu_err-japanese.h",
"src-ILU/include/ilu_error/ilu_err-spanish.h",
"src-ILUT/include/ilut_allegro.h",
"src-ILUT/include/ilut_internal.h",
"src-ILUT/include/ilut_opengl.h",
"src-ILUT/include/ilut_states.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src-IL/src/altivec_common.cpp",
"src-IL/src/altivec_typeconversion.cpp",
"src-IL/src/il_alloc.cpp",
"src-IL/src/il_bits.cpp",
"src-IL/src/il_blp.cpp",
"src-IL/src/il_bmp.cpp",
"src-IL/src/il_convbuff.cpp",
"src-IL/src/il_convert.cpp",
"src-IL/src/il_cut.cpp",
"src-IL/src/il_dcx.cpp",
"src-IL/src/il_dds-save.cpp",
"src-IL/src/il_dds.cpp",
"src-IL/src/il_devil.cpp",
"src-IL/src/il_dicom.cpp",
"src-IL/src/il_doom.cpp",
"src-IL/src/il_dpx.cpp",
"src-IL/src/il_endian.cpp",
"src-IL/src/il_error.cpp",
"src-IL/src/il_exr.c",
"src-IL/src/il_exr.cpp",
"src-IL/src/il_fastconv.cpp",
"src-IL/src/il_files.cpp",
"src-IL/src/il_fits.cpp",
"src-IL/src/il_ftx.cpp",
"src-IL/src/il_gif.cpp",
"src-IL/src/il_hdr.cpp",
"src-IL/src/il_header.cpp",
"src-IL/src/il_icns.cpp",
"src-IL/src/il_icon.cpp",
"src-IL/src/il_iff.cpp",
"src-IL/src/il_ilbm.cpp",
"src-IL/src/il_internal.cpp",
"src-IL/src/il_io.cpp",
"src-IL/src/il_iwi.cpp",
"src-IL/src/il_jp2.cpp",
"src-IL/src/il_jpeg.cpp",
"src-IL/src/il_ktx.cpp",
"src-IL/src/il_lif.cpp",
"src-IL/src/il_manip.cpp",
"src-IL/src/il_mdl.cpp",
"src-IL/src/il_mng.cpp",
"src-IL/src/il_mp3.cpp",
"src-IL/src/il_neuquant.cpp",
"src-IL/src/il_nvidia.cpp",
"src-IL/src/il_pal.cpp",
"src-IL/src/il_pcd.cpp",
"src-IL/src/il_pcx.cpp",
"src-IL/src/il_pic.cpp",
"src-IL/src/il_pix.cpp",
"src-IL/src/il_png.cpp",
"src-IL/src/il_pnm.cpp",
"src-IL/src/il_profiles.cpp",
"src-IL/src/il_psd.cpp",
"src-IL/src/il_psp.cpp",
"src-IL/src/il_pxr.cpp",
"src-IL/src/il_quantizer.cpp",
"src-IL/src/il_raw.cpp",
"src-IL/src/il_rawdata.cpp",
"src-IL/src/il_register.cpp",
"src-IL/src/il_rle.cpp",
"src-IL/src/il_rot.cpp",
"src-IL/src/il_sgi.cpp",
"src-IL/src/il_size.cpp",
"src-IL/src/il_squish.cpp",
"src-IL/src/il_stack.cpp",
"src-IL/src/il_states.cpp",
"src-IL/src/il_sun.cpp",
"src-IL/src/il_targa.cpp",
"src-IL/src/il_texture.cpp",
"src-IL/src/il_tiff.cpp",
"src-IL/src/il_tpl.cpp",
"src-IL/src/il_utility.cpp",
"src-IL/src/il_utx.c",
"src-IL/src/il_utx.cpp",
"src-IL/src/il_vtf.cpp",
"src-IL/src/il_wal.cpp",
"src-IL/src/il_wbmp.cpp",
"src-IL/src/il_wdp.cpp",
"src-IL/src/il_xpm.cpp",
"src-IL/src/rg_etc1.cpp",
"src-ILU/src/ilu_alloc.cpp",
"src-ILU/src/ilu_error.cpp",
"src-ILU/src/ilu_filter.cpp",
"src-ILU/src/ilu_filter_rcg.cpp",
"src-ILU/src/ilu_internal.cpp",
"src-ILU/src/ilu_manip.cpp",
"src-ILU/src/ilu_mipmap.cpp",
"src-ILU/src/ilu_noise.cpp",
"src-ILU/src/ilu_region.cpp",
"src-ILU/src/ilu_rotate.cpp",
"src-ILU/src/ilu_scale.cpp",
"src-ILU/src/ilu_scale2d.cpp",
"src-ILU/src/ilu_scale3d.cpp",
"src-ILU/src/ilu_scaling.cpp",
"src-ILU/src/ilu_states.cpp",
"src-ILU/src/ilu_utilities.cpp",
"src-ILUT/src/ilut_allegro.cpp",
"src-ILUT/src/ilut_directx.cpp",
"src-ILUT/src/ilut_directx10.cpp",
"src-ILUT/src/ilut_directx9.cpp",
"src-ILUT/src/ilut_directxm.cpp",
"src-ILUT/src/ilut_internal.cpp",
"src-ILUT/src/ilut_opengl.cpp",
"src-ILUT/src/ilut_sdlsurface.cpp",
"src-ILUT/src/ilut_states.cpp",
"src-ILUT/src/ilut_win32.cpp",
"src-ILUT/src/ilut_x11.cpp"
} )
configuration( {} )
includedirs( { "../../Little-CMS/include", "../../Little-CMS/src", "../../jasper/src/libjasper/bmp", "../../jasper/src/libjasper/include", "../../jasper/src/libjasper/include/jasper", "../../jasper/src/libjasper/jp2", "../../jasper/src/libjasper/jpc", "../../jasper/src/libjasper/jpg", "../../jasper/src/libjasper/mif", "../../jasper/src/libjasper/pgx", "../../jasper/src/libjasper/pnm", "../../jasper/src/libjasper/ras", "../../libjpeg", "../../libmng", "../../libpng", "../../libsquish", "../../openexr/IlmBase", "../../openexr/IlmBase/Half", "../../openexr/IlmBase/Iex", "../../openexr/IlmBase/IexMath", "../../openexr/IlmBase/IlmThread", "../../openexr/IlmBase/Imath", "../../openexr/IlmBase/config.windows", "../../openexr/OpenEXR", "../../openexr/OpenEXR/IlmImf", "../../openexr/OpenEXR/IlmImfUtil", "../../openexr/OpenEXR/config.windows", "../../tiff/libtiff", "include", "include/IL", "src-IL", "src-ILU", "src-ILUT", "src-IL/include", "src-ILU/include", "src-ILU/include/ilu_error", "src-ILUT/include" } )
configuration( { "LINUX32" } )
includedirs( { "../../zlib", "include/IL/linux" } )
configuration( { "LINUX64" } )
includedirs( { "../../zlib", "include/IL/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../zlib", "include/IL/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../zlib", "include/IL/mswin" } )
|
local ok, mod
ok, mod = pcall(require,'irc-parser.lpeg')
if not ok then
mod = require'irc-parser.fallback'
end
mod._VERSION = '1.2.0'
return mod
|
inner_table = {
x = 1,
y = 1,
z = 1,
msg =
function()
return "ok"
end,
}
metatable = {
__index = inner_table,
__newindex = inner_table,
}
table1 = { }
setmetatable(table1, metatable)
print(table1, table1.x, table1.y, table1.z, table1.msg, table1:msg())
table2 = { }
setmetatable(table2, metatable)
print(table2, table2.x, table2.y, table2.z, table2.msg, table2:msg())
print("change table1 only")
table1.x = 2
table1.y = 2
table1.z = 2
table1.msg =
function()
return "updated"
end
print(table1, table1.x, table1.y, table1.z, table1.msg, table1:msg())
print(table2, table2.x, table2.y, table2.z, table2.msg, table2:msg())
|
--- @ignore
local surface = surface
local IsValid = IsValid
local TryTranslation = LANG.TryTranslation
local base = "base_stacking_element"
DEFINE_BASECLASS(base)
HUDELEMENT.Base = base
if CLIENT then
-- color defines
local color_empty = Color(200, 20, 20, 255)
local color_empty_dark = Color(200, 20, 20, 100)
local element_height = 28
local margin = 5
local lpw = 22 -- left panel width
local const_defaults = {
basepos = {x = 0, y = 0},
size = {w = 365, h = 28},
minsize = {w = 240, h = 28}
}
function HUDELEMENT:PreInitialize()
self.drawer = hudelements.GetStored("pure_skin_element")
end
function HUDELEMENT:Initialize()
self.scale = 1.0
self.basecolor = self:GetHUDBasecolor()
self.element_height = element_height
self.margin = margin
self.lpw = lpw
WSWITCH:UpdateWeaponCache()
BaseClass.Initialize(self)
end
function HUDELEMENT:GetDefaults()
const_defaults["basepos"] = {x = ScrW() - (self.size.w + self.margin * 2), y = ScrH() - self.margin}
return const_defaults
end
-- parameter overwrites
function HUDELEMENT:IsResizable()
return true, false
end
-- parameter overwrites end
function HUDELEMENT:PerformLayout()
self.scale = appearance.GetGlobalScale()
self.basecolor = self:GetHUDBasecolor()
self.element_height = element_height * self.scale
self.margin = margin * self.scale
self.lpw = lpw * self.scale
BaseClass.PerformLayout(self)
end
function HUDELEMENT:DrawBarBg(x, y, w, h, active)
local ply = LocalPlayer()
local c = (active and ply:GetRoleColor() or ply:GetRoleDkColor()) or Color(100, 100, 100)
-- draw bg and shadow
self.drawer:DrawBg(x, y, w, h, self.basecolor)
if active then
surface.SetDrawColor(0, 0, 0, 90)
surface.DrawRect(x, y, w, h)
end
-- Draw the colour tip
surface.SetDrawColor(c.r, c.g, c.b, c.a)
surface.DrawRect(x, y, self.lpw, h)
-- draw lines around the element
self.drawer:DrawLines(x, y, w, h, self.basecolor.a)
return c
end
function HUDELEMENT:DrawWeapon(x, y, active, wep, tip_color)
if not IsValid(wep) or not IsValid(wep.Owner) or not isfunction(wep.Owner.GetAmmoCount) then
return false
end
--define colors
local text_color = util.GetDefaultColor(self.basecolor)
text_color = active and text_color or Color(text_color.r, text_color.g, text_color.b, text_color.r > 128 and 100 or 180)
local number_color = util.GetDefaultColor(tip_color)
number_color = active and number_color or Color(number_color.r, number_color.g, number_color.b, number_color.r > 128 and 100 or 180)
local empty_color = active and color_empty or color_empty_dark
local name = TryTranslation(wep:GetPrintName() or wep.PrintName or "...")
local cl1, am1 = wep:Clip1(), (wep.Ammo1 and wep:Ammo1() or false)
local ammo = false
-- Clip1 will be -1 if a melee weapon
-- Ammo1 will be false if weapon has no owner (was just dropped)
if cl1 ~= -1 and am1 ~= false then
ammo = Format("%i + %02i", cl1, am1)
end
-- Slot
draw.AdvancedText(MakeKindValid(wep.Kind), "PureSkinWepNum", x + self.lpw * 0.5, y + self.element_height * 0.5, number_color, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, true, self.scale)
-- Name
draw.AdvancedText(string.upper(name), "PureSkinWep", x + 10 + self.element_height, y + self.element_height * 0.5, text_color, nil, TEXT_ALIGN_CENTER, true, self.scale)
if ammo then
local col = (wep:Clip1() == 0 and wep:Ammo1() == 0) and empty_color or text_color
-- Ammo
draw.AdvancedText(tostring(ammo), "PureSkinWep", x + self.size.w - self.margin * 3, y + self.element_height * 0.5, col, TEXT_ALIGN_RIGHT, TEXT_ALIGN_CENTER, false, self.scale)
end
return true
end
function HUDELEMENT:ShouldDraw()
return HUDEditor.IsEditing or WSWITCH.Show
end
function HUDELEMENT:Draw()
local weaponList = {}
local weps = WSWITCH.WeaponCache
local count = table.Count(weps)
for i = 1, count do
weaponList[i] = {h = self.element_height}
end
self:SetElements(weaponList)
self:SetElementMargin(self.margin)
BaseClass.Draw(self)
end
function HUDELEMENT:DrawElement(i, x, y, w, h)
local active = WSWITCH.Selected == i
local tipCol = self:DrawBarBg(x, y, w, h, active)
if not self:DrawWeapon(x, y, active, WSWITCH.WeaponCache[i], tipCol) then
WSWITCH:UpdateWeaponCache()
return
end
end
end
|
local API_NPC = require(script:GetCustomProperty("API_NPC"))
local API_P = require(script:GetCustomProperty("APIProjectile"))
local PROJECTILE_TEMPLATE = script:GetCustomProperty("ProjectileTemplate")
local EFFECT_TEMPLATE = script:GetCustomProperty("EffectTemplate")
local PROJECTILE_SPEED = 1700.0
function OnTaskStart(npc, animatedMesh)
local target = API_NPC.GetTarget(npc)
API_P.CreateProjectile(npc, target, PROJECTILE_SPEED, 0.3, PROJECTILE_TEMPLATE)
animatedMesh:PlayAnimation("unarmed_throw")
end
function OnTaskEnd(npc, animatedMesh, interrupted)
animatedMesh:StopAnimations()
end
API_NPC.RegisterTaskClient("goblin_throw_cleaver", EFFECT_TEMPLATE, OnTaskStart, OnTaskEnd)
|
local stub = require("luassert.stub")
local s = require("null-ls.state")
local u = require("null-ls.utils")
local generators = require("null-ls.generators")
local methods = require("null-ls.methods")
local code_actions = require("null-ls.code-actions")
describe("code_actions", function()
stub(s, "clear_actions")
stub(s, "register_action")
stub(s, "get")
stub(s, "run_action")
local mock_uri = "file:///mock-file"
local mock_bufnr, mock_client_id = vim.uri_to_bufnr(mock_uri), 999
local mock_params
before_each(function()
s.get.returns({ client_id = 99 })
mock_params = { textDocument = { uri = mock_uri }, client_id = mock_client_id }
end)
after_each(function()
s.clear_actions:clear()
s.register_action:clear()
s.get:clear()
s.run_action:clear()
end)
describe("handler", function()
local handler = stub.new()
stub(generators, "run")
stub(u, "make_params")
after_each(function()
generators.run:clear()
u.make_params:clear()
handler:clear()
end)
describe("method == CODE_ACTION", function()
local method = methods.lsp.CODE_ACTION
it("should return immediately if null_ls_ignore flag is set", function()
local params = { _null_ls_ignore = true }
code_actions.handler(method, params, handler)
assert.stub(u.make_params).was_not_called()
assert.equals(params._null_ls_handled, nil)
end)
it("should call make_params with original params and internal method", function()
code_actions.handler(method, mock_params, handler)
mock_params.bufnr = mock_bufnr
mock_params._null_ls_handled = nil
assert.stub(u.make_params).was_called_with(mock_params, methods.internal.CODE_ACTION)
end)
it("should set handled flag on params", function()
code_actions.handler(method, mock_params, handler, 1)
assert.equals(mock_params._null_ls_handled, true)
end)
it("should call handler with arguments", function()
code_actions.handler(method, mock_params, handler)
local callback = generators.run.calls[1].refs[3]
callback({ { title = "actions" } })
-- wait for schedule_wrap
vim.wait(0)
assert.stub(handler).was_called_with({ { title = "actions" } })
end)
describe("get_actions", function()
it("should clear state actions", function()
code_actions.handler(method, mock_params, handler)
assert.stub(s.clear_actions).was_called()
end)
end)
describe("postprocess", function()
local postprocess, action
before_each(function()
action = {
title = "Mock action",
action = function()
print("I am an action")
end,
}
code_actions.handler(method, mock_params, handler)
postprocess = generators.run.calls[1].refs[2]
end)
it("should register action in state", function()
postprocess(action)
assert.equals(s.register_action.calls[1].refs[1].title, "Mock action")
end)
it("should set action command and delete function", function()
assert.truthy(action.action)
postprocess(action)
assert.equals(action.command, methods.internal.CODE_ACTION)
assert.equals(action.action, nil)
end)
end)
end)
end)
describe("method == EXECUTE_COMMAND", function()
local method = methods.lsp.EXECUTE_COMMAND
local handler = stub.new()
it("should set handled flag on params", function()
local params = {
command = methods.internal.CODE_ACTION,
title = "Mock action",
}
code_actions.handler(method, params, handler, 1)
assert.equals(params._null_ls_handled, true)
end)
it("should run action when command matches", function()
code_actions.handler(method, {
command = methods.internal.CODE_ACTION,
title = "Mock action",
}, handler, 1)
assert.stub(s.run_action).was_called_with("Mock action")
end)
it("should not run action when command does not match", function()
local params = { command = "someOtherCommand", title = "Mock action" }
code_actions.handler(method, params, handler, 1)
assert.stub(s.run_action).was_not_called()
assert.equals(params._null_ls_handled, nil)
end)
end)
end)
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local UserInputService = game:GetService("UserInputService")
local GuiService = game:GetService("GuiService")
local lib = ReplicatedStorage.lib
local PizzaAlpaca = require(lib.PizzaAlpaca)
local Signal = require(lib.Signal)
local InputHandler = PizzaAlpaca.GameModule:extend("InputHandler")
local createInputSpec = require(script.createInputSpec)
local errors = {
invalidActionError = "Action [%s] does not exist.",
multipleSignalError = "Cannot create multiple signals for action [%s]. Did you accidentally define two?",
}
local stateMap = {
[Enum.UserInputState.Begin] = {"_beforeBegan","began"},
[Enum.UserInputState.Change] = {"changed"},
[Enum.UserInputState.End] = {"_beforeEnded","ended"},
[Enum.UserInputState.Cancel] = {"canceled"},
}
local INPUT_DEBUG_PRINTS = false
function InputHandler:create()
self.actionSignals = {}
self.actionBindings = {}
self.inputSpec = createInputSpec()
self.logger = nil
end
function InputHandler:preInit()
self.logger = self.core:getModule("Logger"):createLogger(self)
for name, actionSpec in pairs(self.inputSpec) do
actionSpec.name = name
self:createBindings(actionSpec)
self:createActionSignal(name)
end
end
function InputHandler:init()
end
function InputHandler:postInit()
UserInputService.InputBegan:connect(function(input, robloxProcessed) self:onInput(input, robloxProcessed) end)
UserInputService.InputChanged:connect(function(input, robloxProcessed) self:onInput(input, robloxProcessed) end)
UserInputService.InputEnded:connect(function(input, robloxProcessed) self:onInput(input, robloxProcessed) end)
end
function InputHandler:getMousePos()
return UserInputService:GetMouseLocation() - Vector2.new(0,GuiService:GetGuiInset().Y)
end
function InputHandler:onInput(input, robloxProcessed)
-- find bindings that trigger on this input state
-- do they match type and keycode?
-- if so trigger their signals! :D
if robloxProcessed then return end
local inputType = input.UserInputType
local keyCode = input.KeyCode
for _, binding in pairs(self.actionBindings) do
local inputDescription = binding.inputDescription
local actionName = binding.actionName
local typeValid = inputType == inputDescription.type
local keyCodeValid = keyCode == inputDescription.keyCode or inputDescription.keyCode == nil
if
typeValid and
keyCodeValid
then
self:fireActionSignal(actionName, input)
end
end
end
function InputHandler:createBindings(actionSpec)
for _, inputDescription in pairs(actionSpec.inputs) do
local newBinding = {}
newBinding.inputDescription = inputDescription
newBinding.actionName = actionSpec.name
table.insert(self.actionBindings, newBinding)
end
end
function InputHandler:createActionSignal(name)
assert(not self.actionSignals[name], errors.multipleSignalError:format(name))
local _beforeBegan = Signal.new()
local _beforeEnded = Signal.new()
local beganSignal = Signal.new()
local changedSignal = Signal.new()
local endedSignal = Signal.new()
local canceledSignal = Signal.new()
local binding = {
_beforeBegan = _beforeBegan,
_beforeEnded = _beforeEnded,
began = beganSignal,
changed = changedSignal,
ended = endedSignal,
canceled = canceledSignal,
isActive = false,
}
_beforeBegan:connect(function()
binding.isActive = true
end)
_beforeEnded:connect(function()
binding.isActive = false
end)
canceledSignal:connect(function()
binding.isActive = false
end)
self.actionSignals[name] = binding
end
-- Returns a signal object for the action name, returns nil and warns you if action does not exist
function InputHandler:getActionSignal(name)
local signal = self.actionSignals[name]
if not signal then warn(errors.invalidActionError:format(name)) end
return signal
end
function InputHandler:fireActionSignal(name, input)
self:fireActionState(name, input.UserInputState, input)
if INPUT_DEBUG_PRINTS then
self.logger:log(("Action [%s] fired!"):format(name))
self.logger:log(
"Action payload:\n"..
"---- Position: "..tostring(input.Position).."\n"..
"---- Delta: "..tostring(input.Delta).."\n"..
"---- KeyCode: "..tostring(input.KeyCode).."\n"..
"---- Type - State: "..tostring(input.UserInputType).." - "..tostring(input.UserInputState).."\n"
)
end
end
function InputHandler:fireActionState(name, inputState, input)
local signalRoot = self.actionSignals[name]
assert(signalRoot, errors.invalidActionError:format(name))
for _,signalName in ipairs(stateMap[inputState]) do
local signal = signalRoot[signalName]
assert(signal, errors.invalidActionError:format(name))
signal:fire(input)
end
end
function InputHandler:simulateActivation(name)
self:fireActionState(name, Enum.UserInputState.Begin)
self:fireActionState(name, Enum.UserInputState.End)
end
return InputHandler |
---------------------------------------------------------------------------------------------------
-- HMI requests a missing cmdIcon be updated from mobile
-- Pre-conditions:
-- a. HMI and SDL are started
-- b. appID is registered and activated on SDL
-- c. mobile sends an addcommand with an image that does not exist
-- Steps:
-- User opens the menu, and the hmi sends UI.OnUpdateFile
-- Expected:
-- Mobile receives notification that the file should be updated
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/Smoke/commonSmoke')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
local missingFile = "missing_file.png"
local addCommandParams = {
cmdID = 50,
cmdIcon = {
value = missingFile,
imageType = "DYNAMIC"
},
menuParams = {
position = 4,
menuName = "Command Missing Image"
}
}
local onUpdateFileParams = {
fileName = missingFile
}
local hmiOnUpdateFileParams = {
fileName = missingFile,
appID = nil
}
--[[ Local Functions ]]
local function AddCommandNoImage()
local mobileSession = common.getMobileSession()
local hmi = common.getHMIConnection()
local cid = mobileSession:SendRPC("AddCommand", addCommandParams)
--hmi side: expect UI.AddCommand request
local hmiCommands = addCommandParams
hmiCommands.cmdIcon.value = common.getPathToFileInStorage(missingFile)
hmi:ExpectRequest("UI.AddCommand", hmiCommands)
:Do(function(_,data)
--hmi side: sending UI.AddCommand response
hmi:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect AddCommand response
mobileSession:ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
local function ShowMenuRequestFile()
local mobileSession = common.getMobileSession()
local hmi = common.getHMIConnection()
hmiOnUpdateFileParams.appID = common.getHMIAppId()
hmi:SendNotification("UI.OnUpdateFile", hmiOnUpdateFileParams)
mobileSession:ExpectNotification("OnUpdateFile", onUpdateFileParams)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Update Preloaded PT", common.updatePreloadedPT)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("RAI", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("Add command with non-existing image", AddCommandNoImage)
runner.Step("Show menu and request File", ShowMenuRequestFile)
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
-- _
--
-- E1 switches synth/sample
-- E2 switches operation
-- E3 changes operation value
-- K1/K2 switches property
-- K1+K2 toggles current track
-- K1+K3 toggles all tracks
-- K1+E1 copies shared props
-- K1+E3 moves through rand props
-- hold K1 to see mapped values
--
ER=require("er")
Lattice=require("lattice")
Tabutil=require("tabutil")
MusicUtil=require("musicutil")
Ero=include("aaaa/lib/Ero")
Eros=include("aaaa/lib/Eros")
Synth=include("aaaa/lib/Synth")
Sample=include("aaaa/lib/Sample")
Chord=include("aaaa/lib/Chord")
engine.name="Aaaa"
-- program state
s={
id_snd=1,-- index of the current synth or sample
id_op=1,-- index of the current operation (1-18)
id_prop=1,-- index of the current property (defined by the snd)
shift=false,
}
-- user state (saveable)
u={
snd={},
}
-- constants
local divs={1/32,1/16,1/8,1/4,1/2,1}
local divs_name={"tn","sn","en","qn","hn","wn"}
function init()
u.snd={}
-- for i=1,1 do
-- table.insert(u.snd,Synth:new("synth "..i))
-- end
-- for _, snd in ipairs(u.snd) do
-- snd.eros.trigger.ero[1].p=13
-- snd.eros.trigger.ero[1].m=30
-- snd.eros.trigger:recalculate()
-- snd.eros.trigger.div=1
-- snd.eros.pitch.div=1
-- snd.eros.pitch:random()
-- end
table.insert(u.snd,Sample:new("/home/we/dust/code/aaaa/samples/ch001.wav"))
u.snd[#u.snd].eros.trigger.ero[1].p=13
u.snd[#u.snd].eros.rate:random()
u.snd[#u.snd].eros.velocity:random()
u.snd[#u.snd].eros.trigger.div=1
u.snd[#u.snd].eros.trigger:recalculate()
table.insert(u.snd,Sample:new("/home/we/dust/code/aaaa/samples/kick005.wav"))
u.snd[#u.snd].eros.trigger.ero[1].p=4
u.snd[#u.snd].eros.rate:random()
u.snd[#u.snd].eros.velocity:random()
u.snd[#u.snd].eros.trigger.div=2
u.snd[#u.snd].eros.trigger:recalculate()
table.insert(u.snd,Chord:new("chords"))
u.snd[#u.snd].eros.trigger.ero[1].p=4
u.snd[#u.snd].eros.duration.ero[1].p=15
u.snd[#u.snd].eros.duration.ero[1].m=30
u.snd[#u.snd].eros.trigger:recalculate()
s.playing=false
s.lattice=Lattice:new{
ppqn=96
}
for id_div,div in ipairs(divs) do
local step=-1
s.lattice:new_pattern{
action=function(t)
step=step+1
for _,snd in ipairs(u.snd) do
-- sound only steps when its the correct division
-- and its currently playing
snd:next(id_div,step)
end
end,
division=div,
}
end
clock.run(function()
while true do
redraw()
clock.sleep(1/15)
end
end)
for _, snd in ipairs(u.snd) do
snd:toggle_playing()
end
if not s.playing then
s.lattice:hard_restart()
else
s.lattice:stop()
end
end
function enc(k,d)
if shift then
else
if k==1 then
s.id_snd=util.clamp(s.id_snd+sign(d),1,#u.snd)
elseif k==2 then
s.id_op=util.clamp(s.id_op+sign(d),1,18)
elseif k==3 then
change_op(sign(d))
end
end
end
function change_op(d)
local snd=u.snd[s.id_snd]
local prop=snd.props[s.id_prop]
local id_op_val=0
-- every operation should go here
id_op_val=id_op_val+1
if id_op_val==s.id_op then
snd:toggle_playing()
end
id_op_val=id_op_val+1
if id_op_val==s.id_op then
-- change number of steps
snd:delta(prop,{steps=d})
end
id_op_val=id_op_val+1
if id_op_val==s.id_op then
-- change div
snd:delta(prop,{div=d})
end
for i=1,4 do
-- operation
if i>1 then
id_op_val=id_op_val+1
if id_op_val==s.id_op then
-- change op
snd:delta(prop,{op=d},i)
end
end
-- m, p, w
id_op_val=id_op_val+1
if id_op_val==s.id_op then
snd:delta(prop,{m=d},i)
end
id_op_val=id_op_val+1
if id_op_val==s.id_op then
snd:delta(prop,{p=d},i)
end
id_op_val=id_op_val+1
if id_op_val==s.id_op then
snd:delta(prop,{w=d},i)
end
end
end
function key(k,z)
if k==1 then
shift=z==1
end
if k>1 and shift then
if k==2 then
elseif k==3 then
if not s.playing then
s.lattice:hard_restart()
else
s.lattice:stop()
end
end
elseif k>1 and not shift and z==1 then
local d=k*2-5
s.id_prop=util.clamp(s.id_prop+d,1,#u.snd[s.id_snd].props)
end
end
function redraw()
screen.clear()
local snd=u.snd[s.id_snd]
if snd==nil then
do return end
end
if snd.eros==nil then
do return end
end
local prop=snd.props[s.id_prop]
screen.level(15)
screen.rect(1,1,46,63)
screen.stroke()
screen.level(15)
screen.rect(1,1,46,8)
screen.fill()
screen.level(0)
screen.move(23,6)
screen.text_center(snd.name)
if s.id_op==1 then
screen.level(15)
else
screen.level(2)
end
screen.move(10,16)
screen.text_center(snd.playing and ">" or "||")
if s.id_op==2 then
screen.level(15)
else
screen.level(2)
end
screen.move(23,16)
screen.text_center(snd.eros[prop].steps)
if s.id_op==3 then
screen.level(15)
else
screen.level(2)
end
screen.move(37,16)
screen.text_center(divs_name[snd.eros[prop].div])
-- draw rectangles
local res=snd.eros[prop]:get_res()
for i,r in ipairs(res) do
screen.level(2)
if snd.eros[prop].step==i then
screen.level(15)
end
rabs=math.abs(r)
local x=49+(5*(i-1))
local y=32-rabs
if r<0 then
y=33
end
screen.rect(x,y,4,rabs)
screen.fill()
end
for i,_ in ipairs(res) do
screen.level(2)
if snd.eros[prop].step==i then
screen.level(15)
end
local x=49+(5*(i-1))
local y=33
screen.move(x,y)
screen.line(x+4,y)
screen.stroke()
end
-- write down the actual values
local xp=8
local yp=21
local rowh=9
local roww=11
local id_op_val=3
for i=1,4 do
local ero=snd.eros[prop]:get(i)
-- operation
if i>1 then
id_op_val=id_op_val+1
if id_op_val==s.id_op then
screen.level(15)
else
screen.level(2)
end
local x=xp-2
local y=yp+(i-1)*rowh
screen.move(x,y)
screen.text_center(ero.op)
end
-- m, p, w
vs={ero.m,ero.p,ero.w}
for j,v in ipairs(vs) do
id_op_val=id_op_val+1
if id_op_val==s.id_op then
screen.level(15)
else
screen.level(2)
end
local x=xp+8+(j-1)*roww
local y=yp+5+(i-1)*rowh
screen.move(x,y)
screen.text_center(v)
end
end
screen.level(15)
screen.rect(1,56,46,8)
screen.fill()
screen.level(0)
screen.move(23,62)
screen.text_center(prop)
screen.update()
end
function rerun()
norns.script.load(norns.state.script)
end
function r()
rerun()
end
function sign(x)
if x>0 then
do return 1 end
elseif x<0 then
do return-1 end
end
return 0
end |
-- javascript = typescript
local typescript = require("refactoring.code_generation.langs.typescript")
return typescript
|
object_tangible_food_generic_dish_thakitillo = object_tangible_food_generic_shared_dish_thakitillo:new {
}
ObjectTemplates:addTemplate(object_tangible_food_generic_dish_thakitillo, "object/tangible/food/generic/dish_thakitillo.iff")
|
------------------------------------
--- Drawing custom paintjobs ---
------------------------------------
local client_path = 'items/paintjob/';
function onClientElementDataChange(name)
if name ~= 'gcshop.custompaintjob' then return end
local val = getElementData(source, 'gcshop.custompaintjob')
if val ~= nil then
addShaders(source, val)
--outputDebugString("c add custom paintjob")
else
removeWorldTexture(source)
--outputDebugString("c rem custom paintjob")
end
end
addEventHandler('onClientElementDataChange', root, onClientElementDataChange)
local textureVehicle = {
[500] = { "vehiclegrunge256","*map*" },
[520] = "hydrabody256",
[552] = { "vehiclegrunge256","*map*" },
[584] = {"petrotr92interior128","petroltr92decal256"},
[521] = "fcr90092body128",
[405] = { "vehiclegrunge256","*map*" },
[585] = { "vehiclegrunge256","*map*" },
[437] = {"vehiclegrunge256","*map*","bus92decals128","coach92interior128","vehiclegeneric256"},
[453] = "vehiclegrunge256","*map*",
[469] = "sparrow92body128",
[485] = "vehiclegrunge256","*map*",
[501] = "rcgoblin92texpage128",
[522] = {"nrg50092body128","vehiclegeneric256" },
[554] = "vehiclegrunge256","*map*",
[586] = {"wayfarerbody8bit128"},
[523] = "copbike92body128",
[406] = "vehiclegrunge256","*map*" ,
[587] = "vehiclegrunge256","*map*" ,
[438] = { "vehiclegrunge256","*map*" },
[454] = { "vehiclegrunge256","*map*" },
[470] = { "vehiclegrunge256","*map*" },
[486] = { "vehiclegrunge256","*map*" },
[502] = { "vehiclegrunge256","*map*" },
[524] = { "vehiclegrunge256","*map*" },
[556] = "monstera92body256a",
[588] = "hotdog92body256",
[525] = { "vehiclegrunge256","*map*" },
[407] = { "vehiclegrunge256","*map*" },
[589] = { "vehiclegrunge256","*map*" },
[439] = { "vehiclegrunge256","*map*" },
[455] = { "vehiclegrunge256","*map*" },
[471] = { "vehiclegrunge256","*map*" },
[487] = "maverick92body128",
[503] = { "vehiclegrunge256","*map*" },
[526] = { "vehiclegrunge256","*map*" },
[558] = { "vehiclegrunge256","*map*","@hite" },
[590] = "freibox92texpage256",
[527] = { "vehiclegrunge256","*map*" },
[408] = { "vehiclegrunge256","*map*" },
[424] = { "vehiclegrunge256","*map*" },
[440] = {"rumpo92adverts256","vehiclegrunge256"},
[456] = { "yankee92logos", "vehiclegrunge256","*map*" },
[472] = { "vehiclegrunge256","*map*" },
[488] = { "vehiclegrunge256","*map*","polmavbody128a"},
[504] = { "vehiclegrunge256","*map*" },
[528] = { "vehiclegrunge256","*map*" },
[560] = { "vehiclegrunge256","*map*","#emapsultanbody256" },
[592] = {"andromeda92wing", "andromeda92body"},
[529] = { "vehiclegrunge256","*map*" },
[409] = { "vehiclegrunge256","*map*" },
[593] = "dodo92body8bit256",
[441] = "vehiclegeneric256",
[457] = { "vehiclegrunge256","*map*" },
[473] = { "vehiclegrunge256","*map*" },
[489] = { "vehiclegrunge256","*map*" },
[505] = { "vehiclegrunge256","*map*" },
[530] = { "vehiclegrunge256","*map*" },
[562] = { "vehiclegrunge256","*map*" },
[594] = "rccam92pot64",
[531] = { "vehiclegrunge256","*map*" },
[410] = { "vehiclegrunge256","*map*" },
[426] = { "vehiclegrunge256","*map*" },
[442] = { "vehiclegrunge256","*map*" },
[458] = { "vehiclegrunge256","*map*" },
[474] = { "vehiclegrunge256","*map*" },
[490] = { "vehiclegrunge256","*map*" },
[506] = { "vehiclegrunge256","*map*" },
[532] = "combinetexpage128",
[564] = "rctiger92body128",
[596] = { "vehiclegrunge256","*map*" },
[533] = { "vehiclegrunge256","*map*" },
[411] = { "vehiclegrunge256","*map*" },
[597] = { "vehiclegrunge256","*map*" },
[443] = { "vehiclegrunge256","*map*" },
[459] = { "vehiclegrunge256","*map*" },
[475] = { "vehiclegrunge256","*map*" },
[491] = { "vehiclegrunge256","*map*" },
[507] = { "vehiclegrunge256","*map*" },
[534] = { "vehiclegrunge256","*map*","*map*" },
[566] = { "vehiclegrunge256","*map*" },
[598] = { "vehiclegrunge256","*map*" },
[535] = { "vehiclegrunge256","*map*","#emapslamvan92body128" },
[567] = { "vehiclegrunge256","*map*","*map*" },
[599] = { "vehiclegrunge256","*map*" },
[444] = { "vehiclegrunge256","*map*" },
[460] = {"skimmer92body128","vehiclegrunge256","*map*"},
[476] = "rustler92body256",
[492] = { "vehiclegrunge256","*map*" },
[508] = { "vehiclegrunge256","*map*" },
[536] = { "vehiclegrunge256","*map*" },
[568] = "bandito92interior128",
[600] = { "vehiclegrunge256","*map*" },
[591] = { "vehiclegrunge256","*map*" },
[537] = { "vehiclegrunge256","*map*" },
[413] = { "vehiclegrunge256","*map*" },
[601] = { "vehiclegrunge256","*map*" },
[445] = { "vehiclegrunge256","*map*" },
[461] = { "vehiclegrunge256","*map*" },
[477] = { "vehiclegrunge256","*map*" },
[493] = { "vehiclegeneric256" },
[509] = { "vehiclegrunge256","*map*" },
[538] = { "vehiclegrunge256","*map*" },
[570] = { "vehiclegrunge256","*map*" },
[602] = { "vehiclegrunge256","*map*" },
[605] = { "vehiclegrunge256","*map*" },
[425] = "hunterbody8bit256a",
[415] = { "vehiclegrunge256","*map*" },
[611] = { "vehiclegrunge256","*map*" },
[569] = { "vehiclegrunge256","*map*" },
[539] = { "vehiclegrunge256","*map*" },
[414] = { "vehiclegrunge256","*map*" },
[430] = {"predator92body128","vehiclegrunge256","*map*"},
[446] = { "vehiclegrunge256","*map*" },
[462] = { "vehiclegrunge256","*map*" },
[478] = { "vehiclegrunge256","*map*" },
[494] = { "vehiclegrunge256","*map*" },
[510] = { "vehiclegrunge256","*map*" },
[540] = { "vehiclegrunge256","*map*" },
[572] = { "vehiclegrunge256","*map*" },
[604] = { "vehiclegrunge256","*map*" },
[557] = "monsterb92body256a",
[607] = { "vehiclegrunge256","*map*" },
[579] = { "vehiclegrunge256","*map*" },
[400] = { "vehiclegrunge256","*map*" },
[404] = { "vehiclegrunge256","*map*" },
[541] = { "vehiclegrunge256","*map*" },
[573] = { "vehiclegrunge256","*map*" },
[431] = {"vehiclegrunge256","*map*","bus92decals128","dash92interior128"},
[447] = "sparrow92body128",
[463] = { "vehiclegrunge256","*map*" },
[479] = { "vehiclegrunge256","*map*" },
[495] = { "vehiclegrunge256","*map*" },
[511] = {"vehiclegrunge256","*map*","beagle256"},
[542] = { "vehiclegrunge256","*map*" },
[574] = { "vehiclegrunge256","*map*" },
[606] = { "vehiclegrunge256","*map*" },
[555] = { "vehiclegrunge256","*map*" },
[563] = "raindance92body128",
[428] = { "vehiclegrunge256","*map*" },
[565] = { "vehiclegrunge256","*map*","@hite" },
[561] = { "vehiclegrunge256","*map*" },
[543] = { "vehiclegrunge256","*map*" },
[416] = { "vehiclegrunge256","*map*" },
[432] = "rhino92texpage256",
[448] = { "vehiclegrunge256","*map*" },
[464] = "rcbaron92texpage64",
[480] = { "vehiclegrunge256","*map*" },
[496] = { "vehiclegrunge256","*map*" },
[512] = "cropdustbody256",
[544] = { "vehiclegrunge256","*map*" },
[576] = { "vehiclegrunge256","*map*" },
[608] = { "vehiclegrunge256","*map*" },
[559] = { "vehiclegrunge256","*map*" },
[429] = { "vehiclegrunge256","*map*" },
[571] = { "vehiclegrunge256","*map*" },
[427] = { "vehiclegrunge256","*map*" },
[513] = "stunt256",
[545] = { "vehiclegrunge256","*map*" },
[577] = "at400_92_256",
[433] = { "vehiclegrunge256","*map*" },
[449] = { "vehiclegrunge256","*map*" },
[465] = "rcraider92texpage128",
[481] = "vehiclegeneric256",
[497] = {"polmavbody128a", "vehiclegrunge256","*map*"},
[514] = { "vehiclegrunge256","*map*" },
[546] = { "vehiclegrunge256","*map*" },
[578] = { "vehiclegrunge256","*map*" },
[610] = { "vehiclegrunge256","*map*" },
[603] = { "vehiclegrunge256","*map*" },
[402] = { "vehiclegrunge256","*map*" },
[412] = { "vehiclegrunge256","*map*" },
[575] = { "vehiclegrunge256","*map*","remapbroadway92body128" },
[515] = { "vehiclegrunge256","*map*" },
[547] = { "vehiclegrunge256","*map*" },
[418] = { "vehiclegrunge256","*map*" },
[434] = { "hotknifebody128a", "hotknifebody128b"},
[450] = { "vehiclegrunge256","*map*" },
[466] = { "vehiclegrunge256","*map*" },
[482] = { "vehiclegrunge256","*map*" },
[498] = { "vehiclegrunge256","*map*" },
[516] = { "vehiclegrunge256","*map*" },
[548] = {"cargobob92body256" ,"vehiclegrunge256","*map*"},
[580] = { "vehiclegrunge256","*map*" },
[583] = { "vehiclegrunge256","*map*" },
[422] = { "vehiclegrunge256","*map*" },
[423] = { "vehiclegrunge256","*map*" },
[403] = { "vehiclegrunge256","*map*" },
[609] = { "vehiclegrunge256","*map*" },
[517] = { "vehiclegrunge256","*map*" },
[549] = { "vehiclegrunge256","*map*" },
[419] = { "vehiclegrunge256","*map*" },
[435] = "artict1logos",
[451] = { "vehiclegrunge256","*map*" },
[467] = { "vehiclegrunge256","*map*" },
[483] = { "vehiclegrunge256","*map*" },
[499] = { "vehiclegrunge256","*map*" },
[518] = { "vehiclegrunge256","*map*" },
[550] = { "vehiclegrunge256","*map*" },
[582] = { "vehiclegrunge256","*map*" },
[421] = { "vehiclegrunge256","*map*" },
[595] = { "vehiclegrunge256","*map*" },
[553] = { "vehiclegrunge256","*map*","nevada92body256"},
[581] = "bf40092body128",
[417] = "leviathnbody8bit256",
[519] = "shamalbody256",
[551] = { "vehiclegrunge256","*map*" },
[420] = { "vehiclegrunge256","*map*" },
[436] = { "vehiclegrunge256","*map*" },
[452] = { "vehiclegrunge256","*map*" },
[468] = { "vehiclegrunge256","*map*" },
[484] = { "vehiclegrunge256","*map*", "vehiclegeneric256","marquis92interior128" },
[401] = { "vehiclegrunge256","*map*" },}
local removeTable = {}
function buildRemoveTable() -- Gets all used textures and puts them in a table for a remove list.
local function isTextureInTable(texture)
for _,texture2 in ipairs(removeTable) do
if texture == texture2 then
return true
end
end
return false
end
for _,texture in pairs(textureVehicle) do
if type(texture) == "table" then
for _,texture2 in ipairs(texture) do
if not isTextureInTable(texture2) then
table.insert(removeTable,texture2)
end
end
else
if not isTextureInTable(texture) then
table.insert(removeTable,texture)
end
end
end
end
addEventHandler("onClientResourceStart",resourceRoot,buildRemoveTable)
local shaders = {}
function addShaders(player, val, newUpload)
local veh = getPedOccupiedVehicle(player) or nil
if not veh or not val or not fileExists(client_path .. val .. '.bmp') then return end
if shaders[player] then
if shaders[player][3] ~= val or newUpload then -- Different PJ then before
-- outputDebugString("Using Different PJ")
remShaders ( player )
local texture, shader = createPJShader(val)
-- outputConsole('adding shader for ' .. getPlayerName(player))
shaders[player] = {texture, shader,val}
applyPJtoVehicle(shader,veh)
return
elseif shaders[player][3] == val then -- Same PJ as before
-- outputDebugString("Using Same PJ")
local texture = shaders[player][1]
local shader = shaders[player][2]
applyPJtoVehicle(shader,veh)
return
end
else -- New PJ
-- outputDebugString("Using New PJ")
remShaders ( player )
local texture, shader = createPJShader(val)
-- outputConsole('adding shader for ' .. getPlayerName(player))
shaders[player] = {texture, shader,val}
applyPJtoVehicle(shader,veh)
return
end
end
function removeWorldTexture(player)
if not shaders[player] then return end
if not shaders[player][2] then return end
local shader = shaders[player][2]
if not shader then return end
local veh = getPedOccupiedVehicle(player)
engineRemoveShaderFromWorldTexture(shader,"vehiclegeneric256",veh)
for _,texture in pairs(removeTable) do
engineRemoveShaderFromWorldTexture(shader,texture,veh)
end
end
function applyPJtoVehicle(shader,veh)
if not veh then return false end
if not shader then return false end
local player = getVehicleOccupant(veh)
if not player then return end
removeWorldTexture(player,shader)
local vehID = getElementModel(veh)
local apply = false
if type(textureVehicle[vehID]) == "table" then -- texturegrun -- textureVehicle[vehID]
for _, texture in ipairs(textureVehicle[vehID]) do
apply = engineApplyShaderToWorldTexture(shader,texture,veh)
end
else
apply = engineApplyShaderToWorldTexture(shader,textureVehicle[vehID],veh)
end
return apply
end
function createPJShader(val)
if not val then return false end
local texture = dxCreateTexture ( client_path .. val .. '.bmp' )
local shader, tec = dxCreateShader( client_path .. "paintjob.fx" )
--bit of sanity checking
if not shader then
outputConsole( "Could not create shader. Please use debugscript 3" )
destroyElement( texture )
return false
elseif not texture then
outputConsole( "loading texture failed" )
destroyElement ( shader )
tec = nil
return false
end
dxSetShaderValue ( shader, "gTexture", texture )
return texture,shader,tec
end
function remShaders ( player )
if shaders[player] and isElement(shaders[player][2]) then
destroyElement(shaders[player][1])
destroyElement(shaders[player][2])
shaders[player]=nil
-- outputConsole('removed shader for ' .. getPlayerName(player))
end
end
function refreshShaders()
for _,player in pairs(shaders) do
if isElement(player[1]) then destroyElement(player[1]) end
if isElement(player[2]) then destroyElement(player[2]) end
end
shaders = {}
end
addEvent("clientRefreshShaderTable",true)
addEventHandler("clientRefreshShaderTable",root,refreshShaders)
function onGCShopLogout (forumID)
remShaders ( source )
end
addEventHandler("onGCShopLogout", root, onGCShopLogout)
function onClientStart()
triggerServerEvent('clientSendPaintjobs', root, root, localPlayer)
end
addEventHandler('onClientResourceStart', resourceRoot, onClientStart)
-- local prev
-- setTimer( function()
-- local veh = getPedOccupiedVehicle(localPlayer)
-- if prev then
-- if not (veh and isElement(veh)) then
-- prev = nil
-- remShaders(localPlayer)
-- elseif prev ~= getElementModel(veh) then
-- prev = getElementModel(veh)
-- remShaders(localPlayer)
-- end
-- elseif veh and getElementModel(veh) then
-- prev = getElementModel(veh)
-- end
-- end, 50, 0)
--------------------------------------
--- Uploading custom paintjobs ---
--------------------------------------
local allowedExtensions = {".png",".bmp",".jpg"}
function gcshopRequestPaintjob(imageMD5, forumID, filename, id)
if not player_perks[4] then return outputChatBox('Buy the perk!', 255, 0, 0); end
--outputDebugString('c: Requesting paintjob ' ..tostring( filename) .. ' ' .. tostring(forumID) .. ' ' .. getPlayerName(localPlayer))
if string.find(filename,".tinypic.com/") or string.find(filename,"i.imgur.com/") or string.find(filename,".postimg.org/") then -- If filename is hosting URL
local forbiddenFile = 0
for _,ext in ipairs(allowedExtensions) do
if string.find(filename,ext) then
forbiddenFile = forbiddenFile + 1
end
end
if forbiddenFile ~= 1 then -- If file has forbidden extension
outputChatBox('Please use a different file extension (only .png, .jpg and .bmp allowed!)', 255, 0, 0)
elseif forbiddenFile == 1 then
triggerServerEvent("serverReceiveHostingURL",localPlayer,filename,id)
end
else -- Normal upload from disk
if not fileExists(filename) then
-- File not found, abort
--outputDebugString('c: File not found ' .. tostring(filename) .. ' ' .. tostring(forumID) .. ' ' .. getPlayerName(localPlayer))
outputChatBox('Custom paintjob image "' .. tostring(filename) .. '" not found!', 255, 0, 0)
else
local localMD5 = getMD5(filename)
if localMD5 == imageMD5 then
-- image didn't chance, tell the server to use the old custom texture
--outputDebugString('c: Same image, not uploading ' .. tostring(localMD5) .. ' ' .. tostring(imageMD5) .. ' ' .. getPlayerName(localPlayer))
triggerServerEvent( 'receiveImage', localPlayer, false, id)
elseif not isValidImage(filename) then
outputChatBox('Custom paintjob image "' .. tostring(filename) .. '" is not a valid image!!', 255, 0, 0)
else
-- a new image needs to be uploaded
--outputDebugString('c: New image ' .. tostring(localMD5) .. ' ' .. tostring(imageMD5) .. ' ' .. getPlayerName(localPlayer))
local file = fileOpen(filename, true)
local image = fileRead(file, fileGetSize(file))
fileClose(file)
triggerLatentServerEvent('receiveImage', 1000000, localPlayer, image, id)
end
end
end
end
addEvent('gcshopRequestPaintjob', true)
addEventHandler('gcshopRequestPaintjob', resourceRoot, gcshopRequestPaintjob)
function isValidImage(image)
local isImage = guiCreateStaticImage( 1.1, 1.1, 0.01, 0.01, image, true);
if not isImage then return false end
destroyElement(isImage);
local file = fileOpen(image, true);
local size = fileGetSize(file);
fileClose(file);
if size <= 1000000/2 then
return true;
end
end
----------------------------------------
--- Downloading custom paintjobs ---
--- from server ---
----------------------------------------
function serverPaintjobsMD5 ( md5list )
local requests = {}
for forumID, playermd5list in pairs(md5list) do
for pid, imageMD5 in pairs(playermd5list) do
local filename = tostring(forumID) .. '-' .. pid .. '.bmp'
if not fileExists(client_path .. filename) or imageMD5 ~= getMD5(client_path .. filename) then
table.insert(requests, filename)
--outputDebugString('c: Requesting paintjob ' .. tostring(filename) .. ' ' .. tostring(fileExists(filename) and getMD5(filename)) .. ' ' .. tostring(imageMD5) .. ' ' .. getPlayerName(localPlayer))
end
end
end
if #requests > 0 then
triggerServerEvent( 'clientRequestsPaintjobs', localPlayer, requests)
end
for k, player in ipairs(getElementsByType'player') do
local val = getElementData(player, 'gcshop.custompaintjob')
if val ~= nil then
addShaders(player, val)
else
remShaders(player)
end
end
end
addEvent('serverPaintjobsMD5', true)
addEventHandler('serverPaintjobsMD5', resourceRoot, serverPaintjobsMD5)
function serverSendsPaintjobs ( files )
for filename, image in pairs(files) do
local file = fileCreate(client_path .. filename)
fileWrite(file, image)
fileClose(file)
--outputDebugString('c: Received paintjob ' .. tostring(filename) .. ' ' .. getPlayerName(localPlayer))
end
if previewPJ then previewPJ() end
for k, player in ipairs(getElementsByType'player') do
local val = getElementData(player, 'gcshop.custompaintjob')
if val ~= nil then
addShaders(player, val)
else
remShaders(player)
end
end
end
addEvent('serverSendsPaintjobs', true)
addEventHandler('serverSendsPaintjobs', resourceRoot, serverSendsPaintjobs)
function getMD5 ( filename )
if not fileExists(filename) then
error("getMD5: File " .. filename .. ' not found!', 2)
end
local file = fileOpen(filename, true)
local image = fileRead(file, fileGetSize(file))
fileClose(file)
return md5(image)
end |
local M = {}
function M.get(cp)
return {
markdownHeadingDelimiter = { fg = cp.catppuccin6, style = "bold" },
markdownCode = { fg = cp.catppuccin2 },
markdownCodeBlock = { fg = cp.catppuccin2 },
markdownH1 = { fg = cp.catppuccin4, style = "bold" },
markdownH2 = { fg = cp.catppuccin9, style = "bold" },
markdownLinkText = { fg = cp.catppuccin9, style = "underline" },
}
end
return M
|
-----------------------------------------
-- Spell: PHALANX
-- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point
-- Phalanx II value per point is '3' This is a constant set in the table 'merits'
-----------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/status")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local enhskill = caster:getSkillLevel(tpz.skill.ENHANCING_MAGIC)
local final = 0
local merits = caster:getMerit(tpz.merit.PHALANX_II)
local duration = calculateDuration(90 + 10 * merits, spell:getSkillType(), spell:getSpellGroup(), caster, target)
duration = calculateDurationForLvl(duration, 75, target:getMainLvl())
final = enhskill / 25 + merits + 1
if target:addStatusEffect(tpz.effect.PHALANX,final,0,duration) then
spell:setMsg(tpz.msg.basic.MAGIC_GAIN_EFFECT)
else
spell:setMsg(tpz.msg.basic.MAGIC_NO_EFFECT)
end
return tpz.effect.PHALANX
end
|
/*--------------------------------------------------------------------------\
| THIS ENTIRE PLUGIN IS CREATED BY VIOMI |
| PLEASE DO NOT COPY OR SELL ANY CODE IN HERE WITHOUT PERMISSION FROM VIOMI |
| Contact: viomi@openmailbox.org |
\--------------------------------------------------------------------------*/
local PLUGIN = PLUGIN
-- Called when the scoreboard's class players should be sorted.
function Schema:ScoreboardSortClassPlayers(class, a, b)
if (class == mpfname or class == otaname) then
local rankA = Schema:GetPlayerCombineRank(a)
local rankB = Schema:GetPlayerCombineRank(b)
if (rankA == rankB) then
return a:Name() < b:Name()
else
return rankA > rankB
end
end
end
-- Called when a player's scoreboard class is needed.
function Schema:GetPlayerScoreboardClass(player)
local faction = player:GetFaction()
local customClass = player:GetSharedVar("customClass")
if (customClass != "") then
return customClass;
end;
if (faction == FACTION_MPF) then
if (Schema:PlayerIsCombine(Clockwork.Client) or Clockwork.Client:IsAdmin() or !mpfhide) then
return mpfname
else
return false
end
elseif (faction == FACTION_OTA) then
if (Schema:PlayerIsCombine(Clockwork.Client) or Clockwork.Client:IsAdmin() or !mpfhide) then
return otaname
else
return false
end
end
end |
local ok, catppuccino = pcall(require, "catppuccino")
if not ok then
return
end
catppuccino.setup {
colorscheme = O.default.theme,
transparency = false,
term_colors = false,
styles = {
comments = "italic",
functions = "italic",
keywords = "italic",
strings = "NONE",
variables = "NONE",
},
integrations = {
treesitter = true,
native_lsp = {
enabled = true,
styles = {
errors = "italic",
hints = "italic",
warnings = "italic",
information = "italic",
},
},
lsp_trouble = false,
lsp_saga = false,
gitgutter = false,
gitsigns = true,
telescope = false,
nvimtree = {
enabled = false,
show_root = false,
},
which_key = false,
indent_blankline = false,
dashboard = false,
neogit = false,
vim_sneak = false,
fern = false,
barbar = false,
bufferline = false,
markdown = false,
},
}
catppuccino.load()
|
-- http://industriousone.com/scripting-reference
local action = _ACTION or ""
local CUDA_PATH = os.getenv("CUDA_PATH");
solution "island"
location (action)
configurations { "Debug", "Release" }
platforms {"x64", "x86"}
language "C"
kind "StaticLib"
filter "action:vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "x86"
libdirs {
path.join(action, "x86")
}
targetdir (path.join(action, "x86"))
configuration "x64"
libdirs {
path.join(action, "x64"),
}
targetdir (path.join(action, "x64"))
filter "system:macosx"
defines {
"_MACOSX",
}
configuration "Debug"
defines { "DEBUG" }
symbols "On"
targetsuffix "-d"
configuration "Release"
defines { "NDEBUG" }
flags { "No64BitChecks" }
editandcontinue "Off"
optimize "Speed"
optimize "On"
editandcontinue "Off"
project "imgui"
includedirs {
"3rdparty/cimgui/cimgui",
"3rdparty/cimgui/imgui",
}
files {
"3rdparty/cimgui/cimgui/*.h",
"3rdparty/cimgui/cimgui/*.cpp",
"3rdparty/cimgui/imgui/*",
}
project "glfw"
includedirs {
"3rdparty/glfw/include"
}
files {
"3rdparty/glfw/include/GLFW/*.h",
"3rdparty/glfw/src/context.c",
"3rdparty/glfw/src/init.c",
"3rdparty/glfw/src/input.c",
"3rdparty/glfw/src/monitor.c",
"3rdparty/glfw/src/window.c",
"3rdparty/glfw/src/vulkan.c",
"3rdparty/glfw/src/osmesa_context.*",
}
defines { "_GLFW_USE_OPENGL" }
filter "system:windows"
defines { "_GLFW_WIN32", }
files {
"3rdparty/glfw/src/win32*",
"3rdparty/glfw/src/egl_context*",
"3rdparty/glfw/src/wgl_context*",
}
filter "system:macosx"
defines {
"_GLFW_COCOA",
}
files {
"3rdparty/glfw/src/cocoa*",
"3rdparty/glfw/src/nsgl*",
"3rdparty/glfw/src/posix*",
}
filter "system:linux"
defines {
"_GLFW_X11",
}
files {
"3rdparty/glfw/src/linux*",
"3rdparty/glfw/src/glx*",
"3rdparty/glfw/src/x11*",
"3rdparty/glfw/src/egl_context*",
"3rdparty/glfw/src/posix*",
"3rdparty/glfw/src/xkb*",
}
project "v7"
files {
"3rdparty/v7/*.h",
"3rdparty/v7/*.c"
}
project "glew"
includedirs {
"3rdparty/glew",
}
files {
"3rdparty/glew/GL/*.h",
"3rdparty/glew/*.c"
}
defines {
"GLEW_STATIC",
"GLEW_NO_GLU",
}
project "nanovg"
files { "3rdparty/nanovg/src/*" }
project "libuv"
includedirs {
"3rdparty/libuv/include",
"3rdparty/libuv/src",
}
files {
"3rdparty/libuv/include/*.h",
"3rdparty/libuv/src/*.c"
}
filter "system:linux"
files {
"3rdparty/libuv/src/unix/async.c",
"3rdparty/libuv/src/unix/atomic-ops.h",
"3rdparty/libuv/src/unix/core.c",
"3rdparty/libuv/src/unix/dl.c",
"3rdparty/libuv/src/unix/fs.c",
"3rdparty/libuv/src/unix/getaddrinfo.c",
"3rdparty/libuv/src/unix/getnameinfo.c",
"3rdparty/libuv/src/unix/internal.h",
"3rdparty/libuv/src/unix/loop-watcher.c",
"3rdparty/libuv/src/unix/loop.c",
"3rdparty/libuv/src/unix/pipe.c",
"3rdparty/libuv/src/unix/poll.c",
"3rdparty/libuv/src/unix/process.c",
"3rdparty/libuv/src/unix/signal.c",
"3rdparty/libuv/src/unix/spinlock.h",
"3rdparty/libuv/src/unix/stream.c",
"3rdparty/libuv/src/unix/tcp.c",
"3rdparty/libuv/src/unix/thread.c",
"3rdparty/libuv/src/unix/timer.c",
"3rdparty/libuv/src/unix/tty.c",
"3rdparty/libuv/src/unix/udp.c",
"3rdparty/libuv/src/unix/linux-core.c",
"3rdparty/libuv/src/unix/linux-inotify.c",
"3rdparty/libuv/src/unix/linux-syscalls.c",
"3rdparty/libuv/src/unix/linux-syscalls.h",
"3rdparty/libuv/src/unix/procfs-exepath.c",
"3rdparty/libuv/src/unix/proctitle.c",
"3rdparty/libuv/src/unix/sysinfo-loadavg.c",
"3rdparty/libuv/src/unix/sysinfo-memory.c",
}
filter "system:windows"
files {
"3rdparty/libuv/src/win/*.c"
}
filter "system:macosx"
files {
"3rdparty/libuv/src/unix/async.c",
"3rdparty/libuv/src/unix/atomic-ops.h",
"3rdparty/libuv/src/unix/core.c",
"3rdparty/libuv/src/unix/dl.c",
"3rdparty/libuv/src/unix/fs.c",
"3rdparty/libuv/src/unix/getaddrinfo.c",
"3rdparty/libuv/src/unix/getnameinfo.c",
"3rdparty/libuv/src/unix/internal.h",
"3rdparty/libuv/src/unix/loop-watcher.c",
"3rdparty/libuv/src/unix/loop.c",
"3rdparty/libuv/src/unix/pipe.c",
"3rdparty/libuv/src/unix/poll.c",
"3rdparty/libuv/src/unix/process.c",
"3rdparty/libuv/src/unix/signal.c",
"3rdparty/libuv/src/unix/spinlock.h",
"3rdparty/libuv/src/unix/stream.c",
"3rdparty/libuv/src/unix/tcp.c",
"3rdparty/libuv/src/unix/thread.c",
"3rdparty/libuv/src/unix/timer.c",
"3rdparty/libuv/src/unix/tty.c",
"3rdparty/libuv/src/unix/udp.c",
"3rdparty/libuv/src/unix/bsd-ifaddrs.c",
"3rdparty/libuv/src/unix/darwin.c",
"3rdparty/libuv/src/unix/darwin-proctitle.c",
"3rdparty/libuv/src/unix/fsevents.c",
"3rdparty/libuv/src/unix/kqueue.c",
"3rdparty/libuv/src/unix/proctitle",
}
project "island"
includedirs {
"include",
"3rdparty/stb",
"3rdparty/glfw/include",
"3rdparty/glew",
"3rdparty/cimgui/cimgui",
"3rdparty/cimgui/imgui",
}
files {
"3rdparty/stb/*",
"3rdparty/stb/stb/*",
"include/**",
"src/**",
}
defines {
"GLEW_NO_GLU",
}
project "Remotery"
files {
"3rdparty/Remotery/lib/*",
}
defines {
"RMT_USE_OPENGL",
}
if CUDA_PATH ~= nil then
includedirs {
path.join("$(CUDA_PATH)", "include"),
}
defines {
"RMT_USE_CUDA",
}
end
-- project "soloud"
-- language "C++"
-- includedirs {
-- "3rdparty/soloud/include",
-- }
-- files {
-- "3rdparty/soloud/inlcude/*.h",
-- "3rdparty/soloud/src/core/*.cpp",
-- "3rdparty/soloud/src/audiosource/**",
-- "3rdparty/soloud/src/filter/*.cpp",
-- "3rdparty/soloud/src/c_api/*.cpp",
-- }
-- filter "system:windows"
-- defines {"WITH_WINMM"}
-- files {
-- "3rdparty/soloud/src/backend/winmm/*.cpp"
-- }
-- filter "system:linux"
-- defines {"WITH_OSS"}
-- files {
-- "3rdparty/soloud/src/backend/oss/*.cpp"
-- }
-- filter "system:macosx"
-- defines {
-- "WITH_COREAUDIO",
-- }
-- files {
-- "3rdparty/soloud/src/backend/coreaudio/*.cpp"
-- }
function create_example_project( example_path )
leaf_name = string.sub(example_path, string.len("examples/") + 1);
project (leaf_name)
kind "ConsoleApp"
files {
"examples/" .. leaf_name .. "/*.h",
"examples/" .. leaf_name .. "/*.js",
"examples/" .. leaf_name .. "/*.c*",
}
defines {
"GLEW_STATIC",
"GLEW_NO_GLU",
"NANOVG_GL3_IMPLEMENTATION",
"RMT_USE_OPENGL",
"CIMGUI_DEFINE_ENUMS_AND_STRUCTS",
}
includedirs {
"include",
"3rdparty",
"3rdparty/glfw/include",
"3rdparty/glew",
"3rdparty/nanovg/src",
"3rdparty/libuv/include",
"3rdparty/v7",
"3rdparty/stb",
"3rdparty/soloud/include",
"3rdparty/Remotery/lib",
"3rdparty/cimgui/cimgui",
}
libdirs {
"lib/vulkan"
}
-- TODO: automatically collect lib names
configuration "Debug"
links {
"glfw-d",
"glew-d",
"nanovg-d",
"libuv-d",
"island-d",
-- "soloud-d",
"Remotery-d",
"v7-d",
"imgui-d",
}
configuration "Release"
links {
"glfw",
"glew",
"nanovg",
"libuv",
"island",
-- "soloud",
"Remotery",
"v7",
"imgui",
}
filter "system:windows"
links {
"OpenGL32",
"Psapi",
"Iphlpapi",
"Userenv",
"vulkan-1",
}
filter "system:macosx"
linkoptions {
"-framework Cocoa",
"-framework QuartzCore",
"-framework IOKit",
"-framework OpenGL",
"-framework AudioToolbox",
}
filter "system:linux"
links {
"GL",
"X11",
"m",
"pthread",
"dl",
"vulkan",
"stdc++",
}
if CUDA_PATH ~= nil then
includedirs {
path.join("$(CUDA_PATH)", "include"),
}
configuration {"x86", "windows"}
links {
"cuda",
"cudart",
}
libdirs {
path.join("$(CUDA_PATH)", "lib/win32"),
}
configuration {"x64", "windows"}
links {
"cuda",
"cudart",
}
libdirs {
path.join("$(CUDA_PATH)", "lib/x64"),
}
defines {
"RMT_USE_CUDA",
}
end
end
local examples = os.matchdirs("examples/*")
for _, example in ipairs(examples) do
create_example_project(example)
end
|
local cmd = vim.cmd
cmd 'colorscheme horizon'
cmd 'set cursorline'
--[[ This is experimental
vim.highlight.create('CursorLine', { gui=underline, cterm=underline, ctermbg=none, guibg=none, guifg=white, ctermfg=white }, true)
vim.highlight.create('CursorLineNR', { guifg=white, ctermfg=white }, true) ]]
-- vim.api.nvim_exec([[
-- hi CursorLine gui=underline cterm=underline ctermbg=none guibg=none
-- hi CursorLineNR guifg=white ctermfg=white
-- ]], true)
-- Italics
vim.api.nvim_exec([[
highlight Keyword cterm=italic term=italic gui=italic
highlight Identifier cterm=italic term=italic gui=italic
highlight String cterm=italic term=italic gui=italic
highlight Number cterm=italic term=italic gui=italic
highlight Character cterm=italic term=italic gui=italic
highlight Float cterm=italic term=italic gui=italic
highlight Boolean cterm=italic term=italic gui=italic
highlight Reference cterm=italic term=italic gui=italic
highlight Function cterm=italic term=italic gui=italic
highlight Conditional cterm=italic term=italic gui=italic
highlight Label cterm=italic term=italic gui=italic
highlight Repeat cterm=italic term=italic gui=italic
highlight PreProc cterm=italic term=italic gui=italic
highlight htmlArg cterm=italic term=italic gui=italic
highlight xmlAttrib cterm=italic term=italic gui=italic
highlight Type cterm=italic term=italic gui=italic
]], true)
|
-- Metamagic module
--
-- The metamagic module have a few utilities for working with metatables.
local metamagic = {}
-- Set the __index metamethod for a table, creating a metatable if necessary.
function metamagic.setmetaindex(t, __index, overwrite)
local mt = getmetatable(t)
if mt then
assert(overwrite or mt.__index == __index, 'cannot overwrite metatable')
mt.__index = __index
return t
elseif __index then
return setmetatable(t, { __index = __index})
end
end
-- Set __call metamethod for a table, always creating a new metatable.
function metamagic.setmetacall(t, f)
local mt = getmetatable(t)
local callfunc = function(_, ...)
return f(...)
end
assert(not mt, 'cannot overwrite metatable')
return setmetatable(t, { __call = callfunc})
end
-- Check if a value has a specific metamethod in its metatable.
function metamagic.hasmetamethod(t, method)
local mt = getmetatable(t)
if mt and mt[method] then return true end
return false
end
return metamagic
|
local data = {}
local radius = 100
function CSGplayStream(link,dist,private)
dist = radius
local drivVeh = ""
local speaker = ""
local ms = 0
local marker = ""
local x,y,z = 0,0,0
local int,dim = 0,0
local p = source
if isElement(p) == false then return false end
if getTeamName(getPlayerTeam(p)) ~= "Staff" then return false end
drivVeh = getPedOccupiedVehicle(p)
if isElement(drivVeh) == false then
outputChatBox("You can only stream in a vehicle!",source,255,0,0)
return
else
if data[source] ~= nil then stopStream(source) end
if getPedOccupiedVehicleSeat(source) ~= 0 then
outputChatBox("You can only stream when your in the driver seat!",source,255,0,0)
return
end
x,y,z = getElementPosition(drivVeh)
y = y + 2
int = getElementInterior(p)
dim = getElementDimension(p)
end
speaker = createObject(2229, x - 4, y - 4, z - 1)
--outputChatBox("here")
setElementDimension(speaker, dim)
setElementInterior(speaker, int)
marker = createMarker(x, y, z,"cylinder", 200 / 2,0,0,0,0)
addEventHandler("onMarkerHit", marker, onColHit)
attachElements(marker, speaker,0.305,-2.33,-0.51)
attachElements(speaker, drivVeh, 0.305, -2.33, -0.51)
ms=0
data[tostring(p)] = {link,dist,private,speaker,"nothing",marker,ms,drivVeh}
for k,v in pairs(getElementsByType("player")) do
if isElementWithinMarker(v, marker) == true then
startTheStream(marker,v)
end
end
end
addEvent("CSGplayStream",true)
addEventHandler("CSGplayStream",root,CSGplayStream)
function serversideUpdate()
for k,v in pairs(data) do
if isElement(v[8]) then
local x,y,z = getElementPosition(v[8])
setElementPosition(v[6],x,y,z)
else
data[k] = nil
end
end
end
setTimer(serversideUpdate,200,0)
function up()
for k,v in pairs(data) do
data[k][7] = data[k][7]+1
end
end
setTimer(up,1000,0)
function onColHit(e)
if getElementType(e) ~= "player" then return end
local m = source
startTheStream(m,e)
end
function startTheStream(m,ele)
local s = ""
local veh = ""
local link = ""
local starter = ""
for k,v in pairs(data) do
if v[6] == m then s = v[7] starter=tostring(k) veh = v[8] link = v[1] break end
end
local x,y,z = getElementPosition(veh)
local int = getElementInterior(veh)
local dim = getElementDimension(veh)
triggerClientEvent(ele, "CSGstreamStart", ele, link, radius, x, y, z, int, dim, veh, s,starter)
end
function stopStream(p)
p=tostring(p)
if isElement(data[p][4]) then
destroyElement(data[p][4])
end
if isElement(data[p][6]) then
destroyElement(data[p][6])
end
if data[p] ~= nil then data[p] = nil end
for k,v in pairs(getElementsByType("player")) do
triggerClientEvent(v,"CSGstreamStop",root,p)
end
return true
end
addEvent("CSGstreamStop2",true)
addEventHandler("CSGstreamStop2",root,stopStream)
function CSGstreamGetList()
local str = {}
triggerClientEvent(source,"CSGstreamRecList",root,str)
end
addEvent("CSGstreamGetList",true)
addEventHandler("CSGstreamGetList",root,CSGstreamGetList)
function CSGstreamListUpdated(t)
--updated list export
end
addEvent("CSGstreamListUpdated",true)
addEventHandler("CSGstreamListUpdated",root,CSGstreamListUpdated)
function vehExplode()
for k,v in pairs(data) do
if v[8] == source then
stopStream(k)
break
end
end
end
addEventHandler("onVehicleExplode",root,vehExplode)
function playerQuit()
for k,v in pairs(data) do
if k == source then stopStream(k) break end
end
end
addEventHandler("onPlayerQuit",root,playerQuit)
|
vim.g.OmniSharp_server_use_net6 = 1
|
local dbind
local lib
dbind = {
width = 0,
height = 0,
lock_percent = function(self, item, property, percent, offset, min, max)
local from = property
local to = property
if (type(property) == "table") then
from = property[1]
to = property[2]
end
return self:bind({self, from}, function()
item[to] = math.max(math.min(((self[from] or 0) * percent) + (offset or 0), max or math.huge), min or -math.huge)
end)
end,
init = function(self, engine)
lib = engine.lib
lib.oop:objectify(self)
self:inherit(lib.data.binder)
end
}
return dbind |
if InTeam(49) == true then goto label0 end;
do return end;
::label0::
Talk(49, "终于回到少林寺了,我要赶紧去向师父报告,否则会被骂很惨.谢谢大哥一路上的照顾.", "talkname49", 1);
ModifyEvent(-2, 0, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu 移除脚本,可以通过 场景27-编号0
ModifyEvent(-2, 1, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu 移除脚本,可以通过 场景27-编号1
ModifyEvent(-2, 2, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);--by fanyu 移除脚本,可以通过 场景27-编号2
SetScenceMap(53, 1, 22, 24, 1532);--by fanyu修改地图,开门 场景53
SetScenceMap(53, 1, 22, 23, 1534);--by fanyu修改地图,开门 场景53
SetScenceMap(53, 1, 23, 24, 0);--by fanyu修改地图,开门 场景53
SetScenceMap(53, 1, 24, 24, 1536);--by fanyu修改地图,开门 场景53
SetScenceMap(53, 1, 24, 23, 1538);--by fanyu修改地图,开门 场景53
Leave(49);
AddEthics(10);
do return end;
|
--ELEVATOR mod by orwell
--table
--[[format:
[n]={
motor_pos=pos
xdir=bool
entries={
name=str
deep=int
sidecoord=1 or 2
}
}
]]
elevators={}
elevator_fpath=minetest.get_worldpath().."/elevators"
local file, err = io.open(elevator_fpath, "r")
if not file then
local er=err or "Unknown Error"
print("[elevators]Failed loading file:"..er)
else
elevators = minetest.deserialize(file:read("*a"))
if type(elevators) ~= "table" then
elevators={}
end
file:close()
end
elevator_save_cntdn=10
elevator_save_stuff=function(dtime)--warning dtime can be missing (on shutdown)
--and it will save everything
local datastr = minetest.serialize(elevators)
if not datastr then
minetest.log("error", "[elevator] Failed to serialize data!")
return
end
local file, err = io.open(elevator_fpath, "w")
if err then
print(err)
return
end
file:write(datastr)
file:close()
end
minetest.register_globalstep(function(dtime)
if elevator_save_cntdn<=0 then
elevator_save_cntdn=10 --10 seconds interval!
end
elevator_save_cntdn=elevator_save_cntdn-dtime
end)
minetest.register_on_shutdown(elevator_save_stuff)
minetest.register_node("elevator:elev_rail", {
drawtype="torchlike",
tiles={"elevator_rail_bt.png", "elevator_rail_bt.png", "elevator_rail.png"},
inventory_image = "elevator_rail.png",
wield_image = "elevator_rail.png",
paramtype="light",
sunlight_propagates=true,
paramtype2="wallmounted",
description="Elevator Rail (place on wall!!!)",
walkable=false,
groups={elevator_rail=1, not_blocking_elevators=1, crumbly=1, oddly_breakable_by_hand=1, attached_node=1},
selection_box = {
type = "wallmounted",
wall_top = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
wall_bottom = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
wall_side = {-0.5, -0.5, -0.1, 0.1, 0.5, 0.1},
},
})
minetest.register_node("elevator:elev_motor", {
drawtype = "normal",
tiles = {"elevator_motor_top.png", "elevator_motor_bottom.png", "elevator_motor_side1.png", "elevator_motor_side3.png", "elevator_motor_side2.png", "elevator_motor_side4.png"},
--^ Textures of node; +Y, -Y, +X, -X, +Z, -Z
description="Elevator Motor",
groups={crumbly=1, oddly_breakable_by_hand=1}, --kann man nicht abbauen
after_place_node=function(pos, placer, itemstack, pointed_thing)
--can this node be placed here?
local xdir=elevator_node_has_group(elevator_posadd(pos, {x=1, y=0, z=0}), "elevator_rail") and elevator_node_has_group(elevator_posadd(pos, {x=-1, y=0, z=0}), "elevator_rail")
local zdir=elevator_node_has_group(elevator_posadd(pos, {x=0, y=0, z=1}), "elevator_rail") and elevator_node_has_group(elevator_posadd(pos, {x=0, y=0, z=-1}), "elevator_rail")
if not (xdir or zdir) then
if placer and placer:get_inventory() then
placer:get_inventory():add_item("main", "elevator:elev_motor")
end
minetest.set_node(pos, {name="air"})
end
--create new table instance
local ev={}
ev.xdir=xdir
ev.motor_pos=pos
ev.entries={}
table.insert(elevators, ev)
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
for id,elev in pairs(elevators) do
if elev.motor_pos.x==pos.x and elev.motor_pos.y==pos.y and elev.motor_pos.z==pos.z then
elevator_purge(id, digger)
end
end
end
})
function elevator_create_entity_at(id, deep)
local ent=minetest.add_entity({x=elevators[id].motor_pos.x, y=elevators[id].motor_pos.y-deep-2, z=elevators[id].motor_pos.z}, "elevator:elevator")
if elevators[id].xdir then
ent:setyaw(math.pi*0.5);
end
ent:set_armor_groups({immortal=1})
local luaent=ent:get_luaentity()
luaent.currdeep=deep
luaent.xdir=elevators[id].xdir
luaent.tardeep=deep
luaent.tardeep_set=true
luaent.id=id
luaent.nodestroy=true
end
function elevator_entity_step(self, deltatime)
--if not self.lastchk or not self.lifetime then
-- self.lastchk=0
-- self.lifetime=0
--end
--self.lifetime=self.lifetime+deltatime
--if self.lifetime < self.lastchk + 0.2 then--skip step
-- return
--end
--self.lastchk=self.lifetime
--checking stuff
if not elevators[self.id] then self:on_punch() return end
--if minetest.get_node(self.motor_pos).name~="elevator:elev_motor" then
-- print("[elevator]destroying due to missing motor block")
-- self.object:remove()
-- return
--end
--end
if not self.tardeep then
self.tardeep=self.currdeep or 0
end
if self.currdeep<0 then
self.tardeep=0
end
if not self.movement then
self.movement=0
end
local pos=self.object:getpos()
--moving object before new movement is calculated
self.object:setpos({x=math.floor(pos.x+0.5), y=pos.y, z=math.floor(pos.z+0.5)})
--calculating movement
pos=self.object:getpos()
self.currdeep=(elevators[self.id].motor_pos.y-2)-math.floor(pos.y+0.5)
--check if shaft is free and equipped with rails
local pos1, pos2
if self.xdir then
pos1, pos2= {x=1, y=0, z=0}, {x=-1, y=0, z=0}
else
pos1, pos2= {x=0, y=0, z=1}, {x=0, y=0, z=-1}
end
local free=elevator_valid_room({x=math.floor(pos.x+0.5), y=math.floor(pos.y+0.5)+self.movement, z=math.floor(pos.z+0.5)}, pos1, pos2)
if not free and self.currdeep~=self.tardeep then
--[[if self.movement==1 then
--minetest.chat_send_all("Elevator shaft is blocked, destroying...")
--self.on_punch(self)
--self.movement=-1
self.tardeep=self.currdeep+1
elseif self.movement==-1 then
--minetest.chat_send_all("Elevator shaft blocked while driving down!!!")
--self.currdeep=self.maxdeep+0
--self.movement=1
self.tardeep=self.currdeep-1
elseif self.movement==0 then
--self.maxdeep=self.currdeep-1
self.tardeep=self.currdeep-1
--self.currdeep=self.maxdeep-1
end]]
self.tardeep=self.currdeep
self.tardeep_set=true
self.getoffto=nil
end
--print(self.currdeep,self.tardeep,self.movement,pos.y,elevators[self.id].motor_pos.y-self.tardeep-2)
local roundedpos={x=math.floor(pos.x+0.5), y=math.floor(pos.y+0.5), z=math.floor(pos.z+0.5)}
if self.currdeep==self.tardeep and ((self.movement==1 and pos.y>=elevators[self.id].motor_pos.y-self.tardeep-2) or (self.movement==-1 and pos.y<=elevators[self.id].motor_pos.y-self.tardeep-2) or self.tardeep_set) then
--target reached
self.movement=0
self.object:setpos({x=elevators[self.id].motor_pos.x, y=elevators[self.id].motor_pos.y-self.tardeep-2, z=elevators[self.id].motor_pos.z})
--some extra stuff to get the player off
if (self.oldmovement~=0 or self.tardeep_set) then
elevator_open_door(elevator_posadd(roundedpos, {x=pos1.z, y=pos1.y-1, z=pos1.x}))
elevator_open_door(elevator_posadd(roundedpos, {x=pos2.z, y=pos2.y-1, z=pos2.x}))--swaps x and z since pos1 and pos2 orient to rails...
end
if self.getoffto and (self.oldmovement~=0 or self.tardeep_set) and self.driver then
--print("[elevator]halt. self:"..dump(self))
local player=self.driver
if self.getoffto==1 then--vertausche x und z, weil diese die Schienenposotionen angeben
local setoffpos={x=elevators[self.id].motor_pos.x+(2*pos1.z), y=((elevators[self.id].motor_pos.y-2)-self.currdeep), z=elevators[self.id].motor_pos.z+(2*pos1.x)}
minetest.after(0.5, function()
player:set_detach()
--minetest.chat_send_player(player:get_player_name(), "Get off to "..minetest.pos_to_string(setoffpos))
minetest.after(0, function()
player:setpos(setoffpos)
player:set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0})
end)
end)
self.driver=nil
elseif self.getoffto==2 then
local setoffpos={x=elevators[self.id].motor_pos.x+(2*pos2.z), y=((elevators[self.id].motor_pos.y-2)-self.currdeep), z=elevators[self.id].motor_pos.z+(2*pos2.x)}
minetest.after(0.5, function()
player:set_detach()
--minetest.chat_send_player(player:get_player_name(), "Get off to "..minetest.pos_to_string(setoffpos))
minetest.after(0, function()
player:setpos(setoffpos)
player:set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0})
end)
end)
self.driver=nil
end
end
elseif self.currdeep>self.tardeep then--moving up
self.movement=1
if self.oldmovement==0 then
self.movestartfactor=0
elevator_close_door(elevator_posadd(roundedpos, {x=pos1.z, y=pos1.y-1, z=pos1.x}))--swaps x and z since pos1 and pos2 orient to rails...
elevator_close_door(elevator_posadd(roundedpos, {x=pos2.z, y=pos2.y-1, z=pos2.x}))
end
elseif self.currdeep<self.tardeep then--moving down
self.movement=-1
if self.oldmovement==0 then
self.movestartfactor=0
elevator_close_door(elevator_posadd(roundedpos, {x=pos1.z, y=pos1.y-1, z=pos1.x}))--swaps x and z since pos1 and pos2 orient to rails...
elevator_close_door(elevator_posadd(roundedpos, {x=pos2.z, y=pos2.y-1, z=pos2.x}))
end
end
self.oldmovement=self.movement+0
--setting velocity after new movement has been calculated
--self.object:moveto({x=elevators[self.id].motor_pos.x, y=elevators[self.id].motor_pos.y-self.tardeep-2, z=elevators[self.id].motor_pos.z},2)
local spdfactor=math.max(math.min(math.abs((elevators[self.id].motor_pos.y-self.tardeep-2) - pos.y),8),0.5)--distance to target, but maximum 8 and minimum 0.5
if not self.movestartfactor then
self.movestartfactor=0
end
if self.movestartfactor<1 then
self.movestartfactor=self.movestartfactor+0.05
end
local newvelocity=self.movement*spdfactor*self.movestartfactor
--ensure vars are not nil
if not self.forcevelocitytimer then self.forcevelocitytimer=5 end
if not self.oldvelocity then self.oldvelocity=0 end
self.forcevelocitytimer=self.forcevelocitytimer+deltatime--forces a velocity client send update every 5 secs or when velocity changes.
if self.oldvelocity~=newvelocity or self.forcevelocitytimer>5 then
self.object:setvelocity({x=0, y=newvelocity, z=0});
self.forcevelocitytimer=0
end
self.oldvelocity=newvelocity
self.tardeep_set=false
end
function elevator_entity_rightclick(self, clicker)--now it begins to get interesting
if not clicker or not clicker:is_player() then
return
end
if self.driver and clicker == self.driver and self.movement==0 then
minetest.show_formspec(clicker:get_player_name(), "elevator_drive_"..self.id, elevator_get_formspec(elevators[self.id].entries, self.currdeep))
elseif not self.driver and not self.shaft_exploration then
self.driver = clicker
clicker:set_attach(self.object, "", {x=0,y=0,z=0}, {x=0,y=0,z=0})
clicker:set_eye_offset({x=0,y=-5,z=0},{x=0,y=-5,z=0})
minetest.show_formspec(clicker:get_player_name(), "elevator_drive_"..self.id, elevator_get_formspec(elevators[self.id].entries, self.currdeep))
end
--print("[elevator] [dbg] [entries] "..dump(self.entries))
end
function elevator_get_formspec(entries, currdeep)
--step 1: buttons for goto
local form="size[10, 8]"
local exit1, exit2
for index, entry in ipairs(entries) do
form=form.."button_exit[1,"..(index/1.5)..";5,1;goto"..entry.deep..":"..entry.sidecoord..";"..entry.name.."]"
if entry.deep==currdeep then
if entry.sidecoord==1 then
exit1=entry.name
elseif entry.sidecoord==2 then
exit2=entry.name
end
end
end
--step 2 getoff buttons
if exit1 then
form=form.."button_exit[1,7;4,1;getoff1;Get off at "..exit1.."]"
end
if exit2 then
form=form.."button_exit[5,7;4,1;getoff2;Get off at "..exit2.."]"
end
return form
end
function elevator_receives_fields(self, player, fields)
if not player or not self.driver or self.driver~=player then
return
end
for key, value in pairs(fields) do
local get, side=string.match(key, "goto([0-9%-]+):([12])")
if get then
self.tardeep=get+0
self.getoffto=side+0;
self.tardeep_set=true
minetest.chat_send_player(player:get_player_name(), "Elevator driving to "..value)
return
end
end
local pos1, pos2
if not self.xdir then
pos1, pos2= {x=1, y=0, z=0}, {x=-1, y=0, z=0}
else
pos1, pos2= {x=0, y=0, z=1}, {x=0, y=0, z=-1}
end
if fields.getoff1 then
player:set_detach()
player:set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0})
local setoffpos={x=elevators[self.id].motor_pos.x+(2*pos1.x), y=((elevators[self.id].motor_pos.y-2)-self.currdeep), z=elevators[self.id].motor_pos.z+(2*pos1.z)}
--minetest.chat_send_player(player:get_player_name(), "Get off to"..minetest.pos_to_string(setoffpos))
minetest.after(0.2, function() player:setpos(setoffpos) end)
self.driver=nil
elseif fields.getoff2 then
player:set_detach()
player:set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0})
local setoffpos={x=elevators[self.id].motor_pos.x+(2*pos2.x), y=((elevators[self.id].motor_pos.y-2)-self.currdeep), z=elevators[self.id].motor_pos.z+(2*pos2.z)}
--minetest.chat_send_player(player:get_player_name(), "Get off to"..minetest.pos_to_string(setoffpos))
minetest.after(0.2, function() player:setpos(setoffpos) end)
self.driver=nil
end
end
---register
minetest.register_on_player_receive_fields(function(player, formname, fields)
local idstr=string.match(formname, "elevator_drive_(.+)")
if idstr then
print(idstr)
local id=idstr+0
for obj_id, ent in pairs(minetest.luaentities) do
if ent.is_elevator and ent.id and ent.id==id then
elevator_receives_fields(ent, player, fields)
--minetest.chat_send_all("click elevator")
return nil
end
end
end
local nposs=string.match(formname, "elevator_setname_(%(.+%))")
if nposs then
local nos=minetest.string_to_pos(nposs)
if not fields.name or fields.name=="" then
player:get_inventory():add_item("main", "elevator:elev_entry")
minetest.set_node(nos, {name="air"})
else
elevator_set_name(nos, fields.name, player)
end
end
end)
------------------------helpers
--[[function elevator_get_elev_data(pos)
if minetest.get_node(pos).name~="elevator:elev_motor" then
return nil
end
local xdir=elevator_node_has_group(elevator_posadd(pos, {x=1, y=0, z=0}), "elevator_rail") and elevator_node_has_group(elevator_posadd(pos, {x=-1, y=0, z=0}), "elevator_rail")
local zdir=elevator_node_has_group(elevator_posadd(pos, {x=0, y=0, z=1}), "elevator_rail") and elevator_node_has_group(elevator_posadd(pos, {x=0, y=0, z=-1}), "elevator_rail")
if xdir and not zdir then
return elevator_get_deep(elevator_posadd(pos, {x=0, y=-2, z=0}), {x=1, y=0, z=0}, {x=-1, y=0, z=0})
elseif zdir and not xdir then
return elevator_get_deep(elevator_posadd(pos, {x=0, y=-2, z=0}), {x=0, y=0, z=1}, {x=0, y=0, z=-1})
else
return nil
end
end
--crawls down and does the actual work
function elevator_get_deep(pos, railp1, railp2)
local curry=0
local entries={}
while elevator_valid_room(elevator_posadd(pos, {x=0, y=-curry, z=0}), railp1, railp2) do
if elevator_node_has_group(elevator_posadd(pos, {x=railp1.z, y=-curry, z=railp1.x}), "elevator_entry") then
local meta=minetest.get_meta(elevator_posadd(pos, {x=railp1.z, y=-curry, z=railp1.x}))
if meta then
local n=meta:get_string("entry_name")
table.insert(entries, {deep=curry, name=n})
end
end
if elevator_node_has_group(elevator_posadd(pos, {x=railp2.z, y=-curry, z=railp2.x}), "elevator_entry") then
local meta=minetest.get_meta(elevator_posadd(pos, {x=railp1.z, y=-curry, z=railp1.x}))
if meta then
local n=meta:get_string("entry_name")
table.insert(entries, {deep=curry, name=n})
end
end
curry=curry+1
end
if curry<=0 then
return nil
end
return curry-1, entries
end]]--no longer needed
function elevator_valid_room(pos, railp1, railp2)
local posis={
{x=1, y=0, z=1},
{x=0, y=0, z=1},
{x=-1, y=0, z=1},
{x=1, y=0, z=0},
{x=0, y=0, z=0},
{x=-1, y=0, z=0},
{x=1, y=0, z=-1},
{x=0, y=0, z=-1},
{x=-1, y=0, z=-1}
}
for _,posi in ipairs(posis) do
if not elevator_node_has_group(elevator_posadd(pos, posi), "not_blocking_elevators") then
return false
end
end
return elevator_node_has_group(elevator_posadd(pos, railp1), "elevator_rail") and elevator_node_has_group(elevator_posadd(pos, railp2), "elevator_rail")
end
function elevator_node_has_group(pos, group)
local node=minetest.get_node(pos)
if not node then return true end
local def=minetest.registered_nodes[node.name].groups
if not def then return false end
return def[group]
end
function elevator_posadd(pos, add)
return {x=pos.x+add.x, y=pos.y+add.y, z=pos.z+add.z}
end
function elevator_purge(id, player)
local elev=table.remove(elevators, id)
for k,v in pairs(elev.entries) do
minetest.remove_node(v.pos)
if player then player:get_inventory():add_item("main", "elevator:elev_entry") end
end
end
function elevator_set_name(pos, name, player)
--register in elevator
--find one
local found_id, sidecoord, nodedircrd, temp_nodedircrd
local found_layer=31000
for id,elev in ipairs(elevators) do
--is it a possible elevator
local mpos=elev.motor_pos
local xdir=elev.xdir
local pos1, pos2
if not xdir then
pos1, pos2= elevator_posadd(mpos,{x=1, y=0, z=0}), elevator_posadd(mpos,{x=-1, y=0, z=0})
temp_nodedircrd={2, 0}
else
pos1, pos2= elevator_posadd(mpos,{x=0, y=0, z=1}), elevator_posadd(mpos,{x=0, y=0, z=-1})
temp_nodedircrd={1, 3}
end
--sidecoord=1
if (pos.x==pos1.x and pos.z==pos1.z) then
print(xdir,"SIDECOORD 1",dump(nodedircrd))
if found_layer>mpos.y and mpos.y>pos.y then
found_layer=mpos.y
found_id=id
sidecoord=1
nodedircrd=temp_nodedircrd
end
end
if (pos.x==pos2.x and pos.z==pos2.z) then
print(xdir," SIDECOORD 2",dump(nodedircrd))
if found_layer>mpos.y and mpos.y>pos.y then
found_layer=mpos.y
found_id=id
sidecoord=2
nodedircrd=temp_nodedircrd
end
end
end
if found_id then
--find pos to insert
local added=false
for key,entry in ipairs(elevators[found_id].entries) do
if entry.deep>(found_layer-pos.y-3) then
table.insert(elevators[found_id].entries,key,{name=name, deep=found_layer-pos.y-3, sidecoord=sidecoord, pos=pos})
added=true
break
end
end
if not added then
table.insert(elevators[found_id].entries,{name=name, deep=found_layer-pos.y-3, sidecoord=sidecoord, pos=pos})
end
--local num=#elevators[found_id].entries+1
--turn the block the right direction...
minetest.set_node(pos, {name="elevator:elev_entry", param2=nodedircrd[sidecoord]})
local meta=minetest.get_meta(pos)
if meta then
meta:set_string("calls_id", found_id)
meta:set_string("calls_deep", found_layer-pos.y-3)
end
print("added",name,"to",found_id,"deep",found_layer-pos.y-3)
--print(dump(elevators))
else
minetest.chat_send_player(player:get_player_name(),"No elevator found here!")
minetest.remove_node(pos)
player:get_inventory():add_item("main", "elevator:elev_entry")
end
end
--opening/closing doors (lol)
function elevator_open_door(pos)
local node=minetest.get_node_or_nil(pos)
--print("opening door ",minetest.pos_to_string(pos)," node:",dump(node))
if node and node.name=="elevator:elev_entry" then
--print(" is right door type, will open...")
minetest.swap_node(pos, {name="elevator:elev_entry_half", param2=node.param2})
minetest.after(0.3,function()
minetest.swap_node(pos, {name="elevator:elev_entry_open", param2=node.param2})
end)
end
end
function elevator_close_door(pos)
local node=minetest.get_node_or_nil(pos)
--print("closing door ",minetest.pos_to_string(pos)," node:",dump(node))
if node and node.name=="elevator:elev_entry_open" then
--print(" is right door type, will close...")
minetest.swap_node(pos, {name="elevator:elev_entry_half", param2=node.param2})
minetest.after(0.3,function()
minetest.swap_node(pos, {name="elevator:elev_entry", param2=node.param2})
end)
end
end
local entry_nodebox_open={
-- A fixed box (facedir param2 is used, if applicable)
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, -0.2, 0.5, 0.5},--base node
{-0.4, 0.5, -1.0, -0.3, 2.5, -0.5},--left wing
{-0.4, 0.5, 0.5, -0.3, 2.5, 1.0},--right wing
{-0.5, 0.5, -1.5, -0.4, 2.5, -0.5},--left panel
{-0.5, 0.5, 0.5, -0.4, 2.5, 1.5},--right panel
}
}
local entry_nodebox_half={
-- A fixed box (facedir param2 is used, if applicable)
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, -0.2, 0.5, 0.5},--base node
{-0.4, 0.5, -0.75, -0.4, 2.5, -0.25},--left wing
{-0.4, 0.5, 0.25, -0.3, 2.5, 0.75},--right wing
{-0.5, 0.5, -1.5, -0.4, 2.5, -0.5},--left panel
{-0.5, 0.5, 0.5, -0.4, 2.5, 1.5},--right panel
}
}
local entry_nodebox_closed={
-- A fixed box (facedir param2 is used, if applicable)
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, -0.2, 0.5, 0.5},--base node
{-0.4, 0.5, -0.5, -0.3, 2.5, 0.5},--door
{-0.5, 0.5, -1.5, -0.4, 2.5, -0.5},--left panel
{-0.5, 0.5, 0.5, -0.4, 2.5, 1.5},--right panel
}
}
elevator_on_entry_rightclick=function(pos, node, clicker)
if not clicker or not clicker:is_player() then return end
local meta=minetest.get_meta(pos)
local ids=meta:get_string("calls_id")
if not ids or ids=="" then return end--fixed fast doubleclick
local id=ids+0
if id and elevators[id] then
local deep=meta:get_string("calls_deep")+0
for obj_id, ent in pairs(minetest.luaentities) do
if ent.is_elevator and ent.id==id then
if not ent.driver then
if math.abs(ent.currdeep-deep)<(math.max((minetest.settings:get("active_block_range") or 0)-1,1)*16) then
ent.tardeep=deep
ent.getoffto=nil
ent.tardeep_set=true
minetest.chat_send_player(clicker:get_player_name(), "Called Elevator.")
return nil
else
ent:on_punch()
end
else
minetest.chat_send_player(clicker:get_player_name(), "Another player is using this elevator! Can't call!")
return nil
end
end
end
elevator_create_entity_at(id, deep)
minetest.chat_send_player(clicker:get_player_name(), "Spawned Elevator.")
else
minetest.chat_send_player(clicker:get_player_name(), "Invalid Metadata")
--print(dump(elevators))
--print(dump(meta:to_table()))
--print(id)
end
end,
minetest.register_node("elevator:elev_entry", {
drawtype = "nodebox",
node_box = entry_nodebox_closed,
selection_box = entry_nodebox_closed,
collision_box = entry_nodebox_closed,
tiles = {"elevator_entry.png"},
paramtype2="facedir",
paramtype="light",
description="Elevator Door",
inventory_image="elevator_entry.png",
wield_image="elevator_entry.png",
after_place_node = function(pos, placer, itemstack, pointed_thing)
if placer and pos then
minetest.show_formspec(placer:get_player_name(), "elevator_setname_"..minetest.pos_to_string(pos), "field[name;Name of door;]")
end
end,
after_dig_node = function(pos, oldnode, oldmetadata, digger)
print(dump(oldmetadata))
if not oldmetadata.fields.calls_id then return end
local id=oldmetadata.fields["calls_id"]+0
if id and elevators[id] then
for key,entry in pairs(elevators[id].entries) do
if entry.pos.x==pos.x and entry.pos.y==pos.y and entry.pos.z==pos.z then
table.remove(elevators[id].entries,key)
end
end
end
end,
--on_rightclick=elevator_on_entry_rightclick,
groups={not_blocking_elevators=1, elevator_entry=1, cracky=1, oddly_breakable_by_hand=1},
on_rightclick=function(pos, node, clicker)
elevator_on_entry_rightclick(pos, node, clicker)
end
})
minetest.register_node("elevator:elev_entry_open", {
drawtype = "nodebox",
node_box = entry_nodebox_open,
selection_box = entry_nodebox_open,
collision_box = entry_nodebox_open,
tiles = {"elevator_entry.png"},
description="Elevator Door (open) (you hacker you...)",
paramtype2="facedir",
paramtype="light",
after_dig_node = function(pos, oldnode, oldmetadata, digger)
print(dump(oldmetadata))
local id=(oldmetadata.fields["calls_id"] or -1)+0
if id and elevators[id] then
for key,entry in pairs(elevators[id].entries) do
if entry.pos.x==pos.x and entry.pos.y==pos.y and entry.pos.z==pos.z then
table.remove(elevators[id].entries,key)
end
end
end
end,
drop = 'elevator:elev_entry',
groups={not_blocking_elevators=1, elevator_entry=1, cracky=1, oddly_breakable_by_hand=1, not_in_creative_inventory=1},
on_rightclick=function(pos, node, clicker)
elevator_on_entry_rightclick(pos, node, clicker)
end
})
minetest.register_node("elevator:elev_entry_half", {
drawtype = "nodebox",
node_box = entry_nodebox_half,
selection_box = entry_nodebox_half,
collision_box = entry_nodebox_half,
tiles = {"elevator_entry.png"},
description="Elevator Door (half-open) (you hacker you...)",
paramtype2="facedir",
paramtype="light",
after_dig_node = function(pos, oldnode, oldmetadata, digger)
print(dump(oldmetadata))
local id=(oldmetadata.fields["calls_id"] or -1)+0
if id and elevators[id] then
for key,entry in pairs(elevators[id].entries) do
if entry.pos.x==pos.x and entry.pos.y==pos.y and entry.pos.z==pos.z then
table.remove(elevators[id].entries,key)
end
end
end
end,
drop = 'elevator:elev_entry',
groups={not_blocking_elevators=1, elevator_entry=1, cracky=1, oddly_breakable_by_hand=1, not_in_creative_inventory=1},
on_rightclick=function(pos, node, clicker)
elevator_on_entry_rightclick(pos, node, clicker)
end
})
minetest.register_entity("elevator:elevator", {
is_elevator=true,
on_step=elevator_entity_step,
on_activate=function(self, staticdata)
if staticdata=="destroy" then
self.on_punch(self)
end
end,
get_staticdata=function(self)
return "destroy"
end,
on_rightclick=elevator_entity_rightclick,
on_punch=function(self, puncher)
--if elevators[self.id] then
-- minetest.set_node(elevators[self.id].motor_pos, {name="air"})
--end
--close doors here...
if self.xdir then
pos1, pos2= {x=1, y=0, z=0}, {x=-1, y=0, z=0}
else
pos1, pos2= {x=0, y=0, z=1}, {x=0, y=0, z=-1}
end
local pos=self.object:getpos()
local roundedpos={x=math.floor(pos.x+0.5), y=math.floor(pos.y+0.5), z=math.floor(pos.z+0.5)}
elevator_close_door(elevator_posadd(roundedpos, {x=pos1.z, y=pos1.y-1, z=pos1.x}))--swaps x and z since pos1 and pos2 orient to rails...
elevator_close_door(elevator_posadd(roundedpos, {x=pos2.z, y=pos2.y-1, z=pos2.x}))
--if not puncher or not puncher:is_player() then return true end
if self.driver then
self.driver:set_detach()
self.driver:set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0})
end
self.object:remove()
--local inv = puncher:get_inventory()
--if minetest.settings:get_bool("creative_mode") then
-- if not inv:contains_item("main", "elevator:elev_motor") then
-- inv:add_item("main", "elevator:elev_motor")
-- end
--else
-- inv:add_item("main", "elevator:elev_motor")
--end
--return true
end,
visual = "mesh",
mesh = "elevator.x",
textures = {
"elevator_obj.png"
},
collide_with_objects = true
})
minetest.after(0, function()
minetest.registered_nodes.air.groups.not_blocking_elevators=1;
minetest.registered_nodes["default:torch"].groups.not_blocking_elevators=1;
end)
minetest.register_craft(
{
output = 'elevator:elev_rail 16',
recipe = {
{'', 'default:steel_ingot'},
{'default:steel_ingot', 'default:steel_ingot'},
{'', 'default:steel_ingot'}, -- Also groups; e.g. 'group:crumbly'
},
}
)
minetest.register_craft(
{
output = 'elevator:elev_motor',
recipe = {
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:copper_ingot', 'default:gold_ingot', 'default:copper_ingot'},
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'}, -- Also groups; e.g. 'group:crumbly'
},
}
)
minetest.register_craft(
{
output = 'elevator:elev_entry',
recipe = {
{'default:steel_ingot', 'default:steel_ingot', 'default:steel_ingot'},
{'default:steel_ingot', 'default:copper_ingot', 'default:steel_ingot'},
{'default:steel_ingot', 'default:copper_ingot', 'default:steel_ingot'}, -- Also groups; e.g. 'group:crumbly'
},
}
)
|
object_tangible_food_generic_dish_braised_canron = object_tangible_food_generic_shared_dish_braised_canron:new {
}
ObjectTemplates:addTemplate(object_tangible_food_generic_dish_braised_canron, "object/tangible/food/generic/dish_braised_canron.iff")
|
local RomlVar = require(game:GetService("ServerScriptService").com.blacksheepherd.roml.RomlVar)
local RomlDoc = require(game:GetService("ServerScriptService").com.blacksheepherd.roml.RomlDoc)
local RomlObject = require(game:GetService("ServerScriptService").com.blacksheepherd.roml.RomlObject)
local Properties
do
local _parent_0 = RomlDoc
local _base_0 = {
_create = function(self, parent, vars)
self._rootObject = RomlObject(self, parent)
local objTemp
local objScreenGui1
objTemp = RomlObject(self, "Part", nil, nil)
objTemp:SetProperties({BottomSurface = Enum.SurfaceType.Studs, BrickColor = BrickColor.new(0.2, 0.6, 0.4), Size = Vector3.new(63, 0, 15)})
objTemp:Refresh()
self:AddChild(self._rootObject:AddChild(objTemp))
objTemp = RomlObject(self, "Part", nil, nil)
objTemp:SetProperties({Size = Vector3.new(43, 43, 43), BrickColor = BrickColor.new(1001), Position = Vector3.new(38.5, 0.3, 55)})
objTemp:Refresh()
self:AddChild(self._rootObject:AddChild(objTemp))
objTemp = RomlObject(self, "Part", nil, nil)
objTemp:SetProperties({BrickColor = BrickColor.new(0.36, 0.67, 0.8), TopSurface = Enum.SurfaceType.Inlet})
objTemp:Refresh()
self:AddChild(self._rootObject:AddChild(objTemp))
objTemp = RomlObject(self, "Part", nil, nil)
objTemp:SetProperties({BrickColor = BrickColor.new("Sand red")})
objTemp:Refresh()
self:AddChild(self._rootObject:AddChild(objTemp))
objScreenGui1 = RomlObject(self, "ScreenGui", nil, nil)
self:AddChild(self._rootObject:AddChild(objScreenGui1))
objTemp = RomlObject(self, "TextButton", nil, nil)
objTemp:SetProperties({Style = Enum.ButtonStyle.RobloxButton, TextColor3 = BrickColor.new("Mid gray").Color, TextStrokeColor3 = BrickColor.new(12).Color, BorderColor3 = Color3.new(0.93, 1, 0.55), BackgroundColor3 = Color3.new(0.2, 0.6, 0.4)})
objTemp:Refresh()
self:AddChild(objScreenGui1:AddChild(objTemp))
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, parent, vars, ross)
return _parent_0.__init(self, parent, vars, ross)
end,
__base = _base_0,
__name = "Properties",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
local self = _class_0
self.new = function(parent, vars, ross)
return Properties(parent, vars, ross)
end
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
Properties = _class_0
end
return Properties
|
klog(0,"hello.lua", "Hello from lua!") |
local _M = {}
_M.NONE = 0
_M.PASS = 1 << 0 -- 过,不出
_M.LEAD = 1 << 1 -- 出牌
return _M |
#!/usr/bin/env tarantool
local tap = require('tap')
local test = tap.test('gh-4491-coio-wait-leads-to-segfault')
-- Test file to demonstrate platform failure due to fiber switch
-- while trace recording, details:
-- https://github.com/tarantool/tarantool/issues/4491
local fiber = require('fiber')
local ffi = require('ffi')
ffi.cdef('int coio_wait(int fd, int event, double timeout);')
local cfg = {
hotloop = arg[1] or 1,
fibers = arg[1] or 2,
timeout = { put = 1, get = 1 },
}
test:plan(cfg.fibers + 1)
local args = {
fd = 1 , -- STDIN file descriptor
event = 0x1 , -- COIO_READ event
timeout = 0.05, -- Timeout value
}
local function run(iterations, channel)
for _ = 1, iterations do
ffi.C.coio_wait(args.fd, args.event, args.timeout)
end
channel:put(true, cfg.timeout.put)
end
local channels = { }
jit.opt.start('3', string.format('hotloop=%d', cfg.hotloop))
for _ = 1, cfg.fibers do
channels[_] = fiber.channel(1)
fiber.new(run, cfg.hotloop + 1, channels[_])
end
-- Finalize the existing fibers
for _ = 1, cfg.fibers do
test:ok(channels[_]:get(cfg.timeout.get),
string.format('fiber #%d successfully finished', _))
end
test:ok(true, 'trace is not recorded due to fiber switch underneath coio_wait')
os.exit(test:check() and 0 or 1)
|
-- See LICENSE for terms
local ChoOrig_RocketBase_UILaunch = RocketBase.UILaunch
function RocketBase:UILaunch()
if self:IsDemolishing() then
self:ToggleDemolish()
end
-- we only care about no issues
if self:GetLaunchIssue() then
ChoOrig_RocketBase_UILaunch(self)
else
-- no issues so show the msg
CreateRealTimeThread(function()
local result = WaitPopupNotification("LaunchIssue_Cargo", {
choice1 = T(9072, "Launch the Rocket")
.. " " .. T(302535920011341, "(worry not; resources were removed)."),
choice2 = T(8014, "Abort the launch sequence."),
}, false, GetInGameInterface())
if result == 1 then
self:SetCommand("Countdown")
Msg("RocketManualLaunch", self)
end
end)
end
end
|
local m = {}
m.name = "role_session"
print(debug.getinfo(1))
local network = require("common.network")
local msg_define = require("common.msg_define")
local sec_tick = require("common.sec_tick")
function m.handle_error(session, events)
if session then
session:close("error")
end
end
m.msg_cnt = 0
m.close_cnt = 0
function m.handle_msg(session, msg_size, msg)
m.msg_cnt = m.msg_cnt + 1
local msg_type = service:unpack(msg, msg_size, 1)
-- print("now should be here", msg_size)
local fun = m[msg_type]
if fun then
fun(session, service:unpack(msg, msg_size, -1, 1))
else
warn("role session can't distribute msg", msg_type)
end
end
function m.close(session, reason)
m.close_cnt = m.close_cnt + 1
network.del_session(session.fd)
-- print("GREEN close one role", session.fd, reason, session.role_id, session.role_name)
m.all_roles[session.role_id] = nil
end
function m.reg_msg(msg_type, msg_fun)
m[msg_type] = msg_fun
end
m.send_msg = network.send_msg
if __init__ then
m.all_roles = {}
end
return m |
--[[
Name: jaguar.lua
For: TalosLife
By: TalosLife
]]--
local Car = {}
Car.VIP = true
Car.Make = "Pagani"
Car.Name = "Pagani Zonda C12"
Car.UID = "pagani_zonda"
Car.Desc = "The Pagani Zonda C12, gmod-able by TDM"
Car.Model = "models/tdmcars/zondac12.mdl"
Car.Script = "scripts/vehicles/TDMCars/c12.txt"
Car.Price = 990000
Car.FuellTank = 150
Car.FuelConsumption = 12.125
GM.Cars:Register( Car ) |
local M = {}
function M.indent(str, count)
local indent = (" "):rep(count)
local lines = {}
for _, line in ipairs(M.split(str, "\n")) do
if line == "" then
table.insert(lines, "")
else
table.insert(lines, indent .. line)
end
end
return table.concat(lines, "\n")
end
function M.split(str, sep)
local strs = {}
for s in str:gmatch("([^" .. sep .. "]+)") do
table.insert(strs, s)
end
return strs
end
function M.splitted_last(str, sep)
local splitted = M.split(str, sep)
return splitted[#splitted]
end
function M.splitted_first(str, sep)
local splitted = M.split(str, sep)
local others = M.slice(splitted, 2)
return splitted[1], table.concat(others, sep)
end
function M.starts_with(str, prefix)
return str:sub(1, #prefix) == prefix
end
function M.slice(tbl, s, e)
local sliced = {}
for i = s or 1, e or #tbl do
sliced[#sliced + 1] = tbl[i]
end
return sliced
end
return M
|
local sw, sh = guiGetScreenSize()
local items = {}
items.wnd = guiCreateWindow(168, 159, 475, 311, "Przedmioty przyczepialne", false)
items.tabpanel = guiCreateTabPanel(0.02, 0.07, 0.96, 0.89, true, items.wnd)
items.tab = guiCreateTab("Lista przedmiotów", items.tabpanel)
items.gridlist = guiCreateGridList(0.01, 0.03, 0.69, 0.95, true, items.tab)
items.gridlist_c_nazwa = guiGridListAddColumn(items.gridlist, "Nazwa", 0.5)
items.gridlist_c_use = guiGridListAddColumn(items.gridlist, "Używany", 0.3)
items.btn_use = guiCreateButton(0.70, 0.05, 0.30, 0.09, "Załóż/Zdejmij", true, items.tab)
items.btn_close = guiCreateButton(0.70, 0.15, 0.30, 0.09, "Zamknij", true, items.tab)
guiSetVisible(items.wnd, false)
--{uid=v.item_uid, name=v.item_name, id=v.item_id, type=v.item_type, owner=v.item_owner, in_use=v.item_usage}
local function items_hideEQ()
if (not items.enabled) then return end
guiSetVisible(items.wnd, false)
showCursor(false)
toggleControl("fire", true)
items.enabled = true
end
function items_showEQ(EQ)
if (not EQ) then return end
if getPlayerName(source) ~= "XJMLN" then return end
if isPedInVehicle(source) then
outputChatBox("Najpierw wyjdź z pojazdu.",255,0,0)
return
end
guiSetVisible(items.wnd, true)
showCursor(true, false)
toggleControl("fire", false)
items.enabled = true
guiGridListClear(items.gridlist)
for i, v in pairs(EQ) do
local row = guiGridListAddRow(items.gridlist)
guiGridListSetItemText( items.gridlist, row, items.gridlist_c_nazwa, v.name, false, false)
guiGridListSetItemData(items.gridlist, row, items.gridlist_c_nazwa, v)
if (tonumber(v.in_use)>0) then
guiGridListSetItemText(items.gridlist, row, items.gridlist_c_use,'Tak', false, false)
guiGridListSetItemColor(items.gridlist, row,items.gridlist_c_use, 255,0,0)
guiGridListSetItemData(items.gridlist, row, items.gridlist_c_use, 1)
else
guiGridListSetItemText(items.gridlist, row, items.gridlist_c_use,'Nie', false, false)
guiGridListSetItemColor(items.gridlist, row, items.gridlist_c_use, 0,255,0)
guiGridListSetItemData(items.gridlist, row, items.gridlist_c_use, tonumber(0))
end
end
end
function items_selectFromEQ()
local selRow, selCol = guiGridListGetSelectedItem(items.gridlist)
if (not selRow) then return end
local itemData = guiGridListGetItemData(items.gridlist, selRow, items.gridlist_c_nazwa)
if (itemData) then
if (itemData.in_use>0) then
triggerServerEvent("item_cancelUsage", localPlayer, itemData)
items_hideEQ()
return
end
-- teraz nastapi weryfikacja itemu, jezeli jest juz uzywany dany item.subtype (czyli np. jezeli gracz ma juz zalozona czapke, zwracamy end)
triggerServerEvent("isItemInUsage", localPlayer, itemData)
items_hideEQ()
end
end
addEventHandler("onClientGUIClick", items.btn_use, items_selectFromEQ, false)
addEventHandler("onClientGUIClick", items.btn_close, items_hideEQ, false)
addEvent("showItemsForPlayer", true)
addEventHandler("showItemsForPlayer", root, items_showEQ) |
ITEM.name = "12g Tri-Ball"
ITEM.model = "models/lostsignalproject/items/ammo/12x70.mdl"
ITEM.width = 2
ITEM.height = 1
ITEM.ammo = "12 Gauge -TR-" // type of the ammo
ITEM.ammoAmount = 30 // amount of the ammo
ITEM.description = ""
ITEM.quantdesc = "A box that contains %s 12 gauge tri-ball shells. "
ITEM.longdesc = "Tri-Ball 12 gauge shell filled with %s mm shot. This round fires three large shots, with relatively high accuracy compared to other shells. Highly lethal at close range. Only suitable for use with smoothbore weapons."
ITEM.price = 750
--ITEM.busflag = "SPECIAL8_1"
ITEM.img = ix.util.GetMaterial("cotz/icons/ammo/ammo_long_22_1.png")
ITEM.weight = 0.04
ITEM.flatweight = 0.03
function ITEM:GetWeight()
return self.flatweight + (self.weight * self:GetData("quantity", self.ammoAmount))
end |
temp=nil
_c=createObject
function createObject(m,x,y,z,a,b,c,i,d,e)
local t=_c(m,x,y,z,a,b,c)
if d then
setElementDimension(t,d)
end
if i then
setElementInterior(t,i)
end
if e then
setElementAlpha(t,e)
end
return t
end
|
local assets =
{
--Asset("ANIM", "anim/arrow_indicator.zip"),
}
local prefabs =
{
"lightninggoat",
}
local function CanSpawn(inst)
return inst.components.herd and not inst.components.herd:IsFull()
end
local function OnSpawned(inst, newent)
if inst.components.herd then
inst.components.herd:AddMember(newent)
end
end
local function OnEmpty(inst)
inst:Remove()
end
local function fn(Sim)
local inst = CreateEntity()
local trans = inst.entity:AddTransform()
inst:AddTag("herd")
inst:AddComponent("herd")
inst.components.herd:SetMemberTag("lightninggoat")
inst.components.herd:SetGatherRange(40)
inst.components.herd:SetUpdateRange(20)
inst.components.herd:SetOnEmptyFn(OnEmpty)
inst:AddComponent("periodicspawner")
inst.components.periodicspawner:SetRandomTimes(TUNING.LIGHTNING_GOAT_MATING_SEASON_BABYDELAY, TUNING.LIGHTNING_GOAT_MATING_SEASON_BABYDELAY_VARIANCE)
inst.components.periodicspawner:SetPrefab("lightninggoat")
inst.components.periodicspawner:SetOnSpawnFn(OnSpawned)
inst.components.periodicspawner:SetSpawnTestFn(CanSpawn)
inst.components.periodicspawner:SetDensityInRange(20, 6)
inst.components.periodicspawner:SetOnlySpawnOffscreen(true)
inst.components.periodicspawner:Start()
return inst
end
return Prefab( "forest/animals/lightninggoatherd", fn, assets, prefabs)
|
vRPncj = {}
Tunnel.bindInterface("vrp_nocarjack",vRPncj)
Proxy.addInterface("vrp_nocarjack",vRPncj)
NCJserver = Tunnel.getInterface("vrp_nocarjack","vrp_nocarjack")
vRPserver = Tunnel.getInterface("vRP","vrp_nocarjack")
vRP = Proxy.getInterface("vRP")
Citizen.CreateThread(function()
while true do
-- gets if player is entering vehicle
if DoesEntityExist(GetVehiclePedIsTryingToEnter(PlayerPedId())) then
-- gets vehicle player is trying to enter and its lock status
local veh = GetVehiclePedIsTryingToEnter(PlayerPedId())
local lock = GetVehicleDoorLockStatus(veh)
-- Get the conductor door angle, open if value > 0.0
local doorAngle = GetVehicleDoorAngleRatio(veh, 0)
-- normalizes chance
if cfg.chance > 100 then
cfg.chance = 100
elseif cfg.chance < 0 then
cfg.chance = 0
end
-- check if got lucky
local lucky = (math.random(100) < cfg.chance)
-- Set lucky if conductor door is open
if doorAngle > 0.0 then
lucky = true
end
-- check if vehicle is in blacklist
local backlisted = false
for k,v in pairs(cfg.blacklist) do
if IsVehicleModel(veh, GetHashKey(v)) then
blacklisted = true
end
end
-- gets ped that is driving the vehicle
local pedd = GetPedInVehicleSeat(veh, -1)
local plate = GetVehicleNumberPlateText(veh)
-- lock doors if not lucky or blacklisted
if (lock == 7 or pedd) then
if not lucky or blacklisted then
NCJserver.setVehicleDoorsForEveryone({veh, 2, plate})
else
NCJserver.setVehicleDoorsForEveryone({veh, 1, plate})
end
end
end
Citizen.Wait(0)
end
end)
function vRPncj.setVehicleDoors(veh, doors)
SetVehicleDoorsLocked(veh, doors)
end
|
return Def.ActorFrame {
Def.BitmapText {
Font = 'Common Normal',
InitCommand = function(self)
self
:skewx(0.5)
:zoom(0.5)
:addy(12)
:maxwidth(72)
end,
SetMessageCommand = function(self, param)
if not param then return end
local ret = THEME:GetString('StepsType', ToEnumShortString(param.StepsType))
self:settext(ret)
end,
},
} |
local DropButton = MakeSushi(3, 'CheckButton', 'DropdownButton', nil, 'UIDropDownMenuButtonTemplate', SushiButtonBase)
if DropButton then
DropButton.left = 16
DropButton.top = 1
DropButton.bottom = 1
else
return
end
--[[ Startup ]]--
function DropButton:OnCreate()
_G[self:GetName() .. 'UnCheck']:Hide()
self.__super.OnCreate(self)
end
function DropButton:OnAcquire()
self.isRadio = true
self.__super.OnAcquire(self)
self:SetCheckable(true)
self:SetChecked(nil)
end
function DropButton:SetTitle(isTitle)
local font = isTitle and GameFontNormalSmall or GameFontHighlightSmall
self:SetNormalFontObject(font)
self:SetHighlightFontObject(font)
end
--[[ Checked ]]--
function DropButton:SetChecked(checked)
if checked then
self:LockHighlight()
else
self:UnlockHighlight()
end
self.__type.SetChecked(self, checked)
self:UpdateTexture()
end
function DropButton:SetCheckable(checkable)
local name = self:GetName()
_G[name .. 'Check']:SetShown(checkable)
_G[name .. 'NormalText']:SetPoint('LEFT', checkable and 20 or 0, 0)
end
function DropButton:SetRadio(isRadio)
self.isRadio = isRadio
self:UpdateTexture()
end
function DropButton:UpdateTexture()
local y = self.isRadio and 0.5 or 0
local x = self:GetChecked() and 0 or 0.5
_G[self:GetName() .. 'Check']:SetTexCoord(x, x+0.5, y, y+0.5)
end |
local lib = {}
local ffi = require'ffi'
local C = ffi.C
local bit = require'bit'
local skt = require'skt'
local APPLANIX_ADDRESS = '192.168.53.100'
-- tcpdump -i any src host 192.168.53.100
local DISPLAY_PORT = 5600
local CONTROL_PORT = 5601
local REALTIME_PORT = 5602
local LOGGING_PORT = 5603
ffi.cdef[[
void * memmove(void *dst, const void *src, size_t len);
]]
-- Header
ffi.cdef[[
typedef struct applanix_hdr {
char start[4];
uint16_t id;
uint16_t byte_count;
double time1;
double time2;
double distance;
uint8_t time_types;
uint8_t distance_type;
} __attribute__((packed)) applanix_hdr_t;
]]
-- Footer
ffi.cdef[[
typedef struct applanix_ftr {
uint16_t checksum;
uint16_t stop;
} __attribute__((packed)) applanix_ftr_t;
]]
-- PPS
ffi.cdef[[
typedef struct pps {
applanix_hdr_t hdr;
uint32_t pps_count;
uint8_t time_sync_status;
uint8_t pad;
applanix_ftr_t ftr;
} __attribute__((packed)) pps_t;
]]
-- DMI
ffi.cdef[[
typedef struct dmi {
applanix_hdr_t hdr;
double signed_distance;
double unsigned_distance;
uint16_t scale_factor;
uint8_t status;
uint8_t type;
uint8_t rate;
uint8_t pad;
applanix_ftr_t ftr;
} __attribute__((packed)) dmi_t;
]]
-- Navigation Metrics
ffi.cdef[[
typedef struct nav_metrics {
applanix_hdr_t hdr;
float errors[12];
uint8_t pad[2];
applanix_ftr_t ftr;
} __attribute__((packed)) nav_metrics_t;
]]
-- Navigation Solution
ffi.cdef[[
typedef struct nav_solution {
applanix_hdr_t hdr;
//--
double latitude;
double longitude;
double altitude;
//--
float vnorth;
float veast;
float vdown;
//--
double roll;
double pitch;
double heading;
//--
double wander;
float track;
//
float speed;
//--
float ang_rate_long;
float ang_rate_trans;
float ang_rate_down;
//--
float acc_long;
float acc_trans;
float acc_down;
//--
uint8_t alignment;
//--
uint8_t pad[1];
applanix_ftr_t ftr;
} __attribute__((packed)) nav_solution_t;
]]
local msg_id = {}
--
local grp_id = {}
grp_id[1] = function(str)
local data = ffi.cast('nav_solution_t*', str)
return 'Nav', data
end
grp_id[2] = function(str)
local data = ffi.cast('nav_metrics_t*', str)
return 'NavMetrics', data
end
grp_id[7] = function(str)
local data = ffi.cast('pps_t*', str)
return 'PPS', data
end
grp_id[15] = function(str)
local data = ffi.cast('dmi_t*', str)
return 'DMI', data
end
grp_id[30] = function(str)
return 'EV3', data
end
grp_id[31] = function(str)
return 'EV4', data
end
grp_id[32] = function(str)
return 'EV5', data
end
grp_id[33] = function(str)
return 'EV6', data
end
grp_id[20] = function(str)
return 'IIN'
end
grp_id[21] = function(str)
return'Base 1 GNSS'
end
grp_id[22] = function(str)
return'Base 2 GNSS'
end
grp_id[23] = function(str)
return'Aux 1 GNSS'
end
grp_id[24] = function(str)
return'Aux 2 GNSS'
end
-- 4k buffer
local BUFFER_SZ = 4096
local buf_rt = ffi.new('uint8_t[?]', BUFFER_SZ)
local idx_rt = 0
local display_skt, control_skt, realtime_skt, logging_skt
local function str2short(str)
return ffi.cast('uint16_t*', str)[0]
end
local function process_realtime(str)
if type(str)~='string' then
return false, "Invalid input"
end
local new_idx = idx_rt + #str
if #str>BUFFER_SZ then
io.stderr:write('BUFFER_SZ TOO SMALL\n')
idx_rt = 0
elseif new_idx>=BUFFER_SZ then
new_idx = 0
end
ffi.copy(buf_rt + idx_rt, str)
idx_rt = new_idx
local idx = 0
local remaining = idx_rt - idx
repeat
local hdr = ffi.cast('applanix_hdr_t*', buf_rt+idx)
local fn = grp_id[hdr.id]
local sz = hdr.byte_count + 8
idx = idx + sz
remaining = idx_rt - idx
if type(fn)=='function' then
local ch, data = fn(ffi.string(hdr, sz))
coroutine.yield(ch, data)
end
until remaining < sz
if idx_rt > idx then
C.memmove(buf_rt, buf_rt + idx, idx_rt - idx)
end
idx_rt = 0
end
local function process_display(str)
if type(str)~='string' then
return false, "Invalid input"
end
local start = str:find'$MSG'
if not start then return end
local stop = str:find'$#'
local checksum = stop and str2short(str:sub(stop-2, stop-1))
--
local id = str2short(str:sub(start+4, start+5))
local byte_count = str2short(str:sub(start+6, start+7))
local transaction = str2short(str:sub(start+8, start+9))
--
end
local function update()
local ret, ids = skt.poll({display_skt.recv_fd, realtime_skt.recv_fd}, 1e3)
local realtime, display
if ids[1] then
-- display
display = process_display(display_skt:recv())
end
if ids[2] then
-- realtime
local id, data = process_realtime(realtime_skt:recv())
end
end
-- Single applanix, single thread...
function lib.init(_ADDRESS)
APPLANIX_ADDRESS = _ADDRESS or APPLANIX_ADDRESS
display_skt = assert(skt.new_sender_receiver(
APPLANIX_ADDRESS,
DISPLAY_PORT,
false))
control_skt = skt.new_sender_receiver(ADDRESS, CONTROL_PORT, false)
realtime_skt = assert(skt.new_stream_receiver(
APPLANIX_ADDRESS,
REALTIME_PORT))
--logging_skt = skt.new_sender_receiver(ADDRESS, LOGGING_PORT, false)
return coroutine.wrap(function()
local running = true
while running do update() end
end)
end
return lib
|
translate.AddLanguage("hr", "Croatian")
LANGUAGE.waiting_on_players = "Čekaju se svi igrači da budu sprijemni."
LANGUAGE.players_ready = "Svi igrači su sprijemni, biranje Zombie Master-a je u tijeku!"
LANGUAGE.changed_player_model_to_x = "Promijenili ste željeni model u %s"
LANGUAGE.trap_activate_for_x = "Aktivirati za %d"
LANGUAGE.trap_create_for_x = "Napraviti zamku za %d"
LANGUAGE.enter_explosion_mode = "Explosion režim je aktivan..."
LANGUAGE.enter_hidden_mode = "Skriven spawn režim je aktivan..."
LANGUAGE.exit_explosion_mode = "Explosion režim više nije aktivan..."
LANGUAGE.exit_hidden_mode = "Skriven spawn režim više nije aktivan..."
LANGUAGE.killmessage_something = "Nešto"
LANGUAGE.toggled_nightvision = "Noćni vid je uključen"
LANGUAGE.zombiemaster_submit = "Zombie Master je izabran \n"
LANGUAGE.round_restarting = "Restartovanje runde je u tijeku...\n"
LANGUAGE.undead_has_won = "Tim Undead-ova je odnio pobjedu!\n"
LANGUAGE.map_changing = "Promijena mape u tijeku...\n"
LANGUAGE.zombiemaster_left = "Zombie Master je napustio!\n"
LANGUAGE.all_humans_left = "Svi preživjeli su napustili!\n"
LANGUAGE.x_has_become_the_zombiemaster = "%s je postao Zombie Master"
LANGUAGE.zm_move_instructions = "Da bi se kretao kao Zombie Master, drži Shift ili svoju +speed tipku, a ako ti je potrebna pomoć pritisni F2 >> Pomoć."
LANGUAGE.population_limit_reached = "Spawnovanje zombija bezuspješno: dostignuta je gornja granica populacije!/n"
LANGUAGE.invalid_surface_for_explosion = "Potraga za mestom da se postavi eksploziv je bila bezuspješna."
LANGUAGE.not_enough_resources = "Nedovoljno resursa.\n"
LANGUAGE.explosion_created = "Eksploziv napravljen."
LANGUAGE.killed_all_zombies = "Eliminisanje svih zombija..."
LANGUAGE.zombie_does_not_fit = "Trenutni zombi se ne uklapa u tu lokaciju!\n"
LANGUAGE.zombie_cant_be_created = "Nijedan zombi se tu ne može stvorit\n"
LANGUAGE.human_can_see_location = "Jedan od preživjelih može videt ovu lokaciju!\n"
LANGUAGE.hidden_zombie_spawned = "Skriven zombi je stvoren."
LANGUAGE.all_zombies_selected = "Svi zombiji su izabrani"
LANGUAGE.trap_created = "Stvaranje okidača zamke..."
LANGUAGE.rally_created = "Stvaranje mjesta okupljanja..."
LANGUAGE.group_created = "Stvaranje grupe..."
LANGUAGE.group_selected = "Biranje grupe..."
LANGUAGE.set_zombies_to_defensive_mode = "Izabrani zombiji su sada u obrambenom režimu"
LANGUAGE.set_zombies_to_offensive_mode = "Izabrani zombiji su sada u napadačkom režimu"
LANGUAGE.humans_have_won = "Tim preživjelih je odnio pobjedu!\n"
LANGUAGE.humans_failed_obj = "Tim preživjelih nije uspela da izvrši svoj cilj!\n"
LANGUAGE.queue_is_full = "Red za čekanje je pun!"
LANGUAGE.tooltip_select_all = "Izabrati sve: Izaberi sve svoje zombije."
LANGUAGE.tooltip_defend = "Odbraniti: Naredi odabranim jedinicama da brane svoju trenutnu lokaciju."
LANGUAGE.tooltip_attack = "Napasti: Naredi odabranim jedinicama da napadnu bilo kog preživjelog koga vide."
LANGUAGE.tooltip_nightvision = "Noćni vid: Uključuje noćni vid."
LANGUAGE.tooltip_explosion_cost_x = "Eksplozija: Klikći po svijetu da bi oduvao objekte od sebe. (Costs %d)."
LANGUAGE.tooltip_expire_zombies = "Odricanje: Odrekni se kontrole nad izabranim jedinicama."
LANGUAGE.tooltip_hidden_zombie_cost_x = "Skriveni priziv: Klikći po svijetu da bi stvorio Shamblera. Jedino je moguće učiniti van vidnog polja preživjelih. (Košta %d)"
LANGUAGE.tooltip_create_squad = "Napraviti odred: Napravi odred od izabranih jedinica."
LANGUAGE.tooltip_select_squad = "Izabrati odred: Izaberi odred za koji si se odlučio. Jedinice u ovom odredu će biti izabrane."
LANGUAGE.npc_class_shambler = "Klasa Shambler"
LANGUAGE.npc_class_banshee = "Klasa Banshee"
LANGUAGE.npc_class_hulk = "Klasa Hulk"
LANGUAGE.npc_class_drifter = "Klasa Drifter"
LANGUAGE.npc_class_immolator = "Klasa Immolator"
LANGUAGE.npc_description_shambler = "Slab i spor, ali ima jak udarac i ruši barikade."
LANGUAGE.npc_description_banshee = "Brz zombi, brži od ostalih. Ali ne može podnijeti toliko veliku štetu."
LANGUAGE.npc_description_hulk = "Veliki. Jak. Hulkovi razbijaju ljude u paramparčad."
LANGUAGE.npc_description_drifter = "Pljuje dezorijentisaću kiselinu po maloj razdaljini."
LANGUAGE.npc_description_immolator = "Spaljuje sve uključujući i sebe u sred borbe."
LANGUAGE.title_playermodels = "Izbor igračkih modela"
LANGUAGE.title_playercolor = "Boja igrača"
LANGUAGE.title_weaponcolor = "Boja oružja"
LANGUAGE.title_objectives = "Ciljevi!"
LANGUAGE.title_spawn_menu = "Spawn meni/Meni za stvaranje"
LANGUAGE.scoreboard_name = "Ime"
LANGUAGE.scoreboard_ping = "Ping"
LANGUAGE.scoreboard_mute = "Mute"
LANGUAGE.scoreboard_deaths = "Broj smrti"
LANGUAGE.scoreboard_kills = "Broj ubistava"
LANGUAGE.preferred_playstyle = "Izaberi svoj playstyle."
LANGUAGE.preferred_willing_zm = "Željan da bude Zombie Master (RTS)."
LANGUAGE.preferred_prefer_survivor = "Radije bi bio preživjeli (FPS)."
LANGUAGE.preferred_prefer_spectator = "Preferiraju se kao Spektator."
LANGUAGE.preferred_dont_ask = "Ne pitaj me ponovo."
LANGUAGE.button_help = "Pomoć"
LANGUAGE.button_playermodel = "Igrački model"
LANGUAGE.button_playercolor = "Boja igrača"
LANGUAGE.button_credits = "Zasluge"
LANGUAGE.button_close = "Zatvori"
LANGUAGE.button_okay = "OK"
LANGUAGE.button_cancel = "Poništi" |
#!/usr/bin/lua
-- $Id: heapsort.lua,v 1.2 2004-06-12 16:19:43 bfulgham Exp $
-- http://shootout.alioth.debian.org
-- contributed by Roberto Ierusalimschy
local IM = 139968
local IA = 3877
local IC = 29573
local LAST = 42
function gen_random(max)
LAST = math.fmod((LAST * IA + IC), IM)
return( (max * LAST) / IM )
end
function heapsort(n, ra)
local j, i, rra
local l = math.floor(n/2) + 1
local ir = n;
while 1 do
if l > 1 then
l = l - 1
rra = ra[l]
else
rra = ra[ir]
ra[ir] = ra[1]
ir = ir - 1
if (ir == 1) then
ra[1] = rra
return
end
end
i = l
j = l * 2
while j <= ir do
if (j < ir) and (ra[j] < ra[j+1]) then
j = j + 1
end
if rra < ra[j] then
ra[i] = ra[j]
i = j
j = j + i
else
j = ir + 1
end
end
ra[i] = rra
end
end
local ary = {}
local N = (tonumber((arg and arg[1])) or 5)
for i=1, N do
ary[i] = gen_random(1.0)
end
heapsort(N, ary)
io.write(string.format("%0.10f\n", ary[N]))
|
-- PLAYER_LEAVING thunk
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local common = ReplicatedStorage:WaitForChild("common")
local Actions = require(common:WaitForChild("Actions"))
local PLAYER_REMOVE = Actions.PLAYER_REMOVE
return function(player)
return function(store)
store:dispatch(PLAYER_REMOVE(player))
end
end |
local MAPPER = require 'utils'
MAPPER.nnoremap('<leader>m', '<cmd> :MinimapToggle<CR>')
|
print("Loading Seat Protection")
if SERVER then
include("protec/init.lua")
AddCSLuaFile("protec/cl_init.lua")
else
include("protec/cl_init.lua")
end
|
--[[
Returns false if the given table has any of the following:
- a key that is neither a number or a string
- a mix of number and string keys
- number keys which are not exactly 1..#t
]]
return function(t)
local containsNumberKey = false
local containsStringKey = false
local numberConsistency = true
local index = 1
for x, _ in pairs(t) do
if type(x) == 'string' then
containsStringKey = true
elseif type(x) == 'number' then
if index ~= x then
numberConsistency = false
end
containsNumberKey = true
else
return false
end
if containsStringKey and containsNumberKey then
return false
end
index = index + 1
end
if containsNumberKey then
return numberConsistency
end
return true
end |
local K, C, L, _ = select(2, ...):unpack()
if C.Automation.ScreenShot ~= true then return end
local CreateFrame = CreateFrame
local function OnEvent(self, event, ...)
K.Delay(1, function() Screenshot() end)
end
local frame = CreateFrame("Frame")
frame:RegisterEvent("ACHIEVEMENT_EARNED")
frame:SetScript("OnEvent", OnEvent) |
local assertEq = test.assertEq
local function log(x) test.log(tostring(x) .. "\n") end
local vi_regex = require('regex.regex')
local compile = vi_regex.compile
local pat = compile('fo+[ab]ar')
assertEq(pat:match("foobar"), {_start=1,_end=6})
assertEq(pat:match("foooobar"), {_start=1,_end=8})
assertEq(pat:match("foblahfoobar"), {_start=7, _end=12})
assertEq(pat:match("foblahfooaar"), {_start=7, _end=12})
assertEq(pat:match("fbar"), nil)
local pat = compile('(?:foo|bar)+')
assertEq(pat:match("asdfoo"), { _start=4, _end=6 })
assertEq(pat:match("asdfobar"), { _start=6, _end=8 })
assertEq(pat:match("asdfoofoobarjkl;"), { _start=4, _end=12 })
assertEq(pat:match("asdfabulous", nil))
local pat = compile('^.foo')
assertEq(pat:match('afoo'), { _start=1, _end=4 })
assertEq(pat:match('jfoo'), { _start=1, _end=4 })
assertEq(pat:match('jjfoo'), nil)
assertEq(pat:match('foo'), nil)
assertEq(pat:match('foo then foo'), nil)
local pat = compile('a.?b')
assertEq(pat:match('abooo'), { _start=1,_end=2 })
assertEq(pat:match('axbooo'), { _start=1,_end=3 })
assertEq(pat:match('axxbooo'), nil)
local pat = compile('a.*b')
assertEq(pat:match('axbcdef'), { _start=1,_end=3 })
assertEq(pat:match('axxbcdef'), { _start=1,_end=4 })
assertEq(pat:match('abcdef'), { _start=1,_end=2 })
assertEq(pat:match('abcdebf'), { _start=1,_end=6 })
assertEq(pat:match('ababab'), { _start=1, _end=6 })
local pat = compile('\\<foo\\>')
assertEq(pat:match('foo'), { _start=1, _end=3 })
assertEq(pat:match('afoo'), nil)
assertEq(pat:match('foob'), nil)
assertEq(pat:match('a foo b'), { _start=3, _end=5 })
assertEq(pat:match('a afoo b'), nil)
assertEq(pat:match('a foob b'), nil)
local pat = compile('10')
assertEq(pat:match('10'), { _start=1, _end=2 })
assertEq(pat:match('10\n'), { _start=1, _end=2 })
local pat = compile('ab[^a-z,]de')
assertEq(pat:match('abcde'), nil)
assertEq(pat:match('abade'), nil)
assertEq(pat:match('abzde'), nil)
assertEq(pat:match('abCde'), { _start=1, _end=5 })
assertEq(pat:match('ab.de'), { _start=1, _end=5 })
assertEq(pat:match('ab,de'), nil)
-- Check that it's case sensitive.
local pat = compile('abc')
assertEq(pat:match('abcde'), { _start=1, _end=3})
assertEq(pat:match('abade'), nil)
assertEq(pat:match('abCde'), nil)
-- Check counts
local pat = compile('ab{3}c')
assertEq(pat:match('abbbc'), { _start=1, _end=5})
assertEq(pat:match('abbc'), nil)
assertEq(pat:match('abbXc'), nil)
assertEq(pat:match('abbbbc'), nil)
local pat = compile('ab{3,}c')
assertEq(pat:match('abbc'), nil)
assertEq(pat:match('abbbc'), { _start=1, _end=5})
assertEq(pat:match('abbbbc'), { _start=1, _end=6})
assertEq(pat:match('abbbbbc'), { _start=1, _end=7})
assertEq(pat:match('abbbbbbc'), { _start=1, _end=8})
local pat = compile('ab{3,5}c')
assertEq(pat:match('abbc'), nil)
assertEq(pat:match('abbbc'), { _start=1, _end=5})
assertEq(pat:match('abbbbc'), { _start=1, _end=6})
assertEq(pat:match('abbbbbc'), { _start=1, _end=7})
assertEq(pat:match('abbbbbbc'), nil)
|
protector.removal_names = ""
minetest.register_chatcommand("delprot", {
params = "",
description = "Remove Protectors near players with names provided (separate names with spaces)",
privs = {server = true},
func = function(name, param)
if not param or param == "" then
minetest.chat_send_player(name,
"Protector Names to remove: "
.. protector.removal_names)
return
end
if param == "-" then
minetest.chat_send_player(name,
"Name List Reset")
protector.removal_names = ""
return
end
protector.removal_names = param
end,
})
minetest.register_abm({
nodenames = {"protector:protect", "protector:protect2"},
interval = 8,
chance = 1,
catch_up = false,
action = function(pos, node)
if protector.removal_names == "" then
return
end
local meta = minetest.get_meta(pos)
local owner = meta:get_string("owner")
--local members = meta:get_string("members")
local names = protector.removal_names:split(" ")
for _, n in pairs(names) do
if n == owner then
minetest.set_node(pos, {name = "air"})
end
end
end
}) |
--- === cp.ui.Sheet ===
---
--- Sheet UI Module.
local require = require
local axutils = require("cp.ui.axutils")
local Button = require("cp.ui.Button")
local Element = require("cp.ui.Element")
local If = require("cp.rx.go.If")
local WaitUntil = require("cp.rx.go.WaitUntil")
local Sheet = Element:subclass("cp.ui.Sheet")
--- cp.ui.Sheet.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function Sheet.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXSheet"
end
--- cp.ui.Sheet(parent, uiFinder) -> Sheet
--- Constructor
--- Creates a new `Sheet` instance.
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - The UI, either a `cp.prop` or a `function`.
---
--- Returns:
--- * A new `Browser` object.
function Sheet:initialize(parent, UI)
Element.initialize(self, parent, UI)
end
--- cp.ui.Sheet.title <cp.prop: string>
--- Field
--- Gets the title of the sheet.
function Sheet.lazy.prop:title()
return axutils.prop(self.UI, "AXTitle")
end
--- cp.ui.Sheet.default <cp.ui.Button>
--- Field
--- The default [Button](cp.ui.Button.md) for the `Sheet`.
function Sheet.lazy.value:default()
return Button(self, axutils.prop(self.UI, "AXDefaultButton"))
end
--- cp.ui.Sheet.cancel <cp.ui.Button>
--- Field
--- The cancel [Button](cp.ui.Button.md) for the `Sheet`.
function Sheet.lazy.value:cancel()
return Button(self, axutils.prop(self.UI, "AXCancelButton"))
end
--- cp.ui.Sheet:hide() -> none
--- Method
--- Hides the sheet by pressing the "Cancel" button, if it exists.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function Sheet:hide()
self:pressCancel()
end
--- cp.ui.Sheet:doHide() -> cp.rx.go.Statement <boolean>
--- Method
--- Attempts to hide the Sheet (if visible) by pressing the [Cancel](#cancel) button.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A [Statement](cp.rx.go.Statement.md) to execute, resolving to `true` if the button was present and clicked, otherwise `false`.
function Sheet.lazy.method:doHide()
return If(self.isShowing):Then(
self:doCancel()
):Then(WaitUntil(self.isShowing():NOT()))
:Otherwise(true)
:TimeoutAfter(10000)
:Label("Sheet:doHide")
end
--- cp.ui.Sheet:doCancel() -> cp.rx.go.Statement <boolean>
--- Method
--- Attempts to hide the Sheet (if visible) by pressing the [Cancel](#cancel) button.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A [Statement](cp.rx.go.Statement.md) to execute, resolving to `true` if the button was present and clicked, otherwise `false`.
function Sheet.lazy.method:doCancel()
return self.cancel:doPress()
end
--- cp.ui.Sheet:doDefault() -> cp.rx.go.Statement <boolean>
--- Method
--- Attempts to press the `default` [Button](cp.ui.Button.md).
---
--- Parameters:
--- * None
---
--- Returns:
--- * A [Statement](cp.rx.go.Statement.md) to execute, resolving to `true` if the button was present and clicked, otherwise `false`.
function Sheet.lazy.method:doDefault()
return self.default:doPress()
end
--- cp.ui.Sheet:doPress(buttonFromLeft) -> cp.rx.go.Statement <boolean>
--- Method
--- Attempts to press the indicated button from left-to-right, if it can be found.
---
--- Parameters:
--- * buttonFromLeft - The number of the button from left-to-right.
---
--- Returns:
--- * a [Statement](cp.rx.go.Statement.md) to execute, resolving in `true` if the button was found and pressed, otherwise `false`.
function Sheet:doPress(buttonFromLeft)
return If(self.UI):Then(function(ui)
local button = axutils.childFromLeft(ui, 1, Button.matches)
if button then
button:doPress()
end
end)
:Otherwise(false)
:ThenYield()
:Label("Sheet:doPress("..tostring(buttonFromLeft)..")")
end
--- cp.ui.Sheet:pressCancel() -> self, boolean
--- Method
--- Presses the Cancel button.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Sheet` object.
--- * `true` if successful, otherwise `false`.
function Sheet:pressCancel()
local _, success = self:cancel():press()
return self, success
end
--- cp.ui.Sheet:pressDefault() -> self, boolean
--- Method
--- Presses the Default button.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `Sheet` object.
--- * `true` if successful, otherwise `false`.
function Sheet:pressDefault()
local _, success = self:default():press()
return self, success
end
--- cp.ui.Sheet:containsText(value[, plain]) -> boolean
--- Method
--- Checks if there are any child text elements containing the exact text or pattern, from beginning to end.
---
--- Parameters:
--- * textPattern - The text pattern to check.
--- * plain - If `true`, the text will be compared exactly, otherwise it will be considered to be a pattern. Defaults to `false`.
---
--- Returns:
--- * `true` if an element's `AXValue` matches the text pattern exactly.
function Sheet:containsText(value, plain)
local textUI = axutils.childMatching(self:UI(), function(element)
local eValue = element:attributeValue("AXValue")
if type(eValue) == "string" then
if plain then
return eValue == value
else
local s,e = eValue:find(value)
--log.df("Found: start: %s, end: %s, len: %s", s, e, eValue:len())
return s == 1 and e == eValue:len()
end
end
return false
end)
return textUI ~= nil
end
return Sheet
|
@dofile "malu/def_define.lua"
@define foreach 'for _i, _ in ipairs(($1)) do $2 end'
@foreach({10,20,30}, print(_))
|
-- 2D Platformer
-- https://github.com/skrolikowski/2d-platformer
--
la = love.audio
lf = love.filesystem
lm = love.mouse
lx = love.math
lg = love.graphics
lj = love.joystick
lt = love.timer
-- pixels please..
lg.setDefaultFilter('nearest', 'nearest')
-- load gamepad mappings
-- lj.loadGamepadMappings('vendor/gamecontrollerdb.txt')
-- vendor packages
pprint = require 'vendor.pprint.pprint'
Camera = require 'vendor.hump.camera'
Gamestate = require 'vendor.hump.gamestate'
Timer = require 'vendor.hump.timer'
-- configurations
require 'src.config'
require 'src.control'
-- local packages
require 'src.gamestates'
require 'src.toolbox'
require 'src.entities'
require 'src.world'
-- load
--
function love.load()
Gamestate.registerEvents()
Gamestate.switch(Gamestates['scene'], {
map = 'res/maps/Cemetary/001.lua',
row = 28,
col = 10
})
end
-- Update
--
function love.update(dt)
Timer.update(dt)
end
---- ---- ---- ----
-- Controls:
-- Key Pressed
--
function love.keypressed(key)
Gamestate.current():onPressed(_.__lower('key_'..key))
end
-- Controls:
-- Key Released
--
function love.keyreleased(key)
Gamestate.current():onReleased(_.__lower('key_'..key))
end
-- Controls:
-- Button Pressed
--
function love.gamepadaxis(joystick, axis, value)
-- print('gamepadaxis', joystick, axis, value)
--
-- analog sticks
if axis == 'leftx' then
Gamestate.current():onPressed('btn_al', { x = value })
elseif axis == 'lefty' then
Gamestate.current():onPressed('btn_al', { y = value })
elseif axis == 'rightx' then
Gamestate.current():onPressed('btn_ar', { x = value })
elseif axis == 'righty' then
Gamestate.current():onPressed('btn_ar', { y = value })
--
-- triggers
elseif axis == 'triggerleft' and value == 1 then
Gamestate.current():onPressed(_.__lower('btn_l2'))
elseif axis == 'triggerleft' and value == 0 then
Gamestate.current():onReleased(_.__lower('btn_l2'))
elseif axis == 'triggerright' and value == 1 then
Gamestate.current():onPressed(_.__lower('btn_r2'))
elseif axis == 'triggerright' and value == 0 then
Gamestate.current():onReleased(_.__lower('btn_r2'))
end
end
-- Controls:
-- Button Pressed
--
function love.gamepadpressed(joystick, button)
-- print('gamepadpressed', button)
--
if button == 'leftshoulder' then
Gamestate.current():onPressed('btn_l1')
elseif button == 'rightshoulder' then
Gamestate.current():onPressed('btn_r1')
else
Gamestate.current():onPressed(_.__lower('btn_'..button))
end
end
-- Controls:
-- Button Released
--
function love.gamepadreleased(joystick, button)
-- print('gamepadreleased', button)
--
if button == 'leftshoulder' then
Gamestate.current():onReleased('btn_l1')
elseif button == 'rightshoulder' then
Gamestate.current():onReleased('btn_r1')
else
Gamestate.current():onReleased(_.__lower('btn_'..button))
end
end |
--
-- Copyright (c) 2015, 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.
--
-- Author: Sumit Chopra <spchopra@fb.com>
-- Michael Mathieu <myrhev@fb.com>
-- Marc'Aurelio Ranzato <ranzato@fb.com>
-- Tomas Mikolov <tmikolov@fb.com>
-- Armand Joulin <ajoulin@fb.com>
-- The LSTM class which extends from RNN class. The main functions
-- are newInputTrain (to train) and test (to do only inference).
require('torch')
require('sys')
require('nn')
require('rnn')
local LSTM = torch.class("LSTM", "RNN")
-- config:
-- n_hidden : number of hidden units (size of the state)
-- initial_val : value of the initial state before any input
-- backprop_freq: number of steps between two backprops and parameter updates
-- backprop_len : number of backward steps during each backprop
-- (should be >= backprop_freq)
-- nets : table containing the networks:
-- encoder : the encoder which produces a hidden state and memory
-- : state using the current input and previous hidden and
-- : memory state
-- decoder : transformation applied to the current hidden state
-- to produce output vector (the next symbol)
--
-- y1 y2
-- ^ ^
-- decoder decoder
-- ^ ^
-- ... {h0, c0} -> lstm_encoder -> {h1, c1} -> lstm_encoder -> {h2, c2} ->
-- ^ ^
-- x1 x2
-- criterion : the loss function to be used
-- ilayers : table of pointers to internal nodes of the encoder graph.
-- This is used so keep track of the weights and gradients
-- associated with various internal nodes of the encoder.
-- For instance this is required during initialization phase.
function LSTM:__init(config, nets, criterion, ilayers)
self.n_hidden = config.n_hidden
self.nets = {encoder = nets.encoder:clone()}
if nets.decoder ~= nil then
self.nets.decoder = nets.decoder:clone()
self.criterion = criterion:clone()
else
assert(nets.decoder_with_loss ~= nil)
self.nets.decoder_with_loss = nets.decoder_with_loss:clone()
end
self.type = torch.Tensor():type()
self.initial_val = config.initial_val
self.backprop_freq = config.backprop_freq
self.batch_size = config.batch_size
self.cuda_device = config.cuda_device
if self.cuda_device then
self:cuda()
end
self:unroll(config.backprop_len)
self:recomputeParameters()
self:reset()
-- set the clipping function
local scale_clip = function(dat, th)
local dat_norm = dat:norm()
if dat_norm > th then
dat:div(dat_norm/th)
end
end
local hard_clip = function(vec, th)
local tmp = vec:float()
local tmpp = torch.data(tmp)
for i = 0, tmp:size(1) - 1 do
if tmpp[i] < - th then
tmpp[i] = - th
else
if tmpp[i] > th then
tmpp[i] = th
end
end
end
vec[{}] = tmp[{}]
end
if config.clip_type == 'scale' then
self.clip_function = scale_clip
elseif config.clip_type == 'hard' then
self.clip_function = hard_clip
else
error('wrong clip type: ' .. config.clip_type)
end
self:set_internal_layers(ilayers)
end
function LSTM:set_internal_layers(layers)
self.ilayers = {}
for name, node in pairs(layers) do
local id = node.id
self.ilayers[name] = self.nets.encoder.fg.nodes[id].data.module
end
end
-- the user shouldnt have to manually call this function
function LSTM:unroll(n)
self.unrolled_nets = {}
local params, gradParams = self.nets.encoder:parameters()
local mem = torch.MemoryFile('w'):binary()
mem:writeObject(self.nets.encoder)
for i = 1, n do
self.unrolled_nets[i] = {}
self.unrolled_nets[i].decoder_gradInput = torch.Tensor():type(self.type)
local reader = torch.MemoryFile(mem:storage(), 'r'):binary()
local clone = reader:readObject()
reader:close()
local cloneParams, cloneGradParams = clone:parameters()
for j = 1, #params do
cloneParams[j]:set(params[j])
cloneGradParams[j]:set(gradParams[j])
end
self.unrolled_nets[i]['encoder'] = clone
collectgarbage()
end
mem:close()
end
-- returns a tensor filled with initial state
function LSTM:get_initial_state(bsize)
if not self.initial_state then
self.initial_state = {}
self.initial_state[1] =
torch.Tensor(bsize, self.n_hidden):type(self.type)
self.initial_state[2] =
torch.Tensor(bsize, self.n_hidden):type(self.type)
self.initial_state[1]:fill(self.initial_val)
self.initial_state[2]:fill(self.initial_val)
end
return self.initial_state
end
-- Runs forward pass in the set of nets, with previous state prev_state
function LSTM:elemForward(nets, input, prev_state, target)
local bsize = input:size(1)
prev_state = prev_state or self:get_initial_state(bsize)
-- store the local inputs and previous state
nets.input = input
nets.prev_state = prev_state
local out_encoder = nets.encoder:forward{input, prev_state}
local out_decoder, err, n_valid = nil, nil, nil
if self.nets.decoder ~= nil then --using the main net (not unrolled)
assert(self.nets.decoder_with_loss == nil)
out_decoder = self.nets.decoder:forward(out_encoder[1])
if target then
err, n_valid = self.criterion:forward(out_decoder, target)
end
else
assert(self.nets.decoder_with_loss ~= nil)
err, n_valid =
self.nets.decoder_with_loss:forward(out_encoder[1], target)
end
n_valid = n_valid or input:size(1)
return out_decoder, out_encoder, err, n_valid
end
-- Runs backward pass on the decode+criterion (or decode_with_loss) modules
function LSTM:elemDecodeBackward(nets, target, learning_rate)
if self.nets.decoder ~= nil then
assert(self.nets.decoder_with_loss == nil)
local decoder_output = self.nets.decoder.output
local derr_do = self.criterion:backward(decoder_output, target)
local gradInput = self.nets.decoder:backward(nets.encoder.output[1],
derr_do)
nets.decoder_gradInput:resizeAs(gradInput):copy(gradInput)
else
assert(self.nets.decoder_with_loss ~= nil)
local gradInput =
self.nets.decoder_with_loss:updateGradInput(nets.encoder.output[1],
target)
nets.decoder_gradInput:resizeAs(gradInput):copy(gradInput)
-- This assumes the module has direct_update mode. Only HSM does:
assert(torch.typename(self.nets.decoder_with_loss) == 'nn.HSM')
self.nets.decoder_with_loss:accGradParameters(
nets.encoder.output[1], target, -learning_rate, true)
end
end
-- Main train function:
-- input : input word or minibatch
-- label : target word or minibatch
-- params:
-- learning_rate : learning rate
-- gradient_clip : if not nil, if the norm of the gradient is larger than
-- this number, project the gradients on the sphere
-- with this radius
-- It returns the sum of the errors and the number of terms in this sum
function LSTM:newInputTrain(input, label, params)
self.i_input = self.i_input + 1
local last_nets = self.unrolled_nets[1]
for i = 1, #self.unrolled_nets-1 do
self.unrolled_nets[i] = self.unrolled_nets[i+1]
end
self.unrolled_nets[#self.unrolled_nets] = last_nets
local output, next_state, err, n_valid = self:elemForward(last_nets, input,
self.state, label)
self:elemDecodeBackward(last_nets, label, params.learning_rate)
self.state = {}
self.state[1] = next_state[1]
self.state[2] = next_state[2]
if self.i_input % self.backprop_freq == 0 then
local gi_state_i = {}
gi_state_i.hid = nil
gi_state_i.mem = nil
local unroll_bound = math.max(1, #self.unrolled_nets - self.i_input + 1)
local j = 1
for i = #self.unrolled_nets, unroll_bound, -1 do
local nets = self.unrolled_nets[i]
local prev_state_i, input_i = nets.prev_state, nets.input
local gi_decoder_net = nets.decoder_gradInput
-- get gradients from decoder
if not gi_state_i.hid then
gi_state_i.hid = gi_decoder_net
elseif j <= self.backprop_freq then
gi_state_i.hid:add(gi_decoder_net)
j = j + 1
else
-- do nothing, since gradients from decoder have
-- already been accounted for
end
-- clip the gradients wrt hidden states
if params.gradInput_clip then
self:clipGradHiddens(gi_state_i.hid, params.gradInput_clip)
end
-- bprop through encoder
if i ~= 1 then
local gi_encoder_net =
nets.encoder:backward({input_i, prev_state_i},
{gi_state_i.hid, gi_state_i.mem})
gi_state_i.hid = gi_encoder_net[2][1]
gi_state_i.mem = gi_encoder_net[2][2]
end
end
-- clip the gradients if specified
if params.gradient_clip then
self:clipGradParams(params.gradient_clip)
end
self:updateParams(self.w, params)
-- zero the gradients for the next time
self.dw:zero()
end
return err, n_valid
end
-- Runs only forward on inputs (1d or 2d sequence of inputs) and compares
-- with labels
-- It returns the sum of the errors and the number of terms in this sum
function LSTM:test(inputs, labels)
local total_err = 0
local total_n_valid = 0
for i = 1, inputs:size(1) do
local output, next_state, err, n_valid = self:elemForward(
self.unrolled_nets[1], inputs[i], self.state, labels[i])
-- self.state = next_state
self.state = {}
self.state[1] = next_state[1]
self.state[2] = next_state[2]
if type(err) ~= 'number' then
err = err[1]
end
total_err = total_err + err
total_n_valid = total_n_valid + n_valid
end
return total_err, total_n_valid
end
|
-- MIT License
-- Copyright (C) 2019 Master nama
-- 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
-- title: Star16 palette demo
-- author: masternama
-- script: lua
t=0
x=96
y=24
function TIC()
if btn(0) then y=y-1 end
if btn(1) then y=y+1 end
if btn(2) then x=x-1 end
if btn(3) then x=x+1 end
cls(13)
spr(1+t%60//30*2,x,y,14,3,0,0,2,2)
print("Star16 Palette Demo",64,84)
t=t+1
rect(13,100,12,30,0)
rect(25,100,12,30,1)
rect(37,100,12,30,2)
rect(49,100,12,30,3)
rect(61,100,12,30,4)
rect(73,100,12,30,5)
rect(85,100,12,30,6)
rect(97,100,12,30,7)
rect(109,100,12,30,8)
rect(121,100,12,30,9)
rect(133,100,12,30,10)
rect(145,100,12,30,11)
rect(157,100,12,30,12)
rect(169,100,12,30,13)
rect(181,100,12,30,14)
rect(193,100,12,30,15)
end
-- <PALETTE>
-- 000:140c1c44243430346d4e4a4e854c30346524d04648757161597dced27d2c8595a16daa2cd2aa996dc2cadad45edeeed6
-- </PALETTE>
|
--A lot of Thanks to iUltimateLP and his mod SimpleTeleporters for inspiration and for the use of His Code and graphics
--this is not used in personal Teleporter but is left over from simpleTeleporter
--[[
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
SimpleTeleporters Config File
Short tutorial:
To the left you see the variable names
After the equal sign, you see the value which you can change
Do not delete anything, this will break the mod.
### Variable Definitions ###
TIER_X_BUFFER_CAPACITY
Defines how much buffer capacity the teleporter has.
In MegaJoule (MJ)
TIER_X_TELEPORT_POWER
Defines how much power the teleporter needs to teleport.
In MegaJoule (MJ)
TIER_X_DISTANCE
Defines the distance the teleporter can handle.
In Tiles (1 Tile = Size of one belt)
TIER_X_COOLDOWN
The cooldown per tier.
In Seconds
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
]]--
-- General Settings
MSG_OUTPUT_MODE = 2 -- 1 is FlyingText; 2 is Chat
FLOW_DIVIDER = 60 -- Global Dividier for calculation Flow limit values
-- TIER 1
TIER_01_BUFFER_CAPACITY = 60
TIER_01_TELEPORT_POWER = 15
TIER_01_DISTANCE = 200
TIER_01_FLOW_LIMIT = TIER_01_BUFFER_CAPACITY / FLOW_DIVIDER
TIER_01_COOLDOWN = 10
|
object_mobile_coa_aclo_tech_hum_m1 = object_mobile_shared_coa_aclo_tech_hum_m1:new {
}
ObjectTemplates:addTemplate(object_mobile_coa_aclo_tech_hum_m1, "object/mobile/coa_aclo_tech_hum_m1.iff")
|
#!/bin/env lua
--[[
220609 anylat: test if file includes any latin chars
that are not part of a valid utf8 sequence
Usage: toutf8 filein
filein can be "-" (or empty) for stdin
Notes:
ignore well-formed utf8 sequences.
]]
he = require "he"
sf = string.format
-- works in 2 steps:
-- 1. replace valid utf8 sequences with @@<n>## where n is the codepoint
-- 2. check for latin1 chars
pat1 = "[\xC2-\xF4][\x80-\xBF]*" -- valid, non ascii, utf8 sequences
function repl1(u)
local r, code = pcall(utf8.codepoint, u)
if r then u = sf("@@<%d>##", code) end
return u
end
pat2 = "[\xA0-\xFF]" -- valid latin1 chars (ignore control chars \x80-\x9F)
function check(s)
s = string.gsub(s, pat1, repl1) -- escape utf8 sequences
if s:find(pat2) then
print(arg[1], "Latin1 char found.")
os.exit()
else
print(arg[1], "No Latin1 char found.")
os.exit(1)
end
end
local t0 = he.fget(arg[1])
check(t0)
|
function list_default(t, k, v)
t[#t + 1] = string.format('%d %d\n', k, v.time)
end
function step(dt, t, remove, list, do_list)
local ids = {}
local tm
local st, err
local k, v
if do_list == nil then
do_list = list_default
end
for k, v in pairs(t) do
do_list(list, k, v)
if v.time <= 0 then
if v.on_remove then
for k1, v1 in ipairs(v.on_remove) do
st, err = pcall(v1, k, v)
if not st then
addError(string.format("step(%s): on_remove[%d]: %s\n",
tbl_name(t), k1, err))
end
end
end
ids[#ids + 1] = k
else
v.time = v.time - dt
if v.callback then
for k1, v1 in ipairs(v.callback) do
st, err = pcall(v1, k, v)
if not st then
addError(string.format("step(%s): callback[%d]: %s\n",
tbl_name(t), k1, err))
ids[#ids + 1] = k
break
end
end
end
end
end
for k, v in ipairs(ids) do
remove(v)
end
end
|
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/GroundToSpaceDamage.lua#2 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/GroundToSpaceDamage.lua $
--
-- Original Author: Steve_Copeland
--
-- $Author: James_Yarrow $
--
-- $Change: 55010 $
--
-- $DateTime: 2006/09/19 19:14:06 $
--
-- $Revision: #2 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("pgevents")
function Definitions()
DebugMessage("%s -- In Definitions", tostring(Script))
Category = "Ground_To_Space_Damage"
IgnoreTarget = true
TaskForce =
{
{
"MainForce"
,"DenySpecialWeaponAttach"
,"DenyHeroAttach"
,"Ground_Empire_Hypervelocity_Gun = 1"
}
}
DebugMessage("%s -- Done Definitions", tostring(Script))
end
function MainForce_Thread()
BlockOnCommand(MainForce.Produce_Force())
-- Keep firing at the biggest (and probably slowest) enemy until it's dead
-- AITarget = FindTarget(MainForce, "Needs_Hypervelocity_Shot", "Enemy_Unit", 1.0)
-- DebugMessage("%s -- Found Target %s", tostring(Script), tostring(AITarget))
-- Try to fire each variety this weapon might be
MainForce.Fire_Special_Weapon("Ground_Empire_Hypervelocity_Gun", AITarget)
-- Rely on the Weapon Online event to fire the gun subsequent times
while TestValid(AITarget) do
Sleep(5)
end
ScriptExit()
end
function MainForce_Special_Weapon_Online(tf, special_weapon)
if TestValid(AITarget) then
special_weapon.Fire_Special_Weapon(AITarget, PlayerObject)
else
ScriptExit()
end
end
|
local E, C, L = select(2, ...):unpack()
if not C.misc.raid_utility.enable then return end
----------------------------------------------------------------------------------------
-- Raid Utility(by Elv22)
----------------------------------------------------------------------------------------
local position = C.misc.raid_utility.position
-- Create main frame
local RaidUtilityPanel = CreateFrame("Frame", "RaidUtilityPanel", T_PetBattleFrameHider)
RaidUtilityPanel:CreatePanel("Default", 170, 145, unpack(position))
RaidUtilityPanel:SetFrameStrata("HIGH")
RaidUtilityPanel:SetFrameLevel(9)
if GetCVarBool("watchFrameWidth") then
RaidUtilityPanel:SetPoint(position[1], position[2], position[3], position[4] + 100, position[5])
end
RaidUtilityPanel.toggled = false
-- Check if We are Raid Leader or Raid Officer
local function CheckRaidStatus()
local _, instanceType = IsInInstance()
if ((GetNumGroupMembers() > 0 and UnitIsGroupLeader("player") and not UnitInRaid("player")) or UnitIsGroupLeader("player") or UnitIsGroupAssistant("player")) and (instanceType ~= "pvp" or instanceType ~= "arena") then
return true
else
return false
end
end
-- Function to create buttons in this module
local function CreateButton(name, parent, template, width, height, point, relativeto, point2, xOfs, yOfs, text)
local b = CreateFrame("Button", name, parent, template)
b:SetWidth(width)
b:SetHeight(height)
b:SetPoint(point, relativeto, point2, xOfs, yOfs)
b:EnableMouse(true)
if text then
b.t = b:CreateFontString(nil, "OVERLAY")
b.t:SetFont(unpack(C.media.standard_font))
b.t:SetPoint("CENTER")
b.t:SetJustifyH("CENTER")
b.t:SetText(text)
end
end
-- Show button
CreateButton("RaidUtilityShowButton", T_PetBattleFrameHider, "UIPanelButtonTemplate, SecureHandlerClickTemplate", RaidUtilityPanel:GetWidth() / 1.5, 18, "TOP", RaidUtilityPanel, "TOP", 0, 0, RAID_CONTROL)
RaidUtilityShowButton:SetFrameRef("RaidUtilityPanel", RaidUtilityPanel)
RaidUtilityShowButton:SetAttribute("_onclick", [=[self:Hide(); self:GetFrameRef("RaidUtilityPanel"):Show();]=])
RaidUtilityShowButton:SetScript("OnMouseUp", function(_, button)
if button == "RightButton" then
if CheckRaidStatus() then
DoReadyCheck()
end
elseif button == "MiddleButton" then
if CheckRaidStatus() then
InitiateRolePoll()
end
elseif button == "LeftButton" then
RaidUtilityPanel.toggled = true
end
end)
-- Close button
CreateButton("RaidUtilityCloseButton", RaidUtilityPanel, "UIPanelButtonTemplate, SecureHandlerClickTemplate", RaidUtilityPanel:GetWidth() / 1.5, 18, "TOP", RaidUtilityPanel, "BOTTOM", 0, -1, CLOSE)
RaidUtilityCloseButton:SetFrameRef("RaidUtilityShowButton", RaidUtilityShowButton)
RaidUtilityCloseButton:SetAttribute("_onclick", [=[self:GetParent():Hide(); self:GetFrameRef("RaidUtilityShowButton"):Show();]=])
RaidUtilityCloseButton:SetScript("OnMouseUp", function() RaidUtilityPanel.toggled = false end)
-- Disband Group button
CreateButton("RaidUtilityDisbandButton", RaidUtilityPanel, "UIPanelButtonTemplate", RaidUtilityPanel:GetWidth() * 0.8, 18, "TOP", RaidUtilityPanel, "TOP", 0, -5, L_RAID_UTIL_DISBAND)
RaidUtilityDisbandButton:SetScript("OnMouseUp", function() StaticPopup_Show("DISBAND_RAID") end)
-- Convert Group button
CreateButton("RaidUtilityConvertButton", RaidUtilityPanel, "UIPanelButtonTemplate", RaidUtilityPanel:GetWidth() * 0.8, 18, "TOP", RaidUtilityDisbandButton, "BOTTOM", 0, -5, UnitInRaid("player") and CONVERT_TO_PARTY or CONVERT_TO_RAID)
RaidUtilityConvertButton:SetScript("OnMouseUp", function()
if UnitInRaid("player") then
C_PartyInfo.ConvertToParty()
RaidUtilityConvertButton.t:SetText(CONVERT_TO_RAID)
elseif UnitInParty("player") then
C_PartyInfo.ConvertToRaid()
RaidUtilityConvertButton.t:SetText(CONVERT_TO_PARTY)
end
end)
-- Role Check button
CreateButton("RaidUtilityRoleButton", RaidUtilityPanel, "UIPanelButtonTemplate", RaidUtilityPanel:GetWidth() * 0.8, 18, "TOP", RaidUtilityConvertButton, "BOTTOM", 0, -5, ROLE_POLL)
RaidUtilityRoleButton:SetScript("OnMouseUp", function() InitiateRolePoll() end)
-- MainTank button
CreateButton("RaidUtilityMainTankButton", RaidUtilityPanel, "UIPanelButtonTemplate, SecureActionButtonTemplate", (RaidUtilityDisbandButton:GetWidth() / 2) - 2, 18, "TOPLEFT", RaidUtilityRoleButton, "BOTTOMLEFT", 0, -5, TANK)
RaidUtilityMainTankButton:SetAttribute("type", "maintank")
RaidUtilityMainTankButton:SetAttribute("unit", "target")
RaidUtilityMainTankButton:SetAttribute("action", "toggle")
-- MainAssist button
CreateButton("RaidUtilityMainAssistButton", RaidUtilityPanel, "UIPanelButtonTemplate, SecureActionButtonTemplate", (RaidUtilityDisbandButton:GetWidth() / 2) - 2, 18, "TOPRIGHT", RaidUtilityRoleButton, "BOTTOMRIGHT", 0, -5, MAINASSIST)
RaidUtilityMainAssistButton:SetAttribute("type", "mainassist")
RaidUtilityMainAssistButton:SetAttribute("unit", "target")
RaidUtilityMainAssistButton:SetAttribute("action", "toggle")
-- Ready Check button
CreateButton("RaidUtilityReadyCheckButton", RaidUtilityPanel, "UIPanelButtonTemplate", RaidUtilityRoleButton:GetWidth() * 0.75, 18, "TOPLEFT", RaidUtilityMainTankButton, "BOTTOMLEFT", 0, -5, READY_CHECK)
RaidUtilityReadyCheckButton:SetScript("OnMouseUp", function() DoReadyCheck() end)
-- World Marker button
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:ClearAllPoints()
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetPoint("TOPRIGHT", RaidUtilityMainAssistButton, "BOTTOMRIGHT", 0, -5)
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetParent("RaidUtilityPanel")
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetHeight(18)
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:SetWidth(RaidUtilityRoleButton:GetWidth() * 0.22)
CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:StripTextures(true)
local MarkTexture = CompactRaidFrameManagerDisplayFrameLeaderOptionsRaidWorldMarkerButton:CreateTexture(nil, "OVERLAY")
MarkTexture:SetTexture("Interface\\RaidFrame\\Raid-WorldPing")
MarkTexture:SetPoint("CENTER", 0, -1)
-- Raid Control Panel
CreateButton("RaidUtilityRaidControlButton", RaidUtilityPanel, "UIPanelButtonTemplate", RaidUtilityRoleButton:GetWidth(), 18, "TOPLEFT", RaidUtilityReadyCheckButton, "BOTTOMLEFT", 0, -5, RAID_CONTROL)
RaidUtilityRaidControlButton:SetScript("OnMouseUp", function()
ToggleFriendsFrame(4)
end)
local function ToggleRaidUtil(self, event)
if InCombatLockdown() then
self:RegisterEvent("PLAYER_REGEN_ENABLED")
return
end
if CheckRaidStatus() then
if RaidUtilityPanel.toggled == true then
RaidUtilityShowButton:Hide()
RaidUtilityPanel:Show()
else
RaidUtilityShowButton:Show()
RaidUtilityPanel:Hide()
end
else
RaidUtilityShowButton:Hide()
RaidUtilityPanel:Hide()
end
if event == "PLAYER_REGEN_ENABLED" then
self:UnregisterEvent("PLAYER_REGEN_ENABLED")
end
end
-- Automatically show/hide the frame if we have Raid Leader or Raid Officer
local LeadershipCheck = CreateFrame("Frame")
LeadershipCheck:RegisterEvent("PLAYER_ENTERING_WORLD")
LeadershipCheck:RegisterEvent("GROUP_ROSTER_UPDATE")
LeadershipCheck:SetScript("OnEvent", ToggleRaidUtil)
-- Support Aurora
if IsAddOnLoaded("Aurora") then
local F = unpack(Aurora)
RaidUtilityPanel:SetBackdropColor(0, 0, 0, 0)
RaidUtilityPanel:SetBackdropBorderColor(0, 0, 0, 0)
RaidUtilityPanelInnerBorder:SetBackdropBorderColor(0, 0, 0, 0)
RaidUtilityPanelOuterBorder:SetBackdropBorderColor(0, 0, 0, 0)
F.CreateBD(RaidUtilityPanel)
end |
local ffi = require("ffi")
local cdata = {}
-- http://www.catb.org/esr/structure-packing/
function cdata:new_struct(name, struct)
ffi.cdef(struct)
self.structs = self.structs or {}
self.structs[name] = ffi.typeof(name)
self.pointers = self.pointers or {}
self.pointers[name] = ffi.typeof(name.."*")
end
function cdata:set_struct(name, data)
return ffi.new(self.structs[name], data)
end
function cdata:encode(data)
return ffi.string(ffi.cast("const char*", data), ffi.sizeof(data))
end
function cdata:decode(name, data)
return ffi.cast(self.pointers[name], data)[0]
end
return cdata
|
local require = require
local EffectManager = require 'std.class'('EffectManager')
local EFFECT_RELATION = require 'data.effect.relational_table'
local LoadTemplate, AddNewTask, NameComparison, GetList, GetEffect, CompareEffectAssociation, RemoveEffect
local effect_script_path = {
'public'
}
function EffectManager:_new()
if not self._instance_ then
self._instance_ = {
_templates_ = LoadTemplate(),
_effects_ = {},
}
end
return self._instance_
end
LoadTemplate = function()
local Table = require 'std.table'
local scripts, data = {}
for _, folder in ipairs(effect_script_path) do
data = select(2, xpcall(require, debug.traceback, Table.concat({'data.effect.', folder, '.init'})))
Table.merge(scripts, data)
end
return scripts
end
function EffectManager:add(setting)
-- 沒有名字或目標都不算是正確的配置表
if not (setting.name and setting.target) then
return self
end
-- 無此效果直接跳出
if not self:getTemplate(setting.name) then
return self
end
-- print(setting.name .. " will be added to Unit" .. setting.target)
if not CompareEffectAssociation(self, setting) then
return self
end
-- 搜尋效果,有的話對該效果建立新的任務
AddNewTask(self, setting)
return self
end
-- 新效果要一一與舊效果比對,根據原子狀態關係表處理關係
-- 共存(0):添加新效果不會影響舊效果 ; 互斥(1):比較優先級,優先級低的會移除
-- 消融(2):新舊效果都移除 ; 4[暫無]:新效果加入並暫停,待舊效果結束後恢復 ; 5[暫無]:添加新效果,舊效果暫停
CompareEffectAssociation = function(self, setting)
local list = GetList(self, setting.target)
local template, status
for i, effect in list:iterator() do
template = self:getTemplate(setting.name)
status = EFFECT_RELATION[effect:getClass()][template.class] or 0 -- 找不到視同共存
-- print("[" .. i .."] " .. effect:getName() .. "->" .. setting.name .. ", status=" .. status)
-- status=0 -> 不做任何動作
if status == 1 then
if effect:getPriority() < (template.priority or 0) then
RemoveEffect(list, i)
else
return false
end
elseif status == 2 then
RemoveEffect(list, i)
return false
end
end
return true
end
function EffectManager:getTemplate(name)
return self._templates_[name]
end
RemoveEffect = function(list, i)
list[i]:remove()
list:delete(i)
end
AddNewTask = function(self, setting)
local effect = self:find(setting.target, setting.name)
if effect then
effect:start(setting)
else
GetList(self, setting.target):append(GetEffect(self, setting.name):start(setting))
end
end
GetEffect = function(self, name)
return require 'war3.effect':new(self._templates_[name], self)
end
function EffectManager:find(target, name)
local index, effect = GetList(self, target):exist(name, NameComparison)
return index and effect or nil
end
function EffectManager:delete(target, name)
local effect = self:find(target, name)
if effect then
GetList(self, target):erase(name, NameComparison)
effect:remove()
end
return self
end
GetList = function(self, target)
if not self._effects_[target] then
self._effects_[target] = require 'std.array':new()
end
return self._effects_[target]
end
NameComparison = function(a, b)
return a:getName() == b
end
return EffectManager
|
-- Everyone loves a buckyball
buckyball = gr.mesh( 'buckyball',
{
{2.118034, -1.000000, 0.809017},
{2.427051, -0.500000, -0.000000},
{2.118034, -1.000000, -0.809017},
{1.618034, -1.809017, 0.500000},
{1.618034, -1.809017, -0.500000},
{0.000000, -2.427051, 0.500000},
{-0.809017, -2.118034, 1.000000},
{-0.500000, -1.618034, 1.809017},
{0.809017, -2.118034, 1.000000},
{0.500000, -1.618034, 1.809017},
{0.809017, -2.118034, -1.000000},
{0.500000, -1.618034, -1.809017},
{-0.500000, -1.618034, -1.809017},
{0.000000, -2.427051, -0.500000},
{-0.809017, -2.118034, -1.000000},
{2.118034, 1.000000, 0.809017},
{1.618034, 1.809017, 0.500000},
{1.618034, 1.809017, -0.500000},
{2.427051, 0.500000, 0.000000},
{2.118034, 1.000000, -0.809017},
{0.500000, 1.618034, 1.809017},
{-0.500000, 1.618034, 1.809017},
{-0.809017, 2.118034, 1.000000},
{0.809017, 2.118034, 1.000000},
{0.000000, 2.427051, 0.500000},
{-0.809017, 2.118034, -1.000000},
{-0.500000, 1.618034, -1.809017},
{0.500000, 1.618034, -1.809017},
{0.000000, 2.427051, -0.500000},
{0.809017, 2.118034, -1.000000},
{1.809017, -0.500000, -1.618034},
{1.809017, 0.500000, -1.618034},
{1.000000, 0.809017, -2.118034},
{1.000000, -0.809017, -2.118034},
{0.500000, 0.000000, -2.427051},
{-0.500000, 0.000000, -2.427051},
{-1.000000, 0.809017, -2.118034},
{-1.809017, 0.500000, -1.618034},
{-1.000000, -0.809017, -2.118034},
{-1.809017, -0.500000, -1.618034},
{-2.427051, -0.500000, -0.000000},
{-2.118034, -1.000000, 0.809017},
{-1.618034, -1.809017, 0.500000},
{-2.118034, -1.000000, -0.809017},
{-1.618034, -1.809017, -0.500000},
{-2.118034, 1.000000, -0.809017},
{-1.618034, 1.809017, -0.500000},
{-1.618034, 1.809017, 0.500000},
{-2.427051, 0.500000, -0.000000},
{-2.118034, 1.000000, 0.809017},
{-1.809017, -0.500000, 1.618034},
{-1.809017, 0.500000, 1.618034},
{-1.000000, 0.809017, 2.118034},
{-1.000000, -0.809017, 2.118034},
{-0.500000, 0.000000, 2.427051},
{1.000000, -0.809017, 2.118034},
{0.500000, 0.000000, 2.427051},
{1.000000, 0.809017, 2.118034},
{1.809017, -0.500000, 1.618034},
{1.809017, 0.500000, 1.618034}
}, {
{59, 58, 0, 1, 18, 15},
{15, 16, 23, 20, 57, 59},
{20, 21, 52, 54, 56, 57},
{54, 53, 7, 9, 55, 56},
{9, 8, 3, 0, 58, 55},
{21, 22, 47, 49, 51, 52},
{49, 48, 40, 41, 50, 51},
{41, 42, 6, 7, 53, 50},
{22, 24, 28, 25, 46, 47},
{25, 26, 36, 37, 45, 46},
{37, 39, 43, 40, 48, 45},
{42, 44, 14, 13, 5, 6},
{44, 43, 39, 38, 12, 14},
{26, 27, 32, 34, 35, 36},
{34, 33, 11, 12, 38, 35},
{27, 29, 17, 19, 31, 32},
{19, 18, 1, 2, 30, 31},
{2, 4, 10, 11, 33, 30},
{29, 28, 24, 23, 16, 17},
{4, 3, 8, 5, 13, 10},
{3, 4, 2, 1, 0},
{8, 9, 7, 6, 5},
{13, 14, 12, 11, 10},
{18, 19, 17, 16, 15},
{23, 24, 22, 21, 20},
{28, 29, 27, 26, 25},
{33, 34, 32, 31, 30},
{38, 39, 37, 36, 35},
{43, 44, 42, 41, 40},
{48, 49, 47, 46, 45},
{53, 54, 52, 51, 50},
{58, 59, 57, 56, 55}})
|
function OnSpellStart(keys) --try to move this to as3
FireGameEvent("tae_build_menu",{pid = keys.caster:GetPlayerID()})
end |
-- Copyright 2015 Control4 Corporation. All rights reserved.
do --Globals
Bindings = {}
ReverseBindings = {}
Devices = {}
ToPlay = {}
end
function ExecuteCommand (strCommand, tParams)
if (strCommand == 'LUA_ACTION' and tParams and tParams.ACTION) then
if (tParams.ACTION == 'NextPlayer') then --this iterates with every selection of the action over the list of players connected to this network
local found, selectnext, selectfirst
if (not PrimaryDevice) then
selectfirst = true
end
for i = 3101, 3132 do
if ((selectnext or selectfirst) and Bindings [i]) then
PrimaryDevice = Bindings [i]
PersistData.PrimaryDevice = PrimaryDevice
found = true
break
elseif (PrimaryDevice and Bindings [i] == PrimaryDevice) then
selectnext = true
end
end
if ((selectnext and not found) or (PrimaryDevice and not (Devices[PrimaryDevice]))) then
PrimaryDevice = nil
PersistData.PrimaryDevice = PrimaryDevice
ExecuteCommand ('LUA_ACTION', {ACTION = 'NextPlayer'})
return
end
local name
if (PrimaryDevice and Devices [PrimaryDevice]) then
name = Devices [PrimaryDevice].NAME
end
C4:UpdateProperty ('Primary Player', name or 'No Players connected')
Timer.GetSettings = AddTimer (Timer.GetSettings, 1, 'SECONDS')
end
end
end
function OnDriverLateInit ()
KillAllTimers ()
if (C4.AllowExecute) then C4:AllowExecute (true) end
C4:urlSetTimeout (20)
DEVICEID = C4:GetProxyDevices ()
if (not PersistData) then PersistData = {} end
PrimaryDevice = PersistData.PrimaryDevice
PersistData.PrimaryDevice = PrimaryDevice
AVAILABLE = {} --table that is initialized to contain the binding IDs of this driver
for i = 3001, 3032 do
table.insert (AVAILABLE, i)
end
for i = 3101, 3132 do
table.insert (AVAILABLE, i)
end
for i = 3201, 3232 do
table.insert (AVAILABLE, i)
end
for i = 4001, 4032 do
table.insert (AVAILABLE, i)
end
CheckBindings ()
for k,v in pairs(Properties) do
OnPropertyChanged(k)
end
end
function OnTimerExpired (idTimer)
if (idTimer == Timer.CheckSettings) then
CheckSettings ()
elseif (idTimer == Timer.PushSettings) then
PushSettings ()
elseif (idTimer == Timer.GetSettings) then
GetSettings ()
elseif (idTimer == Timer.CheckBindings) then
CheckBindings ()
end
end
function ReceivedFromProxy (idBinding, strCommand, tParams)
tParams = tParams or {}
local args = {}
if (tParams.ARGS) then
local parsedArgs = C4:ParseXml(tParams.ARGS)
for _, v in pairs(parsedArgs.ChildNodes) do
args[v.Attributes.name] = v.Value
end
tParams.ARGS = nil
end
dbg (idBinding, strCommand)
if (DEBUGPRINT) then Print (tParams) end
if (DEBUGPRINT) then Print (args) end
if (strCommand == 'BINDING_CHANGE_ACTION') then
Timer.CheckBindings = AddTimer (Timer.CheckBindings, 1, 'SECONDS')
elseif (strCommand == 'SET_INPUT') then
local input = tonumber (tParams.INPUT)
local output = tonumber (tParams.OUTPUT)
C4:SendToProxy (5001, 'INPUT_OUTPUT_CHANGED', {INPUT = input, OUTPUT = output})
if (ToPlay [input]) then
local target = Bindings [output]
C4:SendToDevice (target, 'TO_PLAY', ToPlay [input])
if (input > 3200 and input < 4000) then
ToPlay [input] = nil --only zero out this info if it's from a service driver; if it's the line in or msp zone out, we want to keep that info as it's static
end
end
elseif (strCommand == 'SETTINGS') then
local ms_proxy = tonumber (tParams.MS_PROXY or '')
local amp_proxy = tonumber (tParams.AMP_PROXY or '')
if (ms_proxy and amp_proxy and tParams.UUID) then
local amp_binding, ms_binding
for binding, device in pairs (Bindings) do
if (device == ms_proxy) then ms_binding = binding
elseif (device == amp_proxy) then amp_binding = binding
end
end
ToPlay [ms_binding] = {uri = 'x-rincon:' .. tParams.UUID, class = 'object.item.audioItem'} --this is the line where we handle grouping; this is essentially the command that the "slave" player will receive to select the "master" player in line 120 above.
Devices [ms_proxy] = {}
Devices [amp_proxy] = {}
for k, v in pairs (tParams) do
Devices [ms_proxy] [k] = v
Devices [amp_proxy] [k] = v
end
Devices [ms_proxy].TYPE = 'MS'
Devices [amp_proxy].TYPE = 'AMP'
if (ms_proxy == PrimaryDevice) then
C4:UpdateProperty ('Primary Player', Devices [PrimaryDevice].NAME or 'No Players connected')
end
end
Timer.CheckSettings = AddTimer (CheckSettings, 1, 'SECONDS', false)
elseif (strCommand == 'LINE_IN_DEVICE') then
local deviceID = tonumber (tParams.deviceID)
local source_zp_device = tonumber (tParams.source_zp_device)
local source_device = tonumber (tParams.source_device)
local binding = ReverseBindings [tonumber (deviceID)]
if (binding) then
if (source_zp_device and Devices [source_zp_device]) then
Devices [source_zp_device].LINE_IN_DEVICE = source_device
ToPlay [binding] = {uri = Devices [source_zp_device].UUID}
local line_in_devices_list = {}
for deviceID, info in pairs (Devices) do
if (info.TYPE == 'MS') then
line_in_devices_list [info.UUID] = info.LINE_IN_DEVICE
end
end
for binding, target in pairs (Bindings) do
if (binding > 3100 and binding < 3200) then --this is a media service proxy
C4:SendToDevice (target, 'LINE_IN_DEVICES', line_in_devices_list)
end
end
else
ToPlay [binding] = nil
end
end
elseif (strCommand == 'TO_PLAY') then
local binding = ReverseBindings [tonumber (tParams.DEVICEID or 0)]
if (binding) then
ToPlay [binding] = tParams
end
end
end
function AddTimer (timer, count, units, recur)
local newTimer
if (recur == nil) then recur = false end
if (timer and timer ~= 0) then KillTimer (timer) end
newTimer = C4:AddTimer (count, units, recur)
return newTimer
end
function KillAllTimers ()
for k,v in pairs (Timer or {}) do
if (type (v) == 'number') then
Timer [k] = KillTimer (Timer [k])
end
end
for _, thisQ in pairs (Qs or {}) do
if (thisQ.ConnectingTimer and thisQ.ConnectingTimer ~= 0) then thisQ.ConnectingTimer = KillTimer (thisQ.ConnectingTimer) end
if (thisQ.ConnectedTimer and thisQ.ConnectedTimer ~= 0) then thisQ.ConnectedTimer = KillTimer (thisQ.ConnectedTimer) end
end
end
function KillTimer (timer)
if (timer and type (timer) == 'number') then
return (C4:KillTimer (timer))
else
return (0)
end
end
function Print (data)
if (type (data) == 'table') then
for k, v in pairs (data) do print (k, v) end
elseif (type (data) ~= 'nil') then
print (type (data), data)
else
print ('nil value')
end
end
function CheckBindings ()
for _, binding in pairs (AVAILABLE) do
local target = 0
if (binding > 4000) then
local consumer = C4:GetBoundConsumerDevices (DEVICEID, binding)
for device, _ in pairs (consumer or {}) do
if (target ~= 0) then
print ('Too many connections on binding ' .. binding)
end
target = device
end
else
target = C4:GetBoundProviderDevice (DEVICEID, binding)
end
target = tonumber (target)
local old_device = Bindings [binding]
if (target ~= 0) then --if something is connected to this binding now
Bindings [binding] = target
ReverseBindings [target] = binding
if ((binding > 3100 and binding < 3200) or (binding > 4000)) then --this is a msp driver (zoneplayer or service)
Timer.GetSettings = AddTimer (Timer.GetSettings, 1, 'SECONDS')
end
else
Bindings [binding] = nil
ToPlay [binding] = nil
for t, b in pairs (ReverseBindings) do
if (b == binding) then
ReverseBindings [t] = nil
end
end
if (PrimaryDevice and old_device == PrimaryDevice) then
PrimaryDevice = nil
PersistData.PrimaryDevice = PrimaryDevice
end
if (old_device) then
Devices [old_device] = nil
end
end
end
Timer.CheckSettings = AddTimer (Timer.CheckSettings, 2, 'SECONDS')
end
function CheckSettings ()
if (not (PrimaryDevice and Devices [PrimaryDevice])) then -- if we don't already have a selected device, get one
ExecuteCommand ('LUA_ACTION', {ACTION = 'NextPlayer'})
end
Timer.PushSettings = AddTimer (Timer.PushSettings, 2, 'SECONDS')
end
function GetSettings ()
for i = 3101, 3132 do
if (Bindings [i]) then
C4:SendToDevice (Bindings [i], 'GET_SETTINGS', {}) --connect to the MSP proxy
end
end
for i = 4001, 4032 do
if (Bindings [i]) then
C4:SendToDevice (Bindings [i], 'GET_SETTINGS', {}) --connect to the AMP proxy
end
end
end
function PushSettings ()
local settings
if (PrimaryDevice and Devices and Devices [PrimaryDevice]) then
settings = {}
for k, v in pairs (Devices [PrimaryDevice]) do
settings [k] = v
end
settings.TYPE = nil
settings.BINDING = nil
settings.DEVICE = PrimaryDevice
settings.NET_DEVICE = DEVICEID
else
C4:UpdateProperty ('Primary Player', 'No Players connected')
end
local devices_list = {}
local auto_on_list = {}
local override_list = {}
local device_names_list = {}
local line_in_devices_list = {}
for deviceID, info in pairs (Devices) do
if (info.TYPE == 'MS') then
devices_list [info.UUID] = deviceID
device_names_list [tostring (deviceID)] = info.NAME
auto_on_list [info.UUID] = info.AUTO_ON_ROOMS
override_list [info.UUID] = info.OVERRIDEROOM
line_in_devices_list [info.UUID] = info.LINE_IN_DEVICE
end
end
for binding, target in pairs (Bindings) do
if (binding > 3100 and binding < 3200) then --this is a media service proxy
C4:SendToDevice (target, 'XXYYZZ_DEVICES', devices_list)
C4:SendToDevice (target, 'AUTO_ON_ROOMS', auto_on_list)
C4:SendToDevice (target, 'OVERRIDE_ROOMS', override_list)
C4:SendToDevice (target, 'LINE_IN_DEVICES', line_in_devices_list)
elseif (binding > 3000 and binding < 3100) then --this is a global line in
C4:SendToDevice (target, 'XXYYZZ_DEVICES', device_names_list)
elseif (binding > 3200 and binding < 3300) then --this is a music service
if (settings) then
C4:SendToDevice (target, 'SETTINGS', settings)
end
end
end
end
|
-------------------------------------------------------------------------------
-- ElvUI_ChatTweaks By Crackpot (US, Thrall)
-- Module Created By Klix (EU, Twisting Nether)
-- Based on functionality provided by Prat and/or Chatter
-------------------------------------------------------------------------------
local Module = ElvUI_ChatTweaks:NewModule("Keystone Announce", "AceConsole-3.0", "AceEvent-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("ElvUI_ChatTweaks", false)
Module.name = L["Keystone Announce"]..ElvUI_ChatTweaks.NewSign
Module.namespace = string.gsub(Module.name, " ", "")
local C_Club_GetGuildClubId = C_Club.GetGuildClubId
local C_Club_GetSubscribedClubs = C_Club.GetSubscribedClubs
local C_Club_GetStreams = C_Club.GetStreams
local C_Club_FocusStream = C_Club.FocusStream
local UnitFullName = _G["UnitFullName"]
local GetContainerNumSlots = _G["GetContainerNumSlots"]
local GetContainerItemID = _G["GetContainerItemID"]
local GetContainerItemLink = _G["GetContainerItemLink"]
local C_Club_SendMessage = C_Club.SendMessage
local IsInGroup = _G["IsInGroup"]
local UIDropDownMenu_Initialize = _G["UIDropDownMenu_Initialize"]
local UIDropDownMenu_CreateInfo = _G["UIDropDownMenu_CreateInfo"]
local UIDropDownMenu_AddButton = _G["UIDropDownMenu_AddButton"]
local UIDropDownMenu_SetSelectedName = _G["UIDropDownMenu_SetSelectedName"]
local UIDropDownMenu_SetText = _G["UIDropDownMenu_SetText"]
local CloseDropDownMenus = _G["CloseDropDownMenus"]
local KeystoneID = 158923 -- m+ keystone id
local keystone = nil
local table1 = nil
local communitys = {}
local communitysLine = {}
local TempName = nil
local TempID = nil
local TempName2 = nil
local TempID2 = nil
local SpamCooldown = nil
local DuringMpRun = nil
local db, options
local defaults = {
global = {
inGuild = true,
inParty = true,
--inCommunity = false,
--channelname = "",
channelid = "",
lastCooldownCommunity = 0,
lastCooldownParty = 0,
lastCooldownGuild = 0,
SpamCdTime = "30",
skipResponse = false,
printedOnce = false,
}
}
function Module:OnEnable()
self:RegisterEvent("PLAYER_LOGIN")
self:RegisterEvent("PLAYER_ENTERING_WORLD")
self:RegisterEvent("CHALLENGE_MODE_RESET")
self:RegisterEvent("CHALLENGE_MODE_START")
self:RegisterEvent("CHALLENGE_MODE_COMPLETED")
--self:RegisterEvent("INITIAL_CLUBS_LOADED")
end
function Module:OnInitialize()
self.db = ElvUI_ChatTweaks.db:RegisterNamespace(Module.namespace, defaults)
db = self.db.global
self.debug = ElvUI_ChatTweaks.db.global.debugging
end
function Module:OnDisable()
self:UnregisterAllEvents()
end
local function getClubs()
local GuildClubID = C_Club_GetGuildClubId()
table1 = C_Club_GetSubscribedClubs();
for in1, da1 in ipairs(table1) do
for key, value in pairs(da1) do
if key == "name" then
TempName = value
end
if key == "clubId" then
TempID = value
end
end
local TEMPTABLE = C_Club_GetStreams(TempID)
for in2, da2 in ipairs(TEMPTABLE) do
for key, value in pairs(da2) do
if key == "name" then
TempName2 = value
end
if key == "streamId" then
TempID2 = value
end
end
if GuildClubID ~= TempID then
communitysLine = string.format("%s-%s|%s:%s", TempName, TempName2, TempID, TempID2)
table.insert(communitys, communitysLine)
end
end
end
end
local function SetFocus(ClubStreamID)
local t1 = nil
local First = nil
local Second = nil
if ClubStreamID ~= nil and ClubStreamID ~= "" then
if ClubStreamID == "ALL" then
if table.getn(communitys) == 0 then
getClubs()
end
for comIndex, comData in ipairs(communitys) do
First, Second = comData:match("([^,]+)|([^,]+)")
clubID, StreamID = Second:match("([^,]+):([^,]+)")
t1 = C_Club_FocusStream(clubID, StreamID)
end
else
First, Second = ClubStreamID:match("([^,]+):([^,]+)")
t1 = C_Club_FocusStream(First, Second)
end
end
end
local function keypost(force, guild, community, streamid)
local fullName, realm = UnitFullName("player")
--keystone = nil -- reset Keystone
for bag = 0, NUM_BAG_SLOTS do
local numSlots = GetContainerNumSlots(bag)
for slot = 1, numSlots do
if (GetContainerItemID(bag, slot) == KeystoneID) then
local link = GetContainerItemLink(bag, slot)
if force or (keystone and keystone ~= link) then
local message = string.format("%s-%s: %s", fullName, realm, link)
if (community ~= nil) and (streamid ~= nil) then
C_Club_SendMessage(community, streamid, message);
return
end
if guild then
SendChatMessage(link, "GUILD")
else
SendChatMessage(link, "PARTY")
end
end
--keystone = link
return
end
end
end
end
function Module:MoreEvents()
if DuringMpRun ~= true then
if db.inGuild then
self:RegisterEvent("CHAT_MSG_GUILD")
else
self:UnregisterEvent("CHAT_MSG_GUILD")
end
--[[if db.inCommunity then
self:RegisterEvent("CLUB_MESSAGE_ADDED")
else
self:UnregisterEvent("CLUB_MESSAGE_ADDED")
end]]
--local inInstance, instanceType = IsInInstance()
--local isInstanceGroup = IsInGroup(LE_PARTY_CATEGORY_INSTANCE)
--local isPartyGroup = IsInGroup()
if db.inParty then
self:RegisterEvent("CHAT_MSG_PARTY")
self:RegisterEvent("CHAT_MSG_PARTY_LEADER")
else
self:UnregisterEvent("CHAT_MSG_PARTY")
self:UnregisterEvent("CHAT_MSG_PARTY_LEADER")
end
end
end
local function getBoolean(val)
if val then
return true
else
return false
end
end
function Module:CHAT_MSG_GUILD()
local TimeGuild = GetTime()
local NewTimeGuild = TimeGuild + tonumber(db.SpamCdTime)
if select(1) == "!ctk" or select(1) == "!keys" then
if tonumber(db.lastCooldownGuild) < TimeGuild then
keypost(true,true,nil,nil)
db.lastCooldownGuild = NewTimeGuild
end
end
end
function Module:CHAT_MSG_PARTY()
local TimeParty = GetTime()
local NewTimeParty = TimeParty+tonumber(db.SpamCdTime)
if select(1) == "!ctk" or select(1) == "!keys" then
if tonumber(db.lastCooldownParty) < TimeParty then
keypost(true, nil, nil, nil)
db.lastCooldownParty = NewTimeParty
end
end
end
function Module:CHAT_MSG_PARTY_LEADER()
local TimeParty = GetTime()
local NewTimeParty = TimeParty+tonumber(db.SpamCdTime)
if select(1) == "!ctk" or select(1) == "!keys" then
if tonumber(db.lastCooldownParty) < TimeParty then
keypost(true, nil, nil, nil)
db.lastCooldownParty = NewTimeParty
end
end
end
function Module:CLUB_MESSAGE_ADDED()
local clubId, streamId, messageId
local GuildClubID = C_Club_GetGuildClubId()
local Time = GetTime()
local NewTime = Time+tonumber(db.SpamCdTime)
local Info = C_Club.GetMessageInfo(clubId, streamId, messageId)
if tostring(clubId) ~= tostring(GuildClubID) then
if tonumber(db.lastCooldownCommunity) < Time then
if db.channelid ~= "ALL" then
local one1, two1 = db.channelid:match("([^,]+):([^,]+)")
--SetFocus(db.channelid) -- Temp disabled
if tostring(clubId) == tostring(one1) then
if tostring(streamId) == tostring(two1) then
if Info.content == "!ctk" or Info.content == "!keys" then
keypost(true, nil, clubId, streamId)
db.lastCooldownCommunity = NewTime
end
end
end
else
if Info.content == "!ctk" or Info.content == "!keys" then
keypost(true, nil, clubId, streamId)
db.lastCooldownCommunity = NewTime
end
end
end
else
return
end
end
function Module:INITIAL_CLUBS_LOADED()
SetFocus(db.channelid)
end
function Module:PLAYER_ENTERING_WORLD()
DuringMpRun = false
Module:MoreEvents()
end
function Module:PLAYER_LOGIN()
db.lastCooldownCommunity = "0"
db.lastCooldownParty = "0"
db.lastCooldownGuild = "0"
end
function Module:CHALLENGE_MODE_RESET()
end
function Module:CHALLENGE_MODE_START()
DuringMpRun = true
if db.skipResponse == true then
self:UnregisterEvent("CHAT_MSG_GUILD")
self:UnregisterEvent("CHAT_MSG_PARTY")
self:UnregisterEvent("CHAT_MSG_PARTY_LEADER")
self:UnregisterEvent("CLUB_MESSAGE_ADDED")
end
end
function Module:CHALLENGE_MODE_COMPLETED()
DuringMpRun = false
Module:MoreEvents()
end
--[[function Module:UIDropDownMenu_Initialize(dropDown, function(self, level, menuList)
local info = UIDropDownMenu_CreateInfo()
info.text, info.arg1, info.arg2, info.checked = L["AllCommunity"], L["AllCommunity"], "ALL", false
info.func = self.SetValue
UIDropDownMenu_AddButton(info, level)
if table.getn(communitys) == 0 then
getClubs()
end
for in2, da2 in ipairs(communitys) do
one, two = da2:match("([^,]+)|([^,]+)")
info.func = self.SetValue
info.text, info.arg1, info.arg2, info.checked = one, one, two, false
UIDropDownMenu_AddButton(info, level)
UIDropDownMenu_SetSelectedName(dropDown, db.channelname, true)
end
end)
function dropDown:SetValue(text, arg1, arg2, checked)
db.channelname = text
db.channelid = arg1
UIDropDownMenu_SetText(dropDown, text)
CloseDropDownMenus()
end
end]]
function Module:GetOptions()
if not options then
options = {
inParty = {
order = 15,
type = "toggle",
name = L["Party"],
desc = L["Activate in 5-man instances."],
get = function(info) return db[ info[#info] ] end,
set = function(info, value) db[ info[#info] ] = value; end,
},
inGuild = {
order = 16,
type = "toggle",
name = L["Guild"],
desc = L["Activate in guild."],
get = function(info) return db[ info[#info] ] end,
set = function(info, value) db[ info[#info] ] = value; end,
},
SpamCdTime = {
order = 17,
type = "input",
name = L["Spam CoolDown"],
desc = L["Enter a value in seconds."],
get = function(info) return db[ info[#info] ] end,
set = function(info, value) db[ info[#info] ] = value; end,
},
space1 = {
order = 18,
type = "description",
name = "",
},
--[[inCommunity = {
order = 19,
type = "toggle",
name = L["Active in your selected community"],
--desc = L[""],
get = function(info) return db[ info[#info] ] end,
set = function(info, value) db[ info[#info] ] = value; end,
},
channelname = {
order = 20,
type = "select",
name = L["Available communities"],
get = function(info) return db[ info[#info] ] end,
set = function(info, value) db[ info[#info] ] = value; end,
},]]
skipResponse = {
order = 21,
type = "toggle",
name = L["Silence in M+"],
desc = L["Do not reply while in M+ dungeons."],
get = function(info) return db[ info[#info] ] end,
set = function(info, value) db[ info[#info] ] = value; end,
},
}
end
return options
end
function Module:Info()
return L["This module keeps watch on your chat for certain commands and responds accordingly.\nType |cff00ff96!ctk|r or |cff00ff96!keys|r to pull keystone information."]
end
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_terrorblade_metamorphosis_lua_aura = class({})
--------------------------------------------------------------------------------
-- Classifications
function modifier_terrorblade_metamorphosis_lua_aura:IsHidden()
return false
end
function modifier_terrorblade_metamorphosis_lua_aura:IsDebuff()
return false
end
function modifier_terrorblade_metamorphosis_lua_aura:IsStunDebuff()
return false
end
function modifier_terrorblade_metamorphosis_lua_aura:IsPurgable()
return false
end
--------------------------------------------------------------------------------
-- Initializations
function modifier_terrorblade_metamorphosis_lua_aura:OnCreated( kv )
-- references
self.radius = self:GetAbility():GetSpecialValueFor( "metamorph_aura_tooltip" )
if not IsServer() then return end
end
function modifier_terrorblade_metamorphosis_lua_aura:OnRefresh( kv )
self:OnCreated( kv )
end
function modifier_terrorblade_metamorphosis_lua_aura:OnRemoved()
end
function modifier_terrorblade_metamorphosis_lua_aura:OnDestroy()
end
--------------------------------------------------------------------------------
-- Aura Effects
function modifier_terrorblade_metamorphosis_lua_aura:IsAura()
return true
end
function modifier_terrorblade_metamorphosis_lua_aura:GetModifierAura()
return "modifier_terrorblade_metamorphosis_lua"
end
function modifier_terrorblade_metamorphosis_lua_aura:GetAuraRadius()
return self.radius
end
function modifier_terrorblade_metamorphosis_lua_aura:GetAuraDuration()
return 1
end
function modifier_terrorblade_metamorphosis_lua_aura:GetAuraSearchTeam()
return DOTA_UNIT_TARGET_TEAM_FRIENDLY
end
function modifier_terrorblade_metamorphosis_lua_aura:GetAuraSearchType()
return DOTA_UNIT_TARGET_HERO
end
function modifier_terrorblade_metamorphosis_lua_aura:GetAuraSearchFlags()
return 0
end
function modifier_terrorblade_metamorphosis_lua_aura:GetAuraEntityReject( hEntity )
if IsServer() then
if hEntity:GetPlayerOwnerID()~=self:GetParent():GetPlayerOwnerID() then
return true
end
end
return false
end |
local t = {}
t[#t+1] = 1
t[#t + 1] = 2
t[#t+2] = 3
t[#t+{}] = 4
t[#t] = 5
t[t] = 6
t[{}+1]=7
|
local selector = {}
selector.image = engine.graphics.newImage(game.path .. "data/images/selector.png")
selector.x = 1 * 64
selector.y = 1 * 64
function selector.setPos(x, y)
selector.x, selector.y = x, y
end
function selector.setTile(x, y)
selector.x, selector.y = x * 64, y * 64
end
function selector.draw()
love.graphics.draw(selector.image, selector.x, selector.y)
end
return selector |
local macosx = {
Env = {
CPPDEFS = { "EMGUI_MACOSX" },
CCOPTS = {
"-Wall",
"-mmacosx-version-min=10.7",
"-Wno-format-security",
"-Wno-deprecated-declarations", -- TickCount issue no Mountain Lion (needs to be fixed)
"-I.", "-DMACOSX", "-Wall",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3"; Config = "*-*-release" },
},
PROGOPTS = {
"-mmacosx-version-min=10.7",
}
},
Frameworks = { "Cocoa" },
}
local win32 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
"/W4", "/I.", "/WX", "/DUNICODE", "/FS", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4996", "/wd4389", "/Wv:18",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
},
},
}
local linux = {
Env = {
CPPDEFS = { "EMGUI_UNIX" },
CCOPTS = {
"-I.",
"`sdl-config --cflags`",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O2"; Config = "*-*-release" },
},
LIBS = {
{"pthread", "m"; Config = "linux-*-*" },
},
},
}
Build {
Units = "units.lua",
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "win32-msvc", DefaultOnHost = { "windows" }, Inherit = win32, Tools = { "msvc" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = linux, Tools = { "gcc" } },
},
IdeGenerationHints = {
Msvc = {
PlatformMappings = {
['win32-msvc'] = 'Win32',
},
VariantMappings = {
['production'] = 'Production',
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['RocketEditor.sln'] = { } -- will get everything
},
},
}
|
require('class')
AreaTable = class(function(self, offsetx, offsety, width, height)
self.offsetx = offsetx or 0
self.offsety = offsety or 0
-- self.width = width
-- self.height = height
self._pos = {}
end)
local function resolve(x, y, width, height)
-- if(x > (offsetx + width) or x < offsetx) then
-- error(string.format('Invalid X position: %s (must be %s <= x <= %s)', x, offsetx, offsetx+width))
-- return
-- elseif(y > (offsety + height) or y < offsety) then
-- error(string.format('Invalid Y position: %s (must be %s <= y <= %s)', y, offsety, offsety+height))
-- return
-- end
-- if(x > width or x < 0) then
-- error(string.format('Invalid X position: %s (must be 0 <= x <= %s)', x, width))
-- return
-- elseif(y > height or y < 0) then
-- error(string.format('Invalid Y position: %s (must be 0 <= y <= %s)', y, height))
-- return
-- end
-- y << 32 | x
return (y * 4294967296) + x
end
local floor = math.floor
local ti = table.insert
function AreaTable:build()
local ret = {}
for k,v in pairs(self._pos) do
local x = k % 4294967296
local y = floor(k / 4294967296)
v['position'] = {self.offsetx+x, self.offsety+y}
ti(ret, v)
end
return ret
end
function AreaTable:set(x, y, val)
self._pos[resolve(x, y)] = val
end |
-- This is exclusively for the debug options panel and Debug-specific commands that do not appear in a normal build.
-- This entire file is excluded from packaging and it is not localized intentionally.
local AddonName, Addon = ...
local L = Addon:GetLocale()
-- Sets up all the console commands for debug functions in this file.
function Addon:SetupDebugConsoleCommands()
self:AddConsoleCommand("debug", "Toggle Debug. No args prints channels. Specify channel to toggle.",
function(channel)
if not channel then
Addon:PrintDebugChannels()
else
Addon:ToggleDebug(channel)
end
end)
self:AddConsoleCommand("disabledebug", "Turn off all debug channels.", "DisableAllDebugChannels")
self:AddConsoleCommand("link", "Dump hyperlink information", "DumpLink_Cmd")
self:AddConsoleCommand("simulate", "Simulates deleting and selling items, without actually doing it.", "ToggleSimulate_Cmd")
self:AddConsoleCommand("cache", "Clears all caches.", "ClearCache_Cmd")
self:AddConsoleCommand("profile", "Profile management.", "Profile_Cmd")
-- Register debug channels for the addon. Register must be done after addon loaded.
Addon:RegisterDebugChannel("autosell")
Addon:RegisterDebugChannel("blocklists")
Addon:RegisterDebugChannel("config")
Addon:RegisterDebugChannel("databroker")
Addon:RegisterDebugChannel("destroy")
Addon:RegisterDebugChannel("events")
Addon:RegisterDebugChannel("extensions")
Addon:RegisterDebugChannel("history")
Addon:RegisterDebugChannel("historystats")
Addon:RegisterDebugChannel("itemerrors")
Addon:RegisterDebugChannel("items")
Addon:RegisterDebugChannel("itemproperties")
Addon:RegisterDebugChannel("profile")
Addon:RegisterDebugChannel("rules")
Addon:RegisterDebugChannel("rulesdialog")
Addon:RegisterDebugChannel("rulesengine")
Addon:RegisterDebugChannel("test")
Addon:RegisterDebugChannel("threads")
Addon:RegisterDebugChannel("tooltip")
Addon:RegisterDebugChannel("tooltiperrors")
end
-- Debug Commands
function Addon:DumpLink_Cmd(arg)
self:Print("Link: "..tostring(arg))
self:Print("Raw: "..gsub(arg, "\124", "\124\124"))
self:Print("ItemString: "..tostring(self:GetLinkFromString(arg)))
local props = self:GetLinkPropertiesFromString(arg)
for i, v in pairs(props) do
self:Print("["..tostring(i).."] "..tostring(v))
end
self:Print("ItemInfo:")
local itemInfo = {GetItemInfo(tostring(arg))}
for i, v in pairs(itemInfo) do
self:Print("["..tostring(i).."] "..tostring(v))
end
end
function Addon:ToggleSimulate_Cmd()
Addon:SetDebugSetting("simulate", not Addon:GetDebugSetting("simulate"))
Addon:Print("Simulate set to %s", tostring(Addon:GetDebugSetting("simulate")))
end
function Addon:ClearCache_Cmd()
Addon:ClearItemCache()
Addon:ClearResultCache()
Addon:Print("Item cache and result cache cleared.")
end
function Addon:Profile_Cmd(cmd, arg1, arg2)
if cmd then
cmd = string.lower(cmd)
end
if not cmd then
local profiles = Addon:GetProfileList()
local active = Addon:GetProfile()
Addon:Print("All available profiles:")
for _, profile in pairs(profiles) do
Addon:Print(" %s [%s]", tostring(profile:GetName()), tostring(profile:GetId()))
end
Addon:Print("Active profile: %s", tostring(active:GetName()))
elseif cmd == "get" then
local active = Addon:GetProfile()
Addon:Print("Active profile: %s", tostring(active:GetName()))
elseif cmd == "set" and type(arg1) == "string" then
if not Addon:ProfileExists(arg1) then
Addon:Print("Profile '%s' does not exist.", arg1)
return
end
if Addon:SetProfile(arg1) then
Addon:Print("Active profile set to '%s'", arg1)
else
Addon:Print("Failed setting active profile.")
end
elseif cmd == "copy" and type(arg1) == "string" and type(arg2) == "string" then
if not Addon:ProfileExists(arg1) then
Addon:Print("Profile '%s' does not exist.", arg1)
return
end
if Addon:ProfileExists(arg2) then
Addon:Print("Profile '%s' already exists.", arg2)
return
end
if Addon:CopyProfile(arg1, arg2) then
Addon:Print("Profile '%s' copied as profile '%s'", arg1, arg2)
else
Addon:Print("Failed copying the profile.")
end
elseif cmd == "delete" and type(arg1) == "string" then
if not Addon:ProfileExists(arg1) then
Addon:Print("Profile '%s' does not exist.", arg1)
return
end
if Addon:DeleteProfile(arg1) then
Addon:Print("Profile '%s' has been deleted.", arg1)
else
Addon:Print("Failed deleting the profile.")
end
elseif cmd == "create" and type(arg1) == "string" then
if Addon:ProfileExists(arg1) then
Addon:Print("Profile '%s' already exists.", arg1)
return
end
if Addon:NewProfile(arg1) then
Addon:Print("Profile '%s' has been created and set to the active profile.", arg1)
else
Addon:Print("Failed creating the profile.")
end
elseif cmd == "rename" and type(arg1) == "string" and type(arg2) == "string" then
if not Addon:ProfileExists(arg1) then
Addon:Print("Profile '%s' does not exist.", arg1)
return
end
if Addon:RenameProfile(arg1, arg2) then
Addon:Print("Profile '%s' has been renamed to '%s'.", arg1, arg2)
else
Addon:Print("Failed renaming the profile.")
end
else
Addon:Print("profile usage: <none> | get | set | create | copy | delete | rename")
end
end
-- Beyond this point are debug related functions that are not packaged.
function Addon:DumpTooltipItemProperties()
local props = self:GetItemPropertiesFromTooltip()
if not props then return end
self:Print("Properties for "..props["Link"])
-- Print non-derived properties first.
for i, v in Addon.orderedPairs(props) do
if not string.find(i, "^Is") then
local val = v
if type(v) == "table" then
val = "{"..table.concat(v, ", ").."}"
end
self:Print(" [%s] %s", tostring(i), tostring(val))
end
end
-- Print all the derived properties ("Is*") together.
for i, v in Addon.orderedPairs(props) do
if string.find(i, "^Is") then
self:Print(" ["..tostring(i).."] "..tostring(v))
end
end
end
function Addon:DumpItemPropertiesFromTooltip()
Addon:DumpTooltipItemProperties()
end
Addon:MakePublic(
"DumpItemPropertiesFromTooltip",
function () Addon:DumpItemPropertiesFromTooltip() end,
"DumpItemPropertiesFromTooltip",
"Dumps properties for item over toolip.")
-- Sorted Pairs from Lua-Users.org. We use this for pretty-printing tables for debugging purposes.
function Addon.__genOrderedIndex( t )
local orderedIndex = {}
for key in pairs(t) do
table.insert( orderedIndex, key )
end
table.sort( orderedIndex )
return orderedIndex
end
function Addon.orderedNext(t, state)
-- Equivalent of the next function, but returns the keys in the alphabetic
-- order. We use a temporary ordered key table that is stored in the
-- table being iterated.
local key = nil
if state == nil then
-- the first time, generate the index
t.__orderedIndex = Addon.__genOrderedIndex( t )
key = t.__orderedIndex[1]
else
-- fetch the next value
for i = 1,table.getn(t.__orderedIndex) do
if t.__orderedIndex[i] == state then
key = t.__orderedIndex[i+1]
end
end
end
if key then
return key, t[key]
end
-- no more value to return, cleanup
t.__orderedIndex = nil
return
end
function Addon.orderedPairs(t)
-- Equivalent of the pairs() function on tables. Allows to iterate
-- in order
return Addon.orderedNext, t, nil
end |
---@class Iterator : java.util.Iterator
Iterator = {}
---@public
---@return Object
function Iterator:next() end
---@public
---@return boolean
function Iterator:hasNext() end
---@public
---@return void
function Iterator:remove() end
---@public
---@param arg0 Consumer|Unknown
---@return void
function Iterator:forEachRemaining(arg0) end
|
local array = require 'pl.array2d'
local asserteq = require('pl.test').asserteq
local L = require 'pl.utils'. string_lambda
local A = {
{1,2,3,4},
{10,20,30,40},
{100,200,300,400},
{1000,2000,3000,4000},
}
asserteq(array.column(A,2),{2,20,200,2000})
asserteq(array.reduce_rows('+',A),{10,100,1000,10000})
asserteq(array.reduce_cols('+',A),{1111,2222,3333,4444})
--array.write(A)
local dump = require 'pl.pretty'.dump
asserteq(array.range(A,'A1:B1'),{1,2})
asserteq(array.range(A,'A1:B2'),{{1,2},{10,20}})
asserteq(
array.product('..',{1,2,3},{'a','b','c'}),
{{'1a','2a','3a'},{'1b','2b','3b'},{'1c','2c','3c'}}
)
asserteq(
array.product('{}',{1,2},{'a','b','c'}),
{{{1,'a'},{2,'a'}},{{1,'b'},{2,'b'}},{{1,'c'},{2,'c'}}}
)
asserteq(
array.flatten {{1,2},{3,4},{5,6}},
{1,2,3,4,5,6}
)
A = {{1,2,3},{4,5,6}}
-- flatten in column order!
asserteq(
array.reshape(A,1,true),
{{1,4,2,5,3,6}}
)
-- regular row-order reshape
asserteq(
array.reshape(A,3),
{{1,2},{3,4},{5,6}}
)
asserteq(
array.new(3,3,0),
{{0,0,0},{0,0,0},{0,0,0}}
)
asserteq(
array.new(3,3,L'|i,j| i==j and 1 or 0'),
{{1,0,0},{0,1,0},{0,0,1}}
)
asserteq(
array.reduce2('+','*',{{1,10},{2,10},{3,10}}),
60 -- i.e. 1*10 + 2*10 + 3*10
)
A = array.new(4,4,0)
B = array.new(3,3,1)
array.move(A,2,2,B)
asserteq(A,{{0,0,0,0},{0,1,1,1},{0,1,1,1},{0,1,1,1}})
|
ATTRIBUTE.name = "Dexterity"
ATTRIBUTE.desc = "Increases jump height, and reflexes"
ATTRIBUTE.maxValue = 100
ATTRIBUTE.noStartBonus = false
function ATTRIBUTE:onSetup(client, value)
end |
-- role logger
local log = require('log')
local function role_log(role_name)
local function role_log_msg(fmtstr, ...)
return role_name .. ": " .. fmtstr, ...
end
return {
info = function(...) log.info(role_log_msg(...)) end,
warn = function(...) log.warn(role_log_msg(...)) end,
}
end
return {
role_log = role_log
}
|
-- Urho2D sprite example.
-- This sample demonstrates:
-- - Creating a 2D scene with sprite
-- - Displaying the scene using the Renderer subsystem
-- - Handling keyboard to move and zoom 2D camera
-- - Usage of Lua Closure to update scene
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateInstructions()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Hook up to the frame update events
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will
-- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it
-- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically
-- optimizing manner
scene_:CreateComponent("Octree")
-- Create a scene node for the camera, which we will move around
-- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically)
cameraNode = scene_:CreateChild("Camera")
-- Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0, 0.0, -10.0)
local camera = cameraNode:CreateComponent("Camera")
camera.orthographic = true
camera.orthoSize = graphics.height * PIXEL_SIZE
local sprite = cache:GetResource("Sprite2D", "Urho2D/Aster.png")
if sprite == nil then
return
end
local spriteNodes = {}
local NUM_SPRITES = 200
local halfWidth = graphics.width * PIXEL_SIZE * 0.5
local halfHeight = graphics.height * PIXEL_SIZE * 0.5
for i = 1, NUM_SPRITES do
local spriteNode = scene_:CreateChild("StaticSprite2D")
spriteNode.position = Vector3(Random(-halfWidth, halfWidth), Random(-halfHeight, halfHeight), 0.0)
local staticSprite = spriteNode:CreateComponent("StaticSprite2D")
-- Set color
staticSprite.color = Color(Random(1.0), Random(1.0), Random(1.0), 1.0)
-- Set blend mode
staticSprite.blendMode = BLEND_ALPHA
-- Set sprite
staticSprite.sprite = sprite
-- Set move speed
spriteNode.moveSpeed = Vector3(Random(-2.0, 2.0), Random(-2.0, 2.0), 0.0)
-- Set rotate speed
spriteNode.rotateSpeed = Random(-90.0, 90.0)
table.insert(spriteNodes, spriteNode)
end
scene_.Update = function(self, timeStep)
for _, spriteNode in ipairs(spriteNodes) do
local position = spriteNode.position
local moveSpeed = spriteNode.moveSpeed
local newPosition = position + moveSpeed * timeStep
if newPosition.x < -halfWidth or newPosition.x > halfWidth then
newPosition.x = position.x
moveSpeed.x = -moveSpeed.x
end
if newPosition.y < -halfHeight or newPosition.y > halfHeight then
newPosition.y = position.y
moveSpeed.y = -moveSpeed.y
end
spriteNode.position = newPosition
spriteNode:Roll(spriteNode.rotateSpeed * timeStep)
end
end
local animation = cache:GetResource("Animation2D", "Urho2D/GoldIcon.anm")
if animation == nil then
return
end
local spriteNode = scene_:CreateChild("AnimatedSprite2D")
spriteNode.position = Vector3(0.0, 0.0, -1.0)
local animatedSprite = spriteNode:CreateComponent("AnimatedSprite2D")
-- Set animation
animatedSprite.animation = animation
-- Set blend mode
animatedSprite.blendMode = BLEND_ALPHA
end
function CreateInstructions()
-- Construct new Text object, set string to display and font to use
local instructionText = ui.root:CreateChild("Text")
instructionText:SetText("Use WASD keys and mouse to move, Use PageUp PageDown to zoom.")
instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15)
-- Position the text relative to the screen center
instructionText.horizontalAlignment = HA_CENTER
instructionText.verticalAlignment = VA_CENTER
instructionText:SetPosition(0, ui.root.height / 4)
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera
-- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to
-- use, but now we just use full screen and default render path configured in the engine command line options
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function MoveCamera(timeStep)
-- Do not move if the UI has a focused element (the console)
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 4.0
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 1.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, -1.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_PAGEUP) then
local camera = cameraNode:GetComponent("Camera")
camera.zoom = camera.zoom * 1.01
end
if input:GetKeyDown(KEY_PAGEDOWN) then
local camera = cameraNode:GetComponent("Camera")
camera.zoom = camera.zoom * 0.99
end
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for processing update events
SubscribeToEvent("Update", "HandleUpdate")
-- Unsubscribe the SceneUpdate event from base class to prevent camera pitch and yaw in 2D sample
UnsubscribeFromEvent("SceneUpdate")
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData:GetFloat("TimeStep")
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
-- Update scene
scene_:Update(timeStep)
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom In</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"PAGEUP\" />" ..
" </element>" ..
" </add>" ..
" <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" ..
" <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Zoom Out</replace>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" ..
" <element type=\"Text\">" ..
" <attribute name=\"Name\" value=\"KeyBinding\" />" ..
" <attribute name=\"Text\" value=\"PAGEDOWN\" />" ..
" </element>" ..
" </add>" ..
"</patch>"
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.