repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
Unrepentant-Atheist/mame | scripts/src/emu.lua | 2 | 10016 | -- license:BSD-3-Clause
-- copyright-holders:MAMEdev Team
---------------------------------------------------------------------------
--
-- emu.lua
--
-- Rules for building emu cores
--
---------------------------------------------------------------------------
project ("emu")
uuid ("e6fa15e4-a354-4526-acef-13c8e80fcacf")
kind (LIBTYPE)
addprojectflags()
precompiledheaders()
options {
"ArchiveSplit",
}
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/emu",
MAME_DIR .. "src/lib",
MAME_DIR .. "src/lib/util",
MAME_DIR .. "3rdparty",
GEN_DIR .. "emu",
GEN_DIR .. "emu/layout",
}
includedirs {
ext_includedir("expat"),
ext_includedir("lua"),
ext_includedir("zlib"),
ext_includedir("flac"),
}
files {
MAME_DIR .. "src/emu/emu.h",
MAME_DIR .. "src/emu/main.h",
MAME_DIR .. "src/emu/gamedrv.h",
MAME_DIR .. "src/emu/hashfile.cpp",
MAME_DIR .. "src/emu/hashfile.h",
MAME_DIR .. "src/emu/addrmap.cpp",
MAME_DIR .. "src/emu/addrmap.h",
MAME_DIR .. "src/emu/attotime.cpp",
MAME_DIR .. "src/emu/attotime.h",
MAME_DIR .. "src/emu/bookkeeping.cpp",
MAME_DIR .. "src/emu/bookkeeping.h",
MAME_DIR .. "src/emu/config.cpp",
MAME_DIR .. "src/emu/config.h",
MAME_DIR .. "src/emu/crsshair.cpp",
MAME_DIR .. "src/emu/crsshair.h",
MAME_DIR .. "src/emu/debugger.cpp",
MAME_DIR .. "src/emu/debugger.h",
MAME_DIR .. "src/emu/devdelegate.cpp",
MAME_DIR .. "src/emu/devdelegate.h",
MAME_DIR .. "src/emu/devcb.cpp",
MAME_DIR .. "src/emu/devcb.h",
MAME_DIR .. "src/emu/devcpu.cpp",
MAME_DIR .. "src/emu/devcpu.h",
MAME_DIR .. "src/emu/devfind.cpp",
MAME_DIR .. "src/emu/devfind.h",
MAME_DIR .. "src/emu/device.cpp",
MAME_DIR .. "src/emu/device.h",
MAME_DIR .. "src/emu/device.ipp",
MAME_DIR .. "src/emu/didisasm.cpp",
MAME_DIR .. "src/emu/didisasm.h",
MAME_DIR .. "src/emu/diexec.cpp",
MAME_DIR .. "src/emu/diexec.h",
MAME_DIR .. "src/emu/digfx.cpp",
MAME_DIR .. "src/emu/digfx.h",
MAME_DIR .. "src/emu/diimage.cpp",
MAME_DIR .. "src/emu/diimage.h",
MAME_DIR .. "src/emu/dimemory.cpp",
MAME_DIR .. "src/emu/dimemory.h",
MAME_DIR .. "src/emu/dinetwork.cpp",
MAME_DIR .. "src/emu/dinetwork.h",
MAME_DIR .. "src/emu/dinvram.cpp",
MAME_DIR .. "src/emu/dinvram.h",
MAME_DIR .. "src/emu/dioutput.cpp",
MAME_DIR .. "src/emu/dioutput.h",
MAME_DIR .. "src/emu/dipty.cpp",
MAME_DIR .. "src/emu/dipty.h",
MAME_DIR .. "src/emu/dirtc.cpp",
MAME_DIR .. "src/emu/dirtc.h",
MAME_DIR .. "src/emu/diserial.cpp",
MAME_DIR .. "src/emu/diserial.h",
MAME_DIR .. "src/emu/dislot.cpp",
MAME_DIR .. "src/emu/dislot.h",
MAME_DIR .. "src/emu/disound.cpp",
MAME_DIR .. "src/emu/disound.h",
MAME_DIR .. "src/emu/dispatch.cpp",
MAME_DIR .. "src/emu/dispatch.h",
MAME_DIR .. "src/emu/distate.cpp",
MAME_DIR .. "src/emu/distate.h",
MAME_DIR .. "src/emu/divideo.cpp",
MAME_DIR .. "src/emu/divideo.h",
MAME_DIR .. "src/emu/divtlb.cpp",
MAME_DIR .. "src/emu/divtlb.h",
MAME_DIR .. "src/emu/drawgfx.cpp",
MAME_DIR .. "src/emu/drawgfx.h",
MAME_DIR .. "src/emu/drawgfxm.h",
MAME_DIR .. "src/emu/driver.cpp",
MAME_DIR .. "src/emu/driver.h",
MAME_DIR .. "src/emu/drivenum.cpp",
MAME_DIR .. "src/emu/drivenum.h",
MAME_DIR .. "src/emu/emualloc.cpp",
MAME_DIR .. "src/emu/emualloc.h",
MAME_DIR .. "src/emu/emucore.cpp",
MAME_DIR .. "src/emu/emucore.h",
MAME_DIR .. "src/emu/emumem.cpp",
MAME_DIR .. "src/emu/emumem.h",
MAME_DIR .. "src/emu/emuopts.cpp",
MAME_DIR .. "src/emu/emuopts.h",
MAME_DIR .. "src/emu/emupal.cpp",
MAME_DIR .. "src/emu/emupal.h",
MAME_DIR .. "src/emu/fileio.cpp",
MAME_DIR .. "src/emu/fileio.h",
MAME_DIR .. "src/emu/hash.cpp",
MAME_DIR .. "src/emu/hash.h",
MAME_DIR .. "src/emu/image.cpp",
MAME_DIR .. "src/emu/image.h",
MAME_DIR .. "src/emu/input.cpp",
MAME_DIR .. "src/emu/input.h",
MAME_DIR .. "src/emu/ioport.cpp",
MAME_DIR .. "src/emu/ioport.h",
MAME_DIR .. "src/emu/inpttype.h",
MAME_DIR .. "src/emu/machine.cpp",
MAME_DIR .. "src/emu/machine.h",
MAME_DIR .. "src/emu/mconfig.cpp",
MAME_DIR .. "src/emu/mconfig.h",
MAME_DIR .. "src/emu/memarray.cpp",
MAME_DIR .. "src/emu/memarray.h",
MAME_DIR .. "src/emu/network.cpp",
MAME_DIR .. "src/emu/network.h",
MAME_DIR .. "src/emu/parameters.cpp",
MAME_DIR .. "src/emu/parameters.h",
MAME_DIR .. "src/emu/profiler.cpp",
MAME_DIR .. "src/emu/profiler.h",
MAME_DIR .. "src/emu/output.cpp",
MAME_DIR .. "src/emu/output.h",
MAME_DIR .. "src/emu/render.cpp",
MAME_DIR .. "src/emu/render.h",
MAME_DIR .. "src/emu/rendfont.cpp",
MAME_DIR .. "src/emu/rendfont.h",
MAME_DIR .. "src/emu/rendlay.cpp",
MAME_DIR .. "src/emu/rendlay.h",
MAME_DIR .. "src/emu/rendutil.cpp",
MAME_DIR .. "src/emu/rendutil.h",
MAME_DIR .. "src/emu/romload.cpp",
MAME_DIR .. "src/emu/romload.h",
MAME_DIR .. "src/emu/save.cpp",
MAME_DIR .. "src/emu/save.h",
MAME_DIR .. "src/emu/schedule.cpp",
MAME_DIR .. "src/emu/schedule.h",
MAME_DIR .. "src/emu/screen.cpp",
MAME_DIR .. "src/emu/screen.h",
MAME_DIR .. "src/emu/softlist.cpp",
MAME_DIR .. "src/emu/softlist.h",
MAME_DIR .. "src/emu/sound.cpp",
MAME_DIR .. "src/emu/sound.h",
MAME_DIR .. "src/emu/speaker.cpp",
MAME_DIR .. "src/emu/speaker.h",
MAME_DIR .. "src/emu/tilemap.cpp",
MAME_DIR .. "src/emu/tilemap.h",
MAME_DIR .. "src/emu/timer.cpp",
MAME_DIR .. "src/emu/timer.h",
MAME_DIR .. "src/emu/uiinput.cpp",
MAME_DIR .. "src/emu/uiinput.h",
MAME_DIR .. "src/emu/validity.cpp",
MAME_DIR .. "src/emu/validity.h",
MAME_DIR .. "src/emu/video.cpp",
MAME_DIR .. "src/emu/video.h",
MAME_DIR .. "src/emu/rendersw.hxx",
MAME_DIR .. "src/emu/ui/uimain.h",
MAME_DIR .. "src/emu/ui/cmdrender.h", -- TODO: remove
MAME_DIR .. "src/emu/ui/cmddata.h", -- TODO: remove
MAME_DIR .. "src/emu/debug/debugcmd.cpp",
MAME_DIR .. "src/emu/debug/debugcmd.h",
MAME_DIR .. "src/emu/debug/debugcon.cpp",
MAME_DIR .. "src/emu/debug/debugcon.h",
MAME_DIR .. "src/emu/debug/debugcpu.cpp",
MAME_DIR .. "src/emu/debug/debugcpu.h",
MAME_DIR .. "src/emu/debug/debughlp.cpp",
MAME_DIR .. "src/emu/debug/debughlp.h",
MAME_DIR .. "src/emu/debug/debugvw.cpp",
MAME_DIR .. "src/emu/debug/debugvw.h",
MAME_DIR .. "src/emu/debug/dvdisasm.cpp",
MAME_DIR .. "src/emu/debug/dvdisasm.h",
MAME_DIR .. "src/emu/debug/dvmemory.cpp",
MAME_DIR .. "src/emu/debug/dvmemory.h",
MAME_DIR .. "src/emu/debug/dvbpoints.cpp",
MAME_DIR .. "src/emu/debug/dvbpoints.h",
MAME_DIR .. "src/emu/debug/dvwpoints.cpp",
MAME_DIR .. "src/emu/debug/dvwpoints.h",
MAME_DIR .. "src/emu/debug/dvstate.cpp",
MAME_DIR .. "src/emu/debug/dvstate.h",
MAME_DIR .. "src/emu/debug/dvtext.cpp",
MAME_DIR .. "src/emu/debug/dvtext.h",
MAME_DIR .. "src/emu/debug/express.cpp",
MAME_DIR .. "src/emu/debug/express.h",
MAME_DIR .. "src/emu/debug/textbuf.cpp",
MAME_DIR .. "src/emu/debug/textbuf.h",
MAME_DIR .. "src/emu/drivers/empty.cpp",
MAME_DIR .. "src/emu/drivers/xtal.h",
MAME_DIR .. "src/emu/video/generic.cpp",
MAME_DIR .. "src/emu/video/generic.h",
MAME_DIR .. "src/emu/video/resnet.cpp",
MAME_DIR .. "src/emu/video/resnet.h",
MAME_DIR .. "src/emu/video/rgbutil.h",
MAME_DIR .. "src/emu/video/rgbgen.cpp",
MAME_DIR .. "src/emu/video/rgbgen.h",
MAME_DIR .. "src/emu/video/rgbsse.cpp",
MAME_DIR .. "src/emu/video/rgbsse.h",
MAME_DIR .. "src/emu/video/rgbvmx.cpp",
MAME_DIR .. "src/emu/video/rgbvmx.h",
}
dependency {
--------------------------------------------------
-- additional dependencies
--------------------------------------------------
{ MAME_DIR .. "src/emu/rendfont.cpp", GEN_DIR .. "emu/uismall.fh" },
{ MAME_DIR .. "src/emu/rendfont.cpp", GEN_DIR .. "emu/ui/uicmd14.fh" },
-------------------------------------------------
-- core layouts
--------------------------------------------------
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/dualhovu.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/dualhsxs.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/dualhuov.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/horizont.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/triphsxs.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/quadhsxs.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/vertical.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/lcd.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/lcd_rot.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/svg.lh" },
{ MAME_DIR .. "src/emu/rendlay.cpp", GEN_DIR .. "emu/layout/noscreens.lh" },
{ MAME_DIR .. "src/emu/video.cpp", GEN_DIR .. "emu/layout/snap.lh" },
}
custombuildtask {
{ MAME_DIR .. "scripts/font/NotoSans-Bold.bdc", GEN_DIR .. "emu/uismall.fh", { MAME_DIR .. "scripts/build/file2str.py" }, {"@echo Converting NotoSans-Bold.bdc...", PYTHON .. " $(1) $(<) $(@) font_uismall UINT8" }},
}
custombuildtask {
{ MAME_DIR .. "src/frontend/mame/ui/uicmd14.png" , GEN_DIR .. "emu/ui/uicmd14.fh", { MAME_DIR.. "scripts/build/png2bdc.py", MAME_DIR .. "scripts/build/file2str.py" }, {"@echo Converting uicmd14.png...", PYTHON .. " $(1) $(<) temp_cmd.bdc", PYTHON .. " $(2) temp_cmd.bdc $(@) font_uicmd14 UINT8" }},
layoutbuildtask("emu/layout", "dualhovu"),
layoutbuildtask("emu/layout", "dualhsxs"),
layoutbuildtask("emu/layout", "dualhuov"),
layoutbuildtask("emu/layout", "horizont"),
layoutbuildtask("emu/layout", "triphsxs"),
layoutbuildtask("emu/layout", "quadhsxs"),
layoutbuildtask("emu/layout", "vertical"),
layoutbuildtask("emu/layout", "lcd"),
layoutbuildtask("emu/layout", "lcd_rot"),
layoutbuildtask("emu/layout", "svg"),
layoutbuildtask("emu/layout", "noscreens"),
layoutbuildtask("emu/layout", "snap"),
}
project ("precompile")
uuid ("a6fb15d4-b123-4445-acef-13c8e80fcacf")
kind (LIBTYPE)
addprojectflags()
precompiledheaders()
includedirs {
MAME_DIR .. "src/osd",
MAME_DIR .. "src/emu",
MAME_DIR .. "src/lib/util",
}
files {
MAME_DIR .. "src/emu/drivers/empty.cpp",
}
dependency {
{ "$(OBJDIR)/src/emu/drivers/empty.o", "$(GCH)", true },
}
| gpl-2.0 |
EliHar/Pattern_recognition | torch1/extra/nn/Replicate.lua | 18 | 1682 | local Replicate, parent = torch.class('nn.Replicate','nn.Module')
function Replicate:__init(nf, dim, ndim)
parent.__init(self)
self.nfeatures = nf
self.dim = dim or 1
self.ndim = ndim
assert(self.dim > 0, "Can only replicate across positive integer dimensions.")
end
function Replicate:updateOutput(input)
self.dim = self.dim or 1 --backwards compatible
assert(
self.dim <= input:dim()+1,
"Not enough input dimensions to replicate along dimension " ..
tostring(self.dim) .. ".")
local batchOffset = self.ndim and input:dim() > self.ndim and 1 or 0
local rdim = self.dim + batchOffset
local sz = torch.LongStorage(input:dim()+1)
sz[rdim] = self.nfeatures
for i = 1,input:dim() do
local offset = 0
if i >= rdim then
offset = 1
end
sz[i+offset] = input:size(i)
end
local st = torch.LongStorage(input:dim()+1)
st[rdim] = 0
for i = 1,input:dim() do
local offset = 0
if i >= rdim then
offset = 1
end
st[i+offset] = input:stride(i)
end
self.output:set(input:storage(),input:storageOffset(),sz,st)
return self.output
end
function Replicate:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input):zero()
local batchOffset = self.ndim and input:dim() > self.ndim and 1 or 0
local rdim = self.dim + batchOffset
local sz = torch.LongStorage(input:dim()+1)
sz[rdim] = 1
for i = 1,input:dim() do
local offset = 0
if i >= rdim then
offset = 1
end
sz[i+offset] = input:size(i)
end
local gradInput = self.gradInput:view(sz)
gradInput:sum(gradOutput, rdim)
return self.gradInput
end
| mit |
EliHar/Pattern_recognition | torch1/install/share/lua/5.1/nn/Replicate.lua | 18 | 1682 | local Replicate, parent = torch.class('nn.Replicate','nn.Module')
function Replicate:__init(nf, dim, ndim)
parent.__init(self)
self.nfeatures = nf
self.dim = dim or 1
self.ndim = ndim
assert(self.dim > 0, "Can only replicate across positive integer dimensions.")
end
function Replicate:updateOutput(input)
self.dim = self.dim or 1 --backwards compatible
assert(
self.dim <= input:dim()+1,
"Not enough input dimensions to replicate along dimension " ..
tostring(self.dim) .. ".")
local batchOffset = self.ndim and input:dim() > self.ndim and 1 or 0
local rdim = self.dim + batchOffset
local sz = torch.LongStorage(input:dim()+1)
sz[rdim] = self.nfeatures
for i = 1,input:dim() do
local offset = 0
if i >= rdim then
offset = 1
end
sz[i+offset] = input:size(i)
end
local st = torch.LongStorage(input:dim()+1)
st[rdim] = 0
for i = 1,input:dim() do
local offset = 0
if i >= rdim then
offset = 1
end
st[i+offset] = input:stride(i)
end
self.output:set(input:storage(),input:storageOffset(),sz,st)
return self.output
end
function Replicate:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input):zero()
local batchOffset = self.ndim and input:dim() > self.ndim and 1 or 0
local rdim = self.dim + batchOffset
local sz = torch.LongStorage(input:dim()+1)
sz[rdim] = 1
for i = 1,input:dim() do
local offset = 0
if i >= rdim then
offset = 1
end
sz[i+offset] = input:size(i)
end
local gradInput = self.gradInput:view(sz)
gradInput:sum(gradOutput, rdim)
return self.gradInput
end
| mit |
paulu/deepfeatinterp | models/facemodel/datasets/transforms.lua | 1 | 7154 | --
-- Copyright (c) 2016, 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.
--
-- Image transforms for data augmentation and input normalization
--
require 'image'
local M = {}
function M.Compose(transforms)
return function(input)
for _, transform in ipairs(transforms) do
input = transform(input)
end
return input
end
end
function M.ColorNormalize(meanstd)
return function(img)
img = img:clone()
for i=1,3 do
img[i]:add(-meanstd.mean[i])
img[i]:div(meanstd.std[i])
end
return img
end
end
-- Scales the smaller edge to size
function M.Scale(size, interpolation)
interpolation = interpolation or 'bicubic'
return function(input)
local w, h = input:size(3), input:size(2)
if (w <= h and w == size) or (h <= w and h == size) then
return input
end
if w < h then
return image.scale(input, size, h/w * size, interpolation)
else
return image.scale(input, w/h * size, size, interpolation)
end
end
end
-- Crop to centered rectangle
function M.CenterCrop(size)
return function(input)
local w1 = math.ceil((input:size(3) - size)/2)
local h1 = math.ceil((input:size(2) - size)/2)
return image.crop(input, w1, h1, w1 + size, h1 + size) -- center patch
end
end
-- Random crop form larger image with optional zero padding
function M.RandomCrop(size, padding)
padding = padding or 0
return function(input)
if padding > 0 then
local temp = input.new(3, input:size(2) + 2*padding, input:size(3) + 2*padding)
temp:zero()
:narrow(2, padding+1, input:size(2))
:narrow(3, padding+1, input:size(3))
:copy(input)
input = temp
end
local w, h = input:size(3), input:size(2)
if w == size and h == size then
return input
end
local x1, y1 = torch.random(0, w - size), torch.random(0, h - size)
local out = image.crop(input, x1, y1, x1 + size, y1 + size)
assert(out:size(2) == size and out:size(3) == size, 'wrong crop size')
return out
end
end
-- Four corner patches and center crop from image and its horizontal reflection
function M.TenCrop(size)
local centerCrop = M.CenterCrop(size)
return function(input)
local w, h = input:size(3), input:size(2)
local output = {}
for _, img in ipairs{input, image.hflip(input)} do
table.insert(output, centerCrop(img))
table.insert(output, image.crop(img, 0, 0, size, size))
table.insert(output, image.crop(img, w-size, 0, w, size))
table.insert(output, image.crop(img, 0, h-size, size, h))
table.insert(output, image.crop(img, w-size, h-size, w, h))
end
-- View as mini-batch
for i, img in ipairs(output) do
output[i] = img:view(1, img:size(1), img:size(2), img:size(3))
end
return input.cat(output, 1)
end
end
-- Resized with shorter side randomly sampled from [minSize, maxSize] (ResNet-style)
function M.RandomScale(minSize, maxSize)
return function(input)
local w, h = input:size(3), input:size(2)
local targetSz = torch.random(minSize, maxSize)
local targetW, targetH = targetSz, targetSz
if w < h then
targetH = torch.round(h / w * targetW)
else
targetW = torch.round(w / h * targetH)
end
return image.scale(input, targetW, targetH, 'bicubic')
end
end
-- Random crop with size 8%-100% and aspect ratio 3/4 - 4/3 (Inception-style)
function M.RandomSizedCrop(size)
local scale = M.Scale(size)
local crop = M.CenterCrop(size)
return function(input)
local attempt = 0
repeat
local area = input:size(2) * input:size(3)
local targetArea = torch.uniform(0.08, 1.0) * area
local aspectRatio = torch.uniform(3/4, 4/3)
local w = torch.round(math.sqrt(targetArea * aspectRatio))
local h = torch.round(math.sqrt(targetArea / aspectRatio))
if torch.uniform() < 0.5 then
w, h = h, w
end
if h <= input:size(2) and w <= input:size(3) then
local y1 = torch.random(0, input:size(2) - h)
local x1 = torch.random(0, input:size(3) - w)
local out = image.crop(input, x1, y1, x1 + w, y1 + h)
assert(out:size(2) == h and out:size(3) == w, 'wrong crop size')
return image.scale(out, size, size, 'bicubic')
end
attempt = attempt + 1
until attempt >= 10
-- fallback
return crop(scale(input))
end
end
function M.HorizontalFlip(prob)
return function(input)
if torch.uniform() < prob then
input = image.hflip(input)
end
return input
end
end
function M.Rotation(deg)
return function(input)
if deg ~= 0 then
input = image.rotate(input, (torch.uniform() - 0.5) * deg * math.pi / 180, 'bilinear')
end
return input
end
end
-- Lighting noise (AlexNet-style PCA-based noise)
function M.Lighting(alphastd, eigval, eigvec)
return function(input)
if alphastd == 0 then
return input
end
local alpha = torch.Tensor(3):normal(0, alphastd)
local rgb = eigvec:clone()
:cmul(alpha:view(1, 3):expand(3, 3))
:cmul(eigval:view(1, 3):expand(3, 3))
:sum(2)
:squeeze()
input = input:clone()
for i=1,3 do
input[i]:add(rgb[i])
end
return input
end
end
local function blend(img1, img2, alpha)
return img1:mul(alpha):add(1 - alpha, img2)
end
local function grayscale(dst, img)
dst:resizeAs(img)
dst[1]:zero()
dst[1]:add(0.299, img[1]):add(0.587, img[2]):add(0.114, img[3])
dst[2]:copy(dst[1])
dst[3]:copy(dst[1])
return dst
end
function M.Saturation(var)
local gs
return function(input)
gs = gs or input.new()
grayscale(gs, input)
local alpha = 1.0 + torch.uniform(-var, var)
blend(input, gs, alpha)
return input
end
end
function M.Brightness(var)
local gs
return function(input)
gs = gs or input.new()
gs:resizeAs(input):zero()
local alpha = 1.0 + torch.uniform(-var, var)
blend(input, gs, alpha)
return input
end
end
function M.Contrast(var)
local gs
return function(input)
gs = gs or input.new()
grayscale(gs, input)
gs:fill(gs[1]:mean())
local alpha = 1.0 + torch.uniform(-var, var)
blend(input, gs, alpha)
return input
end
end
function M.RandomOrder(ts)
return function(input)
local img = input.img or input
local order = torch.randperm(#ts)
for i=1,#ts do
img = ts[order[i]](img)
end
return input
end
end
function M.ColorJitter(opt)
local brightness = opt.brightness or 0
local contrast = opt.contrast or 0
local saturation = opt.saturation or 0
local ts = {}
if brightness ~= 0 then
table.insert(ts, M.Brightness(brightness))
end
if contrast ~= 0 then
table.insert(ts, M.Contrast(contrast))
end
if saturation ~= 0 then
table.insert(ts, M.Saturation(saturation))
end
if #ts == 0 then
return function(input) return input end
end
return M.RandomOrder(ts)
end
return M
| gpl-3.0 |
dhakust/galvera | backup/config/rc.lua | 1 | 22850 | -- FILE: rc.lua
-- PATH: ~/.config/awesome
-- DATE: 2018-06-26
-- AUTH: David Hannon <dhakust@gmail.com>
-- TYPE: Configuration File - Awesome WM (Lua)
--[[ NOTES & TO-DO LIST:
--]]
-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
-- Notification library
local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup").widget
-- Lain
local lain = require("lain")
-- Freedesktop menu
local freedesktop = require("freedesktop")
-- Check if awesome encountered an error during startup and fell back
if awesome.startup_errors then
naughty.notify({
preset = naughty.config.presets.critical,
title = "Oops, there were errors during startup!",
text = awesome.startup_errors
})
end
-- Handle runtime errors after startup
do
local in_error = false
awesome.connect_signal("debug::error", function (err)
if in_error then return end
in_error = true
naughty.notify({
preset = naughty.config.presets.critical,
title = "Oops, an error happened!",
text = tostring(err)
})
in_error = false
end)
end
-- Variable definitions
beautiful.init(awful.util.getdir("config") .. "/themes/cesious/theme.lua")
terminal = "urxvtc"
browser = "chromium"
filemanager = "thunar"
editor = "vim"
modkey = "Mod4"
altkey = "Mod1"
configfile = ".config/awesome/rc.lua"
themesfile = ".config/awesome/themes/cesious/theme.lua"
-- Table of layouts to cover with awful.layout.inc, order matters.
awful.layout.layouts = {
awful.layout.suit.tile,
awful.layout.suit.magnifier,
awful.layout.suit.max,
-- awful.layout.suit.floating,
-- awful.layout.suit.fair,
-- awful.layout.suit.tile.bottom
-- awful.layout.suit.tile.left,
-- awful.layout.suit.tile.top,
-- awful.layout.suit.fair.horizontal,
-- awful.layout.suit.spiral,
-- awful.layout.suit.spiral.dwindle,
-- awful.layout.suit.max.fullscreen,
-- awful.layout.suit.corner.nw,
-- awful.layout.suit.corner.ne,
-- awful.layout.suit.corner.sw,
-- awful.layout.suit.corner.se,
}
-- Helper functions
local function client_menu_toggle_fn()
local instance = nil
return function()
if instance and instance.wibox.visible then
instance:hide()
instance = nil
else
instance = awful.menu.clients({theme = {width = 250}})
end
end
end
-- Menu
myawesomemenu = {
{"hotkeys", function() return false, hotkeys_popup.show_help end},
{"manual", terminal .. " -e man awesome"},
{"config", string.format("%s -e %s %s", terminal, editor, configfile)},
{"theme", string.format("%s -e %s %s", terminal, editor, themesfile)},
{"restart", awesome.restart}
}
myexitmenu = {
{"logout", function() awesome.quit() end},
{"suspend", "systemctl suspend"},
{"hibernate", "systemctl hibernate"},
{"reboot", "systemctl reboot" },
{"shutdown", "poweroff"}
}
mymainmenu = awful.menu({
items = {
{"urxvtc", "urxvtc"},
{"chromium", "chromium"},
{"ranger", "urxvtc -e ranger"},
{"htop", "urxvtc -e htop"},
{"vim", "urxvtc -e vim"},
{"awesome", myawesomemenu},
{"exit", myexitmenu}
}
})
myfullmenu = freedesktop.menu.build({
before = {
{"terminal", terminal},
{"browser", browser},
{"files", filemanager}
},
after = {
{"awesome", myawesomemenu},
{"exit", myexitmenu}
}
})
mylauncher = awful.widget.launcher({
image = beautiful.awesome_icon,
menu = mymainmenu
})
-- Menubar configuration
menubar.utils.terminal = terminal -- Set the terminal for applications that require it
-- Keyboard map indicator and switcher
mykeyboardlayout = awful.widget.keyboardlayout()
-- Create a textclock widget
mytextclock = awful.widget.textclock("%l:%M%P ")
markup = lain.util.markup
darkblue = theme.bg_focus
blue = "#9EBABA"
red = "#EB8F8F"
seperator = wibox.widget.textbox(' <span color="' .. blue .. '">| </span>')
spacer = wibox.widget.textbox(' <span color="' .. blue .. '"> </span>')
-- Create a wibox for each screen and add it
local taglist_buttons = gears.table.join(
awful.button({}, 1, function(t) t:view_only() end),
awful.button({modkey}, 1, function(t)
if client.focus then
client.focus:move_to_tag(t)
end
end),
awful.button({}, 3, awful.tag.viewtoggle),
awful.button({modkey}, 3, function(t)
if client.focus then
client.focus:toggle_tag(t)
end
end),
awful.button({}, 4, function(t) awful.tag.viewnext(t.screen) end),
awful.button({}, 5, function(t) awful.tag.viewprev(t.screen) end)
)
local tasklist_buttons = gears.table.join(
awful.button({}, 1, function(c)
if c == client.focus then
c.minimized = true
else
c.minimized = false
if not c:isvisible() and c.first_tag then
c.first_tag:view_only()
end
client.focus = c
c:raise()
end
end),
awful.button({}, 3, client_menu_toggle_fn()),
awful.button({}, 4, function()
awful.client.focus.byidx(1)
end),
awful.button({}, 5, function()
awful.client.focus.byidx(-1)
end)
)
-- Wallpaper
local function set_wallpaper(s)
if beautiful.wallpaper then
local wallpaper = beautiful.wallpaper
if type(wallpaper) == "function" then
wallpaper = wallpaper(s)
end
gears.wallpaper.maximized(wallpaper, s, true)
end
end
-- Reset wallpaper when a screen's geometry changes (e.g. different resolution)
screen.connect_signal("property::geometry", set_wallpaper)
awful.screen.connect_for_each_screen(function(s)
set_wallpaper(s)
-- Each screen has its own tag table.
awful.tag({"D", "H", "A", "K", "U", "S", "T"}, s, awful.layout.layouts[1])
-- Create a promptbox for each screen
s.mypromptbox = awful.widget.prompt()
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
s.mylayoutbox = awful.widget.layoutbox(s)
s.mylayoutbox:buttons(gears.table.join(
awful.button({}, 1, function() awful.layout.inc( 1) end),
awful.button({}, 3, function() awful.layout.inc(-1) end),
awful.button({}, 4, function() awful.layout.inc( 1) end),
awful.button({}, 5, function() awful.layout.inc(-1) end)
))
-- Create a taglist widget
s.mytaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, taglist_buttons)
-- Create a tasklist widget
s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist_buttons)
-- Create the wibox
s.mywibox = awful.wibar({position = "bottom", screen = s})
-- Add widgets to the wibox
s.mywibox:setup {
layout = wibox.layout.align.horizontal,
-- Left widgets
{
layout = wibox.layout.fixed.horizontal,
mylauncher,
seperator,
s.mytaglist,
seperator,
s.mypromptbox,
},
-- Middle widget
s.mytasklist,
-- Right widgets
{
layout = wibox.layout.fixed.horizontal,
-- mykeyboardlayout,
seperator,
wibox.widget.systray(),
seperator,
mytextclock,
seperator,
s.mylayoutbox,
},
}
end)
-- Mouse bindings
root.buttons(gears.table.join(
awful.button({}, 1, function() mymainmenu:hide() end),
awful.button({}, 3, function() mymainmenu:toggle() end),
awful.button({}, 4, awful.tag.viewnext),
awful.button({}, 5, awful.tag.viewprev),
awful.button({altkey}, 1, function() myfullmenu:hide() end),
awful.button({altkey}, 3, function() myfullmenu:toggle() end)
))
-- Key bindings
globalkeys = gears.table.join(
-- (Super + s) = Show Help window
awful.key({modkey}, "s", hotkeys_popup.show_help,
{description = "show help", group="awesome"}),
-- (Super + Left) = Go to the previous tag
awful.key({modkey}, "Left", awful.tag.viewprev,
{description = "view previous", group = "tag"}),
-- (Super + Right) = Go to the next tag
awful.key({modkey}, "Right", awful.tag.viewnext,
{description = "view next", group = "tag"}),
-- (Super + Esc) = Go back to last tag
awful.key({modkey}, "Escape", awful.tag.history.restore,
{description = "go back", group = "tag"}),
-- (Super + j) = Go to the next window
awful.key({modkey}, "j",
function()
awful.client.focus.byidx(1)
end,
{description = "focus next by index", group = "client"}
),
-- (Super + k) = Go to the previous window
awful.key({modkey}, "k",
function()
awful.client.focus.byidx(-1)
end,
{description = "focus previous by index", group = "client"}
),
-- (Super + w) = Open the main menu
awful.key({modkey}, "w", function() mymainmenu:show() end,
{description = "show main menu", group = "awesome"}),
-- Layout manipulation
awful.key({modkey, "Shift"}, "j", function() awful.client.swap.byidx(1) end,
{description = "swap with next client by index", group = "client"}),
awful.key({modkey, "Shift"}, "k", function() awful.client.swap.byidx(-1) end,
{description = "swap with previous client by index", group = "client"}),
awful.key({modkey, "Control"}, "j", function() awful.screen.focus_relative(1) end,
{description = "focus the next screen", group = "screen"}),
awful.key({modkey, "Control"}, "k", function() awful.screen.focus_relative(-1) end,
{description = "focus the previous screen", group = "screen"}),
awful.key({modkey}, "u", awful.client.urgent.jumpto,
{description = "jump to urgent client", group = "client"}),
awful.key({modkey}, "Tab",
function()
awful.client.focus.history.previous()
if client.focus then
client.focus:raise()
end
end,
{description = "go back", group = "client"}),
-- Standard program
awful.key({modkey}, "Return", function() awful.spawn(terminal) end,
{description = "open a terminal", group = "launcher"}),
awful.key({modkey}, "z", function() awful.spawn(terminal) end,
{description = "open a terminal", group = "launcher"}),
awful.key({modkey, "Control"}, "r", awesome.restart,
{description = "reload awesome", group = "awesome"}),
awful.key({modkey, "Shift"}, "q", awesome.quit,
{description = "quit awesome", group = "awesome"}),
awful.key({modkey}, "l", function() awful.tag.incmwfact(0.05) end,
{description = "increase master width factor", group = "layout"}),
awful.key({modkey}, "h", function() awful.tag.incmwfact(-0.05) end,
{description = "decrease master width factor", group = "layout"}),
awful.key({modkey, "Shift"}, "h", function() awful.tag.incnmaster(1, nil, true) end,
{description = "increase the number of master clients", group = "layout"}),
awful.key({modkey, "Shift"}, "l", function() awful.tag.incnmaster(-1, nil, true) end,
{description = "decrease the number of master clients", group = "layout"}),
awful.key({modkey, "Control"}, "h", function() awful.tag.incncol(1, nil, true) end,
{description = "increase the number of columns", group = "layout"}),
awful.key({modkey, "Control"}, "l", function() awful.tag.incncol(-1, nil, true) end,
{description = "decrease the number of columns", group = "layout"}),
awful.key({modkey}, "space", function() awful.util.spawn("/usr/bin/dmenu_recency") end,
{description = "launch dmenu", group = "launcher"}),
awful.key({modkey}, "b", function() awful.util.spawn("/usr/bin/chromium") end,
{description = "launch Browser", group = "launcher"}),
awful.key({modkey, "Shift"}, "p", function() awful.util.spawn("/usr/bin/rofi -show") end,
{description = "launch rofi", group = "launcher"}),
awful.key({modkey}, "e", function() awful.util.spawn("/usr/bin/thunar") end,
{description = "launch filemanager", group = "launcher"}),
awful.key({modkey, "Shift"}, "space", function() awful.layout.inc(-1) end,
{description = "select previous", group = "layout"}),
awful.key({modkey, "Control"}, "n",
function()
local c = awful.client.restore()
if c then
client.focus = c
c:raise()
end
end,
{description = "restore minimized", group = "client"}),
-- Prompt
awful.key({modkey}, "r", function() awful.screen.focused().mypromptbox:run() end,
{description = "run prompt", group = "launcher"}),
awful.key({modkey, "Shift"}, "o",
function()
awful.prompt.run {
prompt = "Run Lua code: ",
textbox = awful.screen.focused().mypromptbox.widget,
exe_callback = awful.util.eval,
history_path = awful.util.get_cache_dir() .. "/history_eval"
}
end,
{description = "lua execute prompt", group = "awesome"}),
-- Menubar
awful.key({modkey}, "p", function() menubar.show() end,
{description = "show the menubar", group = "launcher"})
)
clientkeys = gears.table.join(
awful.key({modkey}, "f",
function (c)
c.fullscreen = not c.fullscreen
c:raise()
end,
{description = "toggle fullscreen", group = "client"}),
awful.key({modkey}, "x", function(c) c:kill() end,
{description = "close", group = "client"}),
awful.key({modkey, "Control"}, "space", awful.client.floating.toggle,
{description = "toggle floating", group = "client"}),
awful.key({modkey, "Control"}, "Return", function(c) c:swap(awful.client.getmaster()) end,
{description = "move to master", group = "client"}),
awful.key({modkey}, "o", function(c) c:move_to_screen() end,
{description = "move to screen", group = "client"}),
awful.key({modkey}, "t", function(c) c.ontop = not c.ontop end,
{description = "toggle keep on top", group = "client"}),
awful.key({modkey}, "n",
function(c)
c.minimized = true
end,
{description = "minimize", group = "client"}),
awful.key({modkey}, "m",
function(c)
c.maximized = not c.maximized
c:raise()
end,
{description = "maximize", group = "client"}),
awful.key({modkey, "Control"}, "m",
function(c)
c.maximized_vertical = not c.maximized_vertical
c:raise()
end,
{description = "maximize vertically", group = "client"}),
awful.key({modkey, "Shift"}, "m",
function(c)
c.maximized_horizontal = not c.maximized_horizontal
c:raise()
end,
{description = "maximize horizontally", group = "client"})
)
-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it work on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, 9 do
globalkeys = gears.table.join(globalkeys,
-- View tag only.
awful.key({ modkey }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
tag:view_only()
end
end,
{description = "view tag #"..i, group = "tag"}),
-- Toggle tag display.
awful.key({ modkey, "Control" }, "#" .. i + 9,
function ()
local screen = awful.screen.focused()
local tag = screen.tags[i]
if tag then
awful.tag.viewtoggle(tag)
end
end,
{description = "toggle tag #" .. i, group = "tag"}),
-- Move client to tag.
awful.key({ modkey, "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:move_to_tag(tag)
end
end
end,
{description = "move focused client to tag #"..i, group = "tag"}),
-- Toggle tag on focused client.
awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
function ()
if client.focus then
local tag = client.focus.screen.tags[i]
if tag then
client.focus:toggle_tag(tag)
end
end
end,
{description = "toggle focused client on tag #" .. i, group = "tag"})
)
end
clientbuttons = gears.table.join(
awful.button({ }, 1, function (c) client.focus = c; c:raise()
mymainmenu:hide() end),
awful.button({ modkey }, 1, awful.mouse.client.move),
awful.button({ modkey }, 3, awful.mouse.client.resize))
-- Set keys
root.keys(globalkeys)
-- Rules
-- Rules to apply to new clients (through the "manage" signal).
awful.rules.rules = {
-- All clients will match this rule.
{ rule = { },
properties = { border_width = beautiful.border_width,
border_color = beautiful.border_normal,
focus = awful.client.focus.filter,
raise = true,
keys = clientkeys,
buttons = clientbuttons,
size_hints_honor = false, -- Remove gaps between terminals
screen = awful.screen.preferred,
callback = awful.client.setslave,
placement = awful.placement.no_overlap+awful.placement.no_offscreen
}
},
-- Floating clients.
{ rule_any = {
instance = {
"DTA", -- Firefox addon DownThemAll.
"copyq", -- Includes session name in class.
},
class = {
"Arandr",
"Gpick",
"Kruler",
"MessageWin", -- kalarm.
"Sxiv",
"Wpa_gui",
"pinentry",
"veromix",
"xtightvncviewer"},
name = {
"Event Tester", -- xev.
},
role = {
"AlarmWindow", -- Thunderbird's calendar.
"pop-up", -- e.g. Google Chrome's (detached) Developer Tools.
}
}, properties = { floating = true }},
-- Add titlebars to normal clients and dialogs
{ rule_any = {type = { "normal", "dialog" } },
except_any = { role = { "browser" }, class = { "Gedit", "gedit", "Nautilus", "Pamac-manager", "Pamac-updater" } },
properties = { titlebars_enabled = true }
},
-- Set Firefox to always map on the tag named "2" on screen 1.
-- { rule = { class = "Firefox" },
-- properties = { screen = 1, tag = "2" } },
}
-- Signal function to execute when a new client appears.
client.connect_signal("manage", function (c)
if awesome.startup and
not c.size_hints.user_position
and not c.size_hints.program_position then
-- Prevent clients from being unreachable after screen count changes.
awful.placement.no_offscreen(c)
end
end)
-- Add a titlebar if titlebars_enabled is set to true in the rules.
client.connect_signal("request::titlebars", function(c)
-- buttons for the titlebar
local buttons = gears.table.join(
awful.button({}, 1, function()
client.focus = c
c:raise()
awful.mouse.client.move(c)
end),
awful.button({}, 3, function()
client.focus = c
c:raise()
awful.mouse.client.resize(c)
end)
)
awful.titlebar(c) : setup {
{ -- Left
awful.titlebar.widget.iconwidget(c),
buttons = buttons,
layout = wibox.layout.fixed.horizontal
},
{ -- Middle
{ -- Title
align = "center",
widget = awful.titlebar.widget.titlewidget(c)
},
buttons = buttons,
layout = wibox.layout.flex.horizontal
},
{ -- Right
awful.titlebar.widget.stickybutton(c),
awful.titlebar.widget.maximizedbutton(c),
awful.titlebar.widget.floatingbutton(c),
awful.titlebar.widget.ontopbutton(c),
awful.titlebar.widget.closebutton(c),
layout = wibox.layout.fixed.horizontal()
},
layout = wibox.layout.align.horizontal
}
end)
-- Enable sloppy focus, so that focus follows mouse.
client.connect_signal("mouse::enter", function(c)
if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
and awful.client.focus.filter(c) then
client.focus = c
end
end)
client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- Disable borders on lone windows and handle border sizes of clients.
for s = 1, screen.count() do screen[s]:connect_signal("arrange", function ()
local clients = awful.client.visible(s)
local layout = awful.layout.getname(awful.layout.get(s))
for _, c in pairs(clients) do
awful.titlebar.hide(c)
if c.maximized then
c.border_width = 0
elseif awful.client.floating.get(c) or layout == "floating" then
c.border_width = beautiful.border_width
elseif layout == "max" or layout == "fullscreen" then
c.border_width = 0
else
local tiled = awful.client.tiled(c.screen)
if #tiled == 1 then
tiled[1].border_width = 0
else
c.border_width = beautiful.border_width
end
end
end
end)
end
awful.util.spawn_with_shell("~/.config/awesome/autorun.sh")
| gpl-3.0 |
EliHar/Pattern_recognition | torch1/install/share/lua/5.1/fftw3/defines.lua | 4 | 1484 | local ffi=require 'ffi'
local defines = {}
function defines.register_hashdefs(fftw, C)
fftw.MEASURE = 0
fftw.DESTROY_INPUT = 1
fftw.UNALIGNED = 2
fftw.CONSERVE_MEMORY = 4
fftw.EXHAUSTIVE = 8 -- /* NO_EXHAUSTIVE is default */
fftw.PRESERVE_INPUT = 16 -- /* cancels DESTROY_INPUT */
fftw.PATIENT =32 -- /* IMPATIENT is default */
fftw.ESTIMATE = 64
fftw.WISDOM_ONLY = 2097152 -- (1U << 21)
fftw.FORWARD = -1
fftw.BACKWARD = 1
fftw.NO_TIMELIMIT = (-1.0)
-- -- typedef
fftw.r2r_kind = ffi.typeof('fftw_r2r_kind')
fftw.R2HC=0
fftw.HC2R=1
fftw.DHT=2
fftw.REDFT00=3
fftw.REDFT01=4
fftw.REDFT10=5
fftw.REDFT11=6
fftw.RODFT00=7
fftw.RODFT01=8
fftw.RODFT10=9
fftw.RODFT11=10
end
function defines.register_hashdefsf(fftw, C)
fftw.MEASURE = 0
fftw.DESTROY_INPUT = 1
fftw.UNALIGNED = 2
fftw.CONSERVE_MEMORY = 4
fftw.EXHAUSTIVE = 8 -- /* NO_EXHAUSTIVE is default */
fftw.PRESERVE_INPUT = 16 -- /* cancels DESTROY_INPUT */
fftw.PATIENT =32 -- /* IMPATIENT is default */
fftw.ESTIMATE = 64
fftw.WISDOM_ONLY = 2097152 -- (1U << 21)
fftw.FORWARD = -1
fftw.BACKWARD = 1
fftw.NO_TIMELIMIT = (-1.0)
-- -- typedef
fftw.r2r_kind = ffi.typeof('fftwf_r2r_kind')
fftw.R2HC=0
fftw.HC2R=1
fftw.DHT=2
fftw.REDFT00=3
fftw.REDFT01=4
fftw.REDFT10=5
fftw.REDFT11=6
fftw.RODFT00=7
fftw.RODFT01=8
fftw.RODFT10=9
fftw.RODFT11=10
end
return defines
| mit |
notcake/glib | lua/glib/resources/resourcecache.lua | 1 | 4847 | local self = {}
GLib.Resources.ResourceCache = GLib.MakeConstructor (self)
function self:ctor ()
self.LastAccessTimes = {}
self.NeedsSaving = false
self:LoadLastAccessTimes ()
timer.Create ("GLib.Resources.ResourceCache.PruneCache", 300, 1,
function ()
self:PruneCache ()
end
)
concommand.Add ("glib_flush_resource_cache_" .. (SERVER and "sv" or "cl"),
function (ply, _, args)
if SERVER then
if ply and ply:IsValid () and not ply:IsAdmin () then return end
end
self:ClearCache ()
end
)
concommand.Add ("glib_prune_resource_cache_" .. (SERVER and "sv" or "cl"),
function (ply, _, args)
if SERVER then
if ply and ply:IsValid () and not ply:IsAdmin () then return end
end
self:PruneCache ()
end
)
end
function self:dtor ()
timer.Destroy ("GLib.Resources.ResourceCache.PruneCache")
timer.Destroy ("GLib.Resources.ResourceCache.SaveLastAccessTimes")
end
function self:CacheResource (namespace, id, versionHash, data)
file.CreateDir ("glib")
file.CreateDir ("glib/resourcecache")
file.CreateDir ("glib/resourcecache/" .. string.lower (namespace))
local f = file.Open (self:GetCachePath (namespace, id, versionHash), "wb", "DATA")
if not f then return end
f:Write (data)
f:Close ()
self:UpdateLastAccessTime (namespace, id, versionHash)
end
function self:ClearCache ()
local _, folders = file.Find ("data/glib/resourcecache/*", "GAME")
for _, folderName in ipairs (folders) do
local files = file.Find ("data/glib/resourcecache/" .. folderName .. "/*", "GAME")
for _, fileName in ipairs (files) do
self.LastAccessTimes ["glib/resourcecache/" .. folderName .. "/" .. fileName] = nil
self:FlagSaveNeeded ()
file.Delete ("glib/resourcecache/" .. folderName .. "/" .. fileName)
print ("GLib.Resources : Flushing cached resource glib/resourcecache/" .. folderName .. "/" .. fileName .. "...")
end
end
end
function self:GetCachePath (namespace, id, versionHash)
return "glib/resourcecache/" .. string.lower (namespace) .. "/" .. string.lower (id) .. "_" .. versionHash .. ".txt"
end
function self:IsResourceCached (namespace, id, versionHash)
return file.Exists ("data/" .. self:GetCachePath (namespace, id, versionHash), "GAME") and
string.format ("%08x", tonumber (util.CRC (file.Read ("data/" .. self:GetCachePath (namespace, id, versionHash), "GAME"))) or 0) == versionHash
end
function self:PruneCache ()
local _, folders = file.Find ("data/glib/resourcecache/*", "GAME")
for _, folderName in ipairs (folders) do
local files = file.Find ("data/glib/resourcecache/" .. folderName .. "/*", "GAME")
for _, fileName in ipairs (files) do
local lastAccessTime = self.LastAccessTimes ["glib/resourcecache/" .. folderName .. "/" .. fileName] or 0
if os.time () - lastAccessTime > 7 * 86400 then
-- Older than 1 week, delete it
self.LastAccessTimes ["glib/resourcecache/" .. folderName .. "/" .. fileName] = nil
self:FlagSaveNeeded ()
file.Delete ("glib/resourcecache/" .. folderName .. "/" .. fileName)
print ("GLib.Resources : Cached resource glib/resourcecache/" .. folderName .. "/" .. fileName .. " has expired, deleting...")
end
end
end
-- Remove nonexistant files from the last access times table
for dataPath, _ in pairs (self.LastAccessTimes) do
if not file.Exists ("data/" .. dataPath, "GAME") then
self.LastAccessTimes [dataPath] = nil
self:FlagSaveNeeded ()
end
end
end
function self:UpdateLastAccessTime (namespace, id, versionHash)
self.LastAccessTimes [self:GetCachePath (namespace, id, versionHash)] = os.time ()
self:FlagSaveNeeded ()
end
-- Internal, do not call
function self:FlagSaveNeeded ()
self.NeedsSaving = true
timer.Create ("GLib.Resources.ResourceCache.SaveLastAccessTimes", 1, 1,
function ()
self:SaveLastAccessTimes ()
end
)
end
function self:LoadLastAccessTimes ()
local inBuffer = GLib.StringInBuffer (file.Read ("data/glib/resourcecache/lastaccesstimes.txt", "GAME") or "")
local path = inBuffer:String ()
while path ~= "" do
self.LastAccessTimes [path] = inBuffer:UInt32 ()
inBuffer:Bytes (1) -- Discard newline
path = inBuffer:String ()
end
self.NeedsSaving = false
end
function self:SaveLastAccessTimes ()
local outBuffer = GLib.StringOutBuffer ()
for path, timestamp in pairs (self.LastAccessTimes) do
outBuffer:String (path)
outBuffer:UInt32 (timestamp)
outBuffer:Bytes ("\n")
end
outBuffer:String ("")
file.CreateDir ("glib")
file.CreateDir ("glib/resourcecache")
file.Write ("glib/resourcecache/lastaccesstimes.txt", outBuffer:GetString ())
self.NeedsSaving = false
end
GLib.Resources.ResourceCache = GLib.Resources.ResourceCache () | gpl-3.0 |
rlcevg/Zero-K | effects/paris.lua | 12 | 4272 | -- paris_glow
-- paris
-- paris_gflash
-- paris_sphere
return {
["paris_glow"] = {
glow = {
air = true,
class = [[CSimpleParticleSystem]],
count = 2,
ground = true,
water = true,
properties = {
airdrag = 1,
colormap = [[0 0 0 0.01 0.8 0.8 0.8 0.9 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 180,
emitvector = [[-0, 1, 0]],
gravity = [[0, 0.00, 0]],
numparticles = 1,
particlelife = 10,
particlelifespread = 0,
particlesize = 60,
particlesizespread = 10,
particlespeed = 1,
particlespeedspread = 0,
pos = [[0, 2, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[circularthingy]],
},
},
groundflash = {
circlealpha = 1,
circlegrowth = 0,
flashalpha = 0.5,
flashsize = 100,
ttl = 10,
color = {
[1] = 0.80000001192093,
[2] = 0.80000001192093,
[3] = 1,
},
},
},
["paris"] = {
dustring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 0,
explosiongenerator = [[custom:GEORGE]],
pos = [[0, 0, 0]],
},
},
gflash = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 0,
explosiongenerator = [[custom:PARIS_GFLASH]],
pos = [[0, 0, 0]],
},
},
glow = {
air = true,
class = [[CExpGenSpawner]],
count = 0,
ground = true,
water = true,
properties = {
delay = [[0 i0.5]],
explosiongenerator = [[custom:PARIS_GLOW]],
pos = [[0, 0, 0]],
},
},
shere = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 0,
explosiongenerator = [[custom:PARIS_SPHERE]],
pos = [[0, 5, 0]],
},
},
},
["paris_gflash"] = {
groundflash = {
circlealpha = 0.5,
circlegrowth = 60,
flashalpha = 0,
flashsize = 30,
ttl = 20,
color = {
[1] = 0.80000001192093,
[2] = 0.80000001192093,
[3] = 1,
},
},
},
["paris_sphere"] = {
groundflash = {
circlealpha = 1,
circlegrowth = 0,
flashalpha = 0.5,
flashsize = 60,
ttl = 60,
color = {
[1] = 0.80000001192093,
[2] = 0.80000001192093,
[3] = 1,
},
},
pikez = {
air = true,
class = [[explspike]],
count = 15,
ground = true,
water = true,
properties = {
alpha = 0.8,
alphadecay = 0.15,
color = [[1.0,1.0,0.8]],
dir = [[-15 r30,-15 r30,-15 r30]],
length = 40,
width = 15,
},
},
sphere = {
air = true,
class = [[CSpherePartSpawner]],
count = 1,
ground = true,
water = true,
properties = {
alpha = 0.3,
alwaysvisible = false,
color = [[0.8,0.8,1]],
expansionspeed = 60,
ttl = 10,
},
},
},
}
| gpl-2.0 |
lynx-seu/skynet | lualib/redis.lua | 47 | 4975 | local skynet = require "skynet"
local socket = require "socket"
local socketchannel = require "socketchannel"
local table = table
local string = string
local redis = {}
local command = {}
local meta = {
__index = command,
-- DO NOT close channel in __gc
}
---------- redis response
local redcmd = {}
redcmd[36] = function(fd, data) -- '$'
local bytes = tonumber(data)
if bytes < 0 then
return true,nil
end
local firstline = fd:read(bytes+2)
return true,string.sub(firstline,1,-3)
end
redcmd[43] = function(fd, data) -- '+'
return true,data
end
redcmd[45] = function(fd, data) -- '-'
return false,data
end
redcmd[58] = function(fd, data) -- ':'
-- todo: return string later
return true, tonumber(data)
end
local function read_response(fd)
local result = fd:readline "\r\n"
local firstchar = string.byte(result)
local data = string.sub(result,2)
return redcmd[firstchar](fd,data)
end
redcmd[42] = function(fd, data) -- '*'
local n = tonumber(data)
if n < 0 then
return true, nil
end
local bulk = {}
local noerr = true
for i = 1,n do
local ok, v = read_response(fd)
if ok then
bulk[i] = v
else
noerr = false
end
end
return noerr, bulk
end
-------------------
local function redis_login(auth, db)
if auth == nil and db == nil then
return
end
return function(so)
if auth then
so:request("AUTH "..auth.."\r\n", read_response)
end
if db then
so:request("SELECT "..db.."\r\n", read_response)
end
end
end
function redis.connect(db_conf)
local channel = socketchannel.channel {
host = db_conf.host,
port = db_conf.port or 6379,
auth = redis_login(db_conf.auth, db_conf.db),
nodelay = true,
}
-- try connect first only once
channel:connect(true)
return setmetatable( { channel }, meta )
end
function command:disconnect()
self[1]:close()
setmetatable(self, nil)
end
-- msg could be any type of value
local function pack_value(lines, v)
if v == nil then
return
end
v = tostring(v)
table.insert(lines,"$"..#v)
table.insert(lines,v)
end
local function compose_message(cmd, msg)
local len = 1
local t = type(msg)
if t == "table" then
len = len + #msg
elseif t ~= nil then
len = len + 1
end
local lines = {"*" .. len}
pack_value(lines, cmd)
if t == "table" then
for _,v in ipairs(msg) do
pack_value(lines, v)
end
else
pack_value(lines, msg)
end
table.insert(lines, "")
local chunk = table.concat(lines,"\r\n")
return chunk
end
setmetatable(command, { __index = function(t,k)
local cmd = string.upper(k)
local f = function (self, v, ...)
if type(v) == "table" then
return self[1]:request(compose_message(cmd, v), read_response)
else
return self[1]:request(compose_message(cmd, {v, ...}), read_response)
end
end
t[k] = f
return f
end})
local function read_boolean(so)
local ok, result = read_response(so)
return ok, result ~= 0
end
function command:exists(key)
local fd = self[1]
return fd:request(compose_message ("EXISTS", key), read_boolean)
end
function command:sismember(key, value)
local fd = self[1]
return fd:request(compose_message ("SISMEMBER", {key, value}), read_boolean)
end
--- watch mode
local watch = {}
local watchmeta = {
__index = watch,
__gc = function(self)
self.__sock:close()
end,
}
local function watch_login(obj, auth)
return function(so)
if auth then
so:request("AUTH "..auth.."\r\n", read_response)
end
for k in pairs(obj.__psubscribe) do
so:request(compose_message ("PSUBSCRIBE", k))
end
for k in pairs(obj.__subscribe) do
so:request(compose_message("SUBSCRIBE", k))
end
end
end
function redis.watch(db_conf)
local obj = {
__subscribe = {},
__psubscribe = {},
}
local channel = socketchannel.channel {
host = db_conf.host,
port = db_conf.port or 6379,
auth = watch_login(obj, db_conf.auth),
nodelay = true,
}
obj.__sock = channel
-- try connect first only once
channel:connect(true)
return setmetatable( obj, watchmeta )
end
function watch:disconnect()
self.__sock:close()
setmetatable(self, nil)
end
local function watch_func( name )
local NAME = string.upper(name)
watch[name] = function(self, ...)
local so = self.__sock
for i = 1, select("#", ...) do
local v = select(i, ...)
so:request(compose_message(NAME, v))
end
end
end
watch_func "subscribe"
watch_func "psubscribe"
watch_func "unsubscribe"
watch_func "punsubscribe"
function watch:message()
local so = self.__sock
while true do
local ret = so:response(read_response)
local type , channel, data , data2 = ret[1], ret[2], ret[3], ret[4]
if type == "message" then
return data, channel
elseif type == "pmessage" then
return data2, data, channel
elseif type == "subscribe" then
self.__subscribe[channel] = true
elseif type == "psubscribe" then
self.__psubscribe[channel] = true
elseif type == "unsubscribe" then
self.__subscribe[channel] = nil
elseif type == "punsubscribe" then
self.__psubscribe[channel] = nil
end
end
end
return redis
| mit |
ViolyS/RayUI_VS | Interface/AddOns/RayUI/libs/oUF/elements/raidroleindicator.lua | 3 | 2598 | --[[
# Element: Raid Role Indicator
Handles the visibility and updating of an indicator based on the unit's raid assignment (main tank or main assist).
## Widget
RaidRoleIndicator - A `Texture` representing the unit's raid assignment.
## Notes
This element updates by changing the texture.
## Examples
-- Position and size
local RaidRoleIndicator = self:CreateTexture(nil, 'OVERLAY')
RaidRoleIndicator:SetSize(16, 16)
RaidRoleIndicator:SetPoint('TOPLEFT')
-- Register it with oUF
self.RaidRoleIndicator = RaidRoleIndicator
--]]
local _, ns = ...
local oUF = ns.oUF
local MAINTANK_ICON = [[Interface\GROUPFRAME\UI-GROUP-MAINTANKICON]]
local MAINASSIST_ICON = [[Interface\GROUPFRAME\UI-GROUP-MAINASSISTICON]]
local function Update(self, event)
local unit = self.unit
local element = self.RaidRoleIndicator
--[[ Callback: RaidRoleIndicator:PreUpdate()
Called before the element has been updated.
* self - the RaidRoleIndicator element
--]]
if(element.PreUpdate) then
element:PreUpdate()
end
local role, isShown
if(UnitInRaid(unit) and not UnitHasVehicleUI(unit)) then
if(GetPartyAssignment('MAINTANK', unit)) then
isShown = true
element:SetTexture(MAINTANK_ICON)
role = 'MAINTANK'
elseif(GetPartyAssignment('MAINASSIST', unit)) then
isShown = true
element:SetTexture(MAINASSIST_ICON)
role = 'MAINASSIST'
end
end
element:SetShown(isShown)
--[[ Callback: RaidRoleIndicator:PostUpdate(role)
Called after the element has been updated.
* self - the RaidRoleIndicator element
* role - the unit's raid assignment (string?)['MAINTANK', 'MAINASSIST']
--]]
if(element.PostUpdate) then
return element:PostUpdate(role)
end
end
local function Path(self, ...)
--[[ Override: RaidRoleIndicator.Override(self, event, ...)
Used to completely override the internal update function.
* self - the parent object
* event - the event triggering the update (string)
* ... - the arguments accompanying the event
--]]
return (self.RaidRoleIndicator.Override or Update)(self, ...)
end
local function ForceUpdate(element)
return Path(element.__owner, 'ForceUpdate')
end
local function Enable(self)
local element = self.RaidRoleIndicator
if(element) then
element.__owner = self
element.ForceUpdate = ForceUpdate
self:RegisterEvent('GROUP_ROSTER_UPDATE', Path, true)
return true
end
end
local function Disable(self)
local element = self.RaidRoleIndicator
if(element) then
element:Hide()
self:UnregisterEvent('GROUP_ROSTER_UPDATE', Path)
end
end
oUF:AddElement('RaidRoleIndicator', Path, Enable, Disable)
| mit |
SneakyB/iceball | pkg/iceball/halp/texts.lua | 4 | 3463 | texts = {}
texts.main = tparse([==[
$cFFFFFF55Welcome to Iceball!
Seeing as people don't know what
reading is, we're moving a quick
tutorial to here.
Use your up/down arrow keys to
scroll through the text.
Please read this whole document
carefully, as it contains
important information, and we
don't want to have to tell people
the same things all over again
which could be avoided if they
had read this tutorial.
$-
$cFFFFFF55What is Iceball?
Iceball is one of two things:
$pA game engine
$pA game built on said engine
This tutorial was built upon said
game engine, and the files can be
found in:
$cFFFF5555 pkg/iceball/halp/
You will not need the files for
the game itself in order to play
games written for Iceball, unless
you are hosting a "server".
This is because the server sends
all the code and files needed to
the clients that connect.
Note, use of pmfedit and mapedit
require you to host a local
"server".
If you ARE running a server, the
code and files are found in:
$cFFFF5555 pkg/base/
If this directory does not exist,
download the source code from:
$cFF55FF55https://
$cFF55FF55 github.com/iamgreaser/iceball/
$cFFFF5555If you are running a serious
$cFFFF5555server, you SHOULD be getting
$cFFFF5555your code from the github
$cFFFF5555repository, as it contains fixes
$cFFFF5555and whatnot.
$-
$cFFFFFF55How do I run Iceball?
Open up a commandline. On Windows,
you can double-click on:
$cFFFF5555 opencmd.bat
In your commandline, type:
$cFFAAAAFF iceball -h
It should give you brief
instructions on how to actually
run this game.
Yes, you do need to press Enter
at the end of a command.
$-
$cFFFFFF55How do I play the Iceball game?
Principles:
$cFFFF0000If you wear blue, you're on blue.
Same goes for green.
If you forget, look down.
$cFFFF0000Never EVER screw your team over.
Subterfuge does not exist.
Griefing your team is cheating.
We don't have an issue with grief
so far, but soon we'll add
support to ban small children.
$cFFFF0000COMMUNICATE
$cFFFF0000COMMUNICATE
$cFFFF0000COMMUNICATE
This cannot be stressed enough.
This is a team game.
If you cannot speak the language
of the server, find another
server.
Controls:
$pWASD = movement
$p1234 = select tool
$pArrows = change block colour
$pM = toggle large map
$pTYU = global/team/squad chat
$pSpace = jump
$pCtrl = crouch
$pV = sneak
$p, = change team
$p. = change gun
$pEsc = quit
Left click:
$pSpade = pick + get more blocks
$pBlock = place block
$pGun = shoot
$pGrenade = throw
Right click:
$pSpade = dig 3 high
$pBlock = pick block colour
$pGun = scope
TIP: you move slightly faster
with a spade in your hand.
$-
$cFFFFFF55Further documentation
How to configure Iceball
(e.g. setting your name and all
that crap):
$cFFFF5555 docs/setup_json.txt
Brief introduction to the engine
(for modders):
$cFFFF5555 docs/modding_101.txt
Lua API reference:
$cFFFF5555 docs/modding_lua.txt
This is also useful, though not
everything is available:
$cFF55FF55 http://lua.org/manual/5.1/
Modding API core reference:
$cFFFF5555 docs/modding_scripts.txt
File format specifications:
$cFFFF5555 docs/format_icemap.txt
$cFFFF5555 docs/format_pmf.txt
Editor usage:
$cFFFF5555 docs/editor_map.txt
$cFFFF5555 docs/editor_pmf.txt
$-
$cFF000000Kurukuru tokei no hari
$cFF000000 Guruguru atama mawaru
$cFF000000Datte tsubura medama
$cFF000000 Futatsu shika nai no ni
$cFF000000 Sanbon no hari nante
$cFF000000 Chinpunkan
]==])
return texts
--
| gpl-3.0 |
joaocc/ta3d-git | src/ta3d/src/luajit/src/jit/bcsave.lua | 20 | 18123 | ----------------------------------------------------------------------------
-- LuaJIT module to save/list bytecode.
--
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module saves or lists the bytecode for an input file.
-- It's run by the -b command line option.
--
------------------------------------------------------------------------------
local jit = require("jit")
assert(jit.version_num == 20002, "LuaJIT core/library version mismatch")
local bit = require("bit")
-- Symbol name prefix for LuaJIT bytecode.
local LJBC_PREFIX = "luaJIT_BC_"
------------------------------------------------------------------------------
local function usage()
io.stderr:write[[
Save LuaJIT bytecode: luajit -b[options] input output
-l Only list bytecode.
-s Strip debug info (default).
-g Keep debug info.
-n name Set module name (default: auto-detect from input name).
-t type Set output file type (default: auto-detect from output name).
-a arch Override architecture for object files (default: native).
-o os Override OS for object files (default: native).
-e chunk Use chunk string as input.
-- Stop handling options.
- Use stdin as input and/or stdout as output.
File types: c h obj o raw (default)
]]
os.exit(1)
end
local function check(ok, ...)
if ok then return ok, ... end
io.stderr:write("luajit: ", ...)
io.stderr:write("\n")
os.exit(1)
end
local function readfile(input)
if type(input) == "function" then return input end
if input == "-" then input = nil end
return check(loadfile(input))
end
local function savefile(name, mode)
if name == "-" then return io.stdout end
return check(io.open(name, mode))
end
------------------------------------------------------------------------------
local map_type = {
raw = "raw", c = "c", h = "h", o = "obj", obj = "obj",
}
local map_arch = {
x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true,
mips = true, mipsel = true,
}
local map_os = {
linux = true, windows = true, osx = true, freebsd = true, netbsd = true,
openbsd = true, solaris = true,
}
local function checkarg(str, map, err)
str = string.lower(str)
local s = check(map[str], "unknown ", err)
return s == true and str or s
end
local function detecttype(str)
local ext = string.match(string.lower(str), "%.(%a+)$")
return map_type[ext] or "raw"
end
local function checkmodname(str)
check(string.match(str, "^[%w_.%-]+$"), "bad module name")
return string.gsub(str, "[%.%-]", "_")
end
local function detectmodname(str)
if type(str) == "string" then
local tail = string.match(str, "[^/\\]+$")
if tail then str = tail end
local head = string.match(str, "^(.*)%.[^.]*$")
if head then str = head end
str = string.match(str, "^[%w_.%-]+")
else
str = nil
end
check(str, "cannot derive module name, use -n name")
return string.gsub(str, "[%.%-]", "_")
end
------------------------------------------------------------------------------
local function bcsave_tail(fp, output, s)
local ok, err = fp:write(s)
if ok and output ~= "-" then ok, err = fp:close() end
check(ok, "cannot write ", output, ": ", err)
end
local function bcsave_raw(output, s)
local fp = savefile(output, "wb")
bcsave_tail(fp, output, s)
end
local function bcsave_c(ctx, output, s)
local fp = savefile(output, "w")
if ctx.type == "c" then
fp:write(string.format([[
#ifdef _cplusplus
extern "C"
#endif
#ifdef _WIN32
__declspec(dllexport)
#endif
const char %s%s[] = {
]], LJBC_PREFIX, ctx.modname))
else
fp:write(string.format([[
#define %s%s_SIZE %d
static const char %s%s[] = {
]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname))
end
local t, n, m = {}, 0, 0
for i=1,#s do
local b = tostring(string.byte(s, i))
m = m + #b + 1
if m > 78 then
fp:write(table.concat(t, ",", 1, n), ",\n")
n, m = 0, #b + 1
end
n = n + 1
t[n] = b
end
bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n")
end
local function bcsave_elfobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct {
uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
uint16_t type, machine;
uint32_t version;
uint32_t entry, phofs, shofs;
uint32_t flags;
uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
} ELF32header;
typedef struct {
uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7];
uint16_t type, machine;
uint32_t version;
uint64_t entry, phofs, shofs;
uint32_t flags;
uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx;
} ELF64header;
typedef struct {
uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize;
} ELF32sectheader;
typedef struct {
uint32_t name, type;
uint64_t flags, addr, ofs, size;
uint32_t link, info;
uint64_t align, entsize;
} ELF64sectheader;
typedef struct {
uint32_t name, value, size;
uint8_t info, other;
uint16_t sectidx;
} ELF32symbol;
typedef struct {
uint32_t name;
uint8_t info, other;
uint16_t sectidx;
uint64_t value, size;
} ELF64symbol;
typedef struct {
ELF32header hdr;
ELF32sectheader sect[6];
ELF32symbol sym[2];
uint8_t space[4096];
} ELF32obj;
typedef struct {
ELF64header hdr;
ELF64sectheader sect[6];
ELF64symbol sym[2];
uint8_t space[4096];
} ELF64obj;
]]
local symname = LJBC_PREFIX..ctx.modname
local is64, isbe = false, false
if ctx.arch == "x64" then
is64 = true
elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then
isbe = true
end
-- Handle different host/target endianess.
local function f32(x) return x end
local f16, fofs = f32, f32
if ffi.abi("be") ~= isbe then
f32 = bit.bswap
function f16(x) return bit.rshift(bit.bswap(x), 16) end
if is64 then
local two32 = ffi.cast("int64_t", 2^32)
function fofs(x) return bit.bswap(x)*two32 end
else
fofs = f32
end
end
-- Create ELF object and fill in header.
local o = ffi.new(is64 and "ELF64obj" or "ELF32obj")
local hdr = o.hdr
if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi.
local bf = assert(io.open("/bin/ls", "rb"))
local bs = bf:read(9)
bf:close()
ffi.copy(o, bs, 9)
check(hdr.emagic[0] == 127, "no support for writing native object files")
else
hdr.emagic = "\127ELF"
hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0
end
hdr.eclass = is64 and 2 or 1
hdr.eendian = isbe and 2 or 1
hdr.eversion = 1
hdr.type = f16(1)
hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch])
if ctx.arch == "mips" or ctx.arch == "mipsel" then
hdr.flags = 0x50001006
end
hdr.version = f32(1)
hdr.shofs = fofs(ffi.offsetof(o, "sect"))
hdr.ehsize = f16(ffi.sizeof(hdr))
hdr.shentsize = f16(ffi.sizeof(o.sect[0]))
hdr.shnum = f16(6)
hdr.shstridx = f16(2)
-- Fill in sections and symbols.
local sofs, ofs = ffi.offsetof(o, "space"), 1
for i,name in ipairs{
".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack",
} do
local sect = o.sect[i]
sect.align = fofs(1)
sect.name = f32(ofs)
ffi.copy(o.space+ofs, name)
ofs = ofs + #name+1
end
o.sect[1].type = f32(2) -- .symtab
o.sect[1].link = f32(3)
o.sect[1].info = f32(1)
o.sect[1].align = fofs(8)
o.sect[1].ofs = fofs(ffi.offsetof(o, "sym"))
o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0]))
o.sect[1].size = fofs(ffi.sizeof(o.sym))
o.sym[1].name = f32(1)
o.sym[1].sectidx = f16(4)
o.sym[1].size = fofs(#s)
o.sym[1].info = 17
o.sect[2].type = f32(3) -- .shstrtab
o.sect[2].ofs = fofs(sofs)
o.sect[2].size = fofs(ofs)
o.sect[3].type = f32(3) -- .strtab
o.sect[3].ofs = fofs(sofs + ofs)
o.sect[3].size = fofs(#symname+1)
ffi.copy(o.space+ofs+1, symname)
ofs = ofs + #symname + 2
o.sect[4].type = f32(1) -- .rodata
o.sect[4].flags = fofs(2)
o.sect[4].ofs = fofs(sofs + ofs)
o.sect[4].size = fofs(#s)
o.sect[5].type = f32(1) -- .note.GNU-stack
o.sect[5].ofs = fofs(sofs + ofs + #s)
-- Write ELF object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
bcsave_tail(fp, output, s)
end
local function bcsave_peobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct {
uint16_t arch, nsects;
uint32_t time, symtabofs, nsyms;
uint16_t opthdrsz, flags;
} PEheader;
typedef struct {
char name[8];
uint32_t vsize, vaddr, size, ofs, relocofs, lineofs;
uint16_t nreloc, nline;
uint32_t flags;
} PEsection;
typedef struct __attribute((packed)) {
union {
char name[8];
uint32_t nameref[2];
};
uint32_t value;
int16_t sect;
uint16_t type;
uint8_t scl, naux;
} PEsym;
typedef struct __attribute((packed)) {
uint32_t size;
uint16_t nreloc, nline;
uint32_t cksum;
uint16_t assoc;
uint8_t comdatsel, unused[3];
} PEsymaux;
typedef struct {
PEheader hdr;
PEsection sect[2];
// Must be an even number of symbol structs.
PEsym sym0;
PEsymaux sym0aux;
PEsym sym1;
PEsymaux sym1aux;
PEsym sym2;
PEsym sym3;
uint32_t strtabsize;
uint8_t space[4096];
} PEobj;
]]
local symname = LJBC_PREFIX..ctx.modname
local is64 = false
if ctx.arch == "x86" then
symname = "_"..symname
elseif ctx.arch == "x64" then
is64 = true
end
local symexport = " /EXPORT:"..symname..",DATA "
-- The file format is always little-endian. Swap if the host is big-endian.
local function f32(x) return x end
local f16 = f32
if ffi.abi("be") then
f32 = bit.bswap
function f16(x) return bit.rshift(bit.bswap(x), 16) end
end
-- Create PE object and fill in header.
local o = ffi.new("PEobj")
local hdr = o.hdr
hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch])
hdr.nsects = f16(2)
hdr.symtabofs = f32(ffi.offsetof(o, "sym0"))
hdr.nsyms = f32(6)
-- Fill in sections and symbols.
o.sect[0].name = ".drectve"
o.sect[0].size = f32(#symexport)
o.sect[0].flags = f32(0x00100a00)
o.sym0.sect = f16(1)
o.sym0.scl = 3
o.sym0.name = ".drectve"
o.sym0.naux = 1
o.sym0aux.size = f32(#symexport)
o.sect[1].name = ".rdata"
o.sect[1].size = f32(#s)
o.sect[1].flags = f32(0x40300040)
o.sym1.sect = f16(2)
o.sym1.scl = 3
o.sym1.name = ".rdata"
o.sym1.naux = 1
o.sym1aux.size = f32(#s)
o.sym2.sect = f16(2)
o.sym2.scl = 2
o.sym2.nameref[1] = f32(4)
o.sym3.sect = f16(-1)
o.sym3.scl = 2
o.sym3.value = f32(1)
o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant.
ffi.copy(o.space, symname)
local ofs = #symname + 1
o.strtabsize = f32(ofs + 4)
o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs)
ffi.copy(o.space + ofs, symexport)
ofs = ofs + #symexport
o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs)
-- Write PE object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs))
bcsave_tail(fp, output, s)
end
local function bcsave_machobj(ctx, output, s, ffi)
ffi.cdef[[
typedef struct
{
uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags;
} mach_header;
typedef struct
{
mach_header; uint32_t reserved;
} mach_header_64;
typedef struct {
uint32_t cmd, cmdsize;
char segname[16];
uint32_t vmaddr, vmsize, fileoff, filesize;
uint32_t maxprot, initprot, nsects, flags;
} mach_segment_command;
typedef struct {
uint32_t cmd, cmdsize;
char segname[16];
uint64_t vmaddr, vmsize, fileoff, filesize;
uint32_t maxprot, initprot, nsects, flags;
} mach_segment_command_64;
typedef struct {
char sectname[16], segname[16];
uint32_t addr, size;
uint32_t offset, align, reloff, nreloc, flags;
uint32_t reserved1, reserved2;
} mach_section;
typedef struct {
char sectname[16], segname[16];
uint64_t addr, size;
uint32_t offset, align, reloff, nreloc, flags;
uint32_t reserved1, reserved2, reserved3;
} mach_section_64;
typedef struct {
uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize;
} mach_symtab_command;
typedef struct {
int32_t strx;
uint8_t type, sect;
int16_t desc;
uint32_t value;
} mach_nlist;
typedef struct {
uint32_t strx;
uint8_t type, sect;
uint16_t desc;
uint64_t value;
} mach_nlist_64;
typedef struct
{
uint32_t magic, nfat_arch;
} mach_fat_header;
typedef struct
{
uint32_t cputype, cpusubtype, offset, size, align;
} mach_fat_arch;
typedef struct {
struct {
mach_header hdr;
mach_segment_command seg;
mach_section sec;
mach_symtab_command sym;
} arch[1];
mach_nlist sym_entry;
uint8_t space[4096];
} mach_obj;
typedef struct {
struct {
mach_header_64 hdr;
mach_segment_command_64 seg;
mach_section_64 sec;
mach_symtab_command sym;
} arch[1];
mach_nlist_64 sym_entry;
uint8_t space[4096];
} mach_obj_64;
typedef struct {
mach_fat_header fat;
mach_fat_arch fat_arch[4];
struct {
mach_header hdr;
mach_segment_command seg;
mach_section sec;
mach_symtab_command sym;
} arch[4];
mach_nlist sym_entry;
uint8_t space[4096];
} mach_fat_obj;
]]
local symname = '_'..LJBC_PREFIX..ctx.modname
local isfat, is64, align, mobj = false, false, 4, "mach_obj"
if ctx.arch == "x64" then
is64, align, mobj = true, 8, "mach_obj_64"
elseif ctx.arch == "arm" then
isfat, mobj = true, "mach_fat_obj"
else
check(ctx.arch == "x86", "unsupported architecture for OSX")
end
local function aligned(v, a) return bit.band(v+a-1, -a) end
local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE.
-- Create Mach-O object and fill in header.
local o = ffi.new(mobj)
local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align)
local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch]
local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch]
if isfat then
o.fat.magic = be32(0xcafebabe)
o.fat.nfat_arch = be32(#cpusubtype)
end
-- Fill in sections and symbols.
for i=0,#cpusubtype-1 do
local ofs = 0
if isfat then
local a = o.fat_arch[i]
a.cputype = be32(cputype[i+1])
a.cpusubtype = be32(cpusubtype[i+1])
-- Subsequent slices overlap each other to share data.
ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0])
a.offset = be32(ofs)
a.size = be32(mach_size-ofs+#s)
end
local a = o.arch[i]
a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface
a.hdr.cputype = cputype[i+1]
a.hdr.cpusubtype = cpusubtype[i+1]
a.hdr.filetype = 1
a.hdr.ncmds = 2
a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym)
a.seg.cmd = is64 and 0x19 or 0x1
a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)
a.seg.vmsize = #s
a.seg.fileoff = mach_size-ofs
a.seg.filesize = #s
a.seg.maxprot = 1
a.seg.initprot = 1
a.seg.nsects = 1
ffi.copy(a.sec.sectname, "__data")
ffi.copy(a.sec.segname, "__DATA")
a.sec.size = #s
a.sec.offset = mach_size-ofs
a.sym.cmd = 2
a.sym.cmdsize = ffi.sizeof(a.sym)
a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs
a.sym.nsyms = 1
a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs
a.sym.strsize = aligned(#symname+2, align)
end
o.sym_entry.type = 0xf
o.sym_entry.sect = 1
o.sym_entry.strx = 1
ffi.copy(o.space+1, symname)
-- Write Macho-O object file.
local fp = savefile(output, "wb")
fp:write(ffi.string(o, mach_size))
bcsave_tail(fp, output, s)
end
local function bcsave_obj(ctx, output, s)
local ok, ffi = pcall(require, "ffi")
check(ok, "FFI library required to write this file type")
if ctx.os == "windows" then
return bcsave_peobj(ctx, output, s, ffi)
elseif ctx.os == "osx" then
return bcsave_machobj(ctx, output, s, ffi)
else
return bcsave_elfobj(ctx, output, s, ffi)
end
end
------------------------------------------------------------------------------
local function bclist(input, output)
local f = readfile(input)
require("jit.bc").dump(f, savefile(output, "w"), true)
end
local function bcsave(ctx, input, output)
local f = readfile(input)
local s = string.dump(f, ctx.strip)
local t = ctx.type
if not t then
t = detecttype(output)
ctx.type = t
end
if t == "raw" then
bcsave_raw(output, s)
else
if not ctx.modname then ctx.modname = detectmodname(input) end
if t == "obj" then
bcsave_obj(ctx, output, s)
else
bcsave_c(ctx, output, s)
end
end
end
local function docmd(...)
local arg = {...}
local n = 1
local list = false
local ctx = {
strip = true, arch = jit.arch, os = string.lower(jit.os),
type = false, modname = false,
}
while n <= #arg do
local a = arg[n]
if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then
table.remove(arg, n)
if a == "--" then break end
for m=2,#a do
local opt = string.sub(a, m, m)
if opt == "l" then
list = true
elseif opt == "s" then
ctx.strip = true
elseif opt == "g" then
ctx.strip = false
else
if arg[n] == nil or m ~= #a then usage() end
if opt == "e" then
if n ~= 1 then usage() end
arg[1] = check(loadstring(arg[1]))
elseif opt == "n" then
ctx.modname = checkmodname(table.remove(arg, n))
elseif opt == "t" then
ctx.type = checkarg(table.remove(arg, n), map_type, "file type")
elseif opt == "a" then
ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture")
elseif opt == "o" then
ctx.os = checkarg(table.remove(arg, n), map_os, "OS name")
else
usage()
end
end
end
else
n = n + 1
end
end
if list then
if #arg == 0 or #arg > 2 then usage() end
bclist(arg[1], arg[2] or "-")
else
if #arg ~= 2 then usage() end
bcsave(ctx, arg[1], arg[2])
end
end
------------------------------------------------------------------------------
-- Public module functions.
module(...)
start = docmd -- Process -b command line option.
| gpl-2.0 |
blueluna/tempserv | modules/radio.lua | 1 | 3945 | -- Radio package handling
--
-- (C) 2014 Erik Svensson <erik.public@gmail.com>
-- Licensed under MIT
local nrf24 = require("nrf24")
local decode = require("decode")
local time = require("time")
local string = require("string")
local Radio = { nrf = nil }
function Radio:open(spi_master, spi_device, ce_pin)
local nrf = nrf24.Nrf24:create(spi_master, spi_device, ce_pin)
obj = nil
if nrf ~= nil then
obj = obj or {}
setmetatable(obj, self)
self.__index = self
self.nrf = nrf
self.nrf:setup(1, 250, 0, "serv1", "clie1", 32, 1, 5, 2000)
else
error("failed to create Nrf24 object")
end
return obj
end
function Radio:version()
return string.format("libnrf24 %d.%d.%d (%s)", nrf24.version())
end
function Radio:close()
self.nrf:destroy()
end
function Radio:power_up()
self.nrf:power_up()
nrf24.msleep(2) -- let the radio power up
end
function Radio:power_down()
self.nrf:power_down()
end
function Radio:query()
local result
local tx_data = {0x01} -- 0x01 means query
local ready
local start
local now
local diff
local rx_data
local rx_data_len = 0
ready = false
count = 0
-- send query, with retry
start = time.useconds_now()
repeat
result = self.nrf:send(tx_data)
if result < 0 then
now = time.useconds_now()
diff = now - start
if (diff >= 20000) then
break;
else
nrf24.usleep(1000) -- wait some
end
else
break;
end
until true
if result < 0 then
error("Failed to send message")
end
-- we seem to be required to wait some here otherwise start_listen seems
-- to fail
nrf24.usleep(700)
-- start listening for reply
self.nrf:start_listen()
-- wait some, the response seems to ready after ~6 ms at earliest
nrf24.msleep(6)
start = time.useconds_now()
while ready == false do
ready = self.nrf:data_ready()
if not ready then
now = time.useconds_now()
diff = now - start
if diff >= 200000 then
break;
else
nrf24.msleep(5) -- wait some
end
end
end
rx_data_len = 0
if ready then
rx_data, rx_data_len = self.nrf:receive()
end
self.nrf:stop_listen()
-- parse the response if any
if rx_data_len > 0 then
state, arg1, arg2 = Radio:handle_package(rx_data, rx_data_len)
if state == 'device_data' then
return true, arg1, arg2
elseif state == 'device_error' then
error(string.format('Device Error: %04x', arg1))
elseif state == 'error_command' then
error(string.format('Remote Unknown Command: %02x\n', arg1))
elseif state == 'error' then
error(string.format('Error: %02x\n', arg1))
elseif state == 'error_unknown_command' then
error(string.format('Unknown Command: %02x\n', arg1))
else
return false
end
else
error("Failed to receive response")
end
end
function Radio:handle_package(package_data, package_data_length)
local data = package_data
local len = package_data_length
local offset = 0
local command = decode.uint8(data, len)
offset = offset + 1
len = len - 1
if command == 0x81 then
local code = decode.int16(data+offset, len)
offset = offset + 2
len = len - 2
if code == 0x0000 then
local device = decode.uint64(data+offset, len)
offset = offset + 8
len = len - 8
local value = decode.int32(data+offset, len)
offset = offset + 4
len = len - 4
real_value = value / 1000000.0
return 'device_data', device, real_value
elseif code == 0x000f then
return 'device_end'
else
error(string.format('Device Error: %04x', code))
end
elseif command == 0xff then
local code = decode.int16(data+offset, len)
offset = offset + 2
len = len - 2
if code == 12 then
local received_command = decode.uint8(data+offset, len)
return 'error_command', received_command
else
return 'error', code
end
else
return 'error_unknown_command', command
end
end
return { Radio = Radio }
| mit |
TeleBang/bangtg | plugins/filterfa.lua | 8 | 2538 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "کلمه جدید به فیلتر کلمات اضافه شد\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات غیرمجاز :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' پاک شد'
end
local function run(msg, matches)
if matches[2] == 'فیلتر' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'filterlist' then
return list_variablesbad(msg)
elseif matches[2] == 'حذف' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'خ فیلتر' or matches[2] == 'خ فیلتر' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/#])(خ فیلتر) (.*)$",
"^([!/#])(فیلتر) (.*)$",
"^([!/#])(خ فیلتر) (.*)$",
"^([!/#])(لیست فیلتر)$",
"^([!/#])(حذف) لیست فیلتر$",
"^(.+)$",
},
run = run
}
| agpl-3.0 |
rlcevg/Zero-K | gamedata/modularcomms/weapons/rocketlauncher.lua | 6 | 1244 | local name = "commweapon_rocketlauncher"
local weaponDef = {
name = [[Rocket Launcher]],
areaOfEffect = 75,
cegTag = [[missiletrailred]],
craterBoost = 0,
craterMult = 0,
customParams = {
slot = [[5]],
muzzleEffectFire = [[custom:STORMMUZZLE]],
},
damage = {
default = 360,
planes = 360,
subs = 18,
},
fireStarter = 180,
flightTime = 3,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 2,
model = [[wep_m_hailstorm.s3o]],
predictBoost = 1,
range = 430,
reloadtime = 3,
smokeTrail = true,
soundHit = [[explosion/ex_med4]],
soundHitVolume = 7,
soundStart = [[weapon/missile/sabot_fire]],
soundStartVolume = 7,
startVelocity = 200,
texture2 = [[darksmoketrail]],
tracks = false,
trajectoryHeight = 0.05,
turret = true,
weaponAcceleration = 100,
weaponType = [[MissileLauncher]],
weaponVelocity = 250,
}
return name, weaponDef
| gpl-2.0 |
abdllhbyrktr/Urho3D | Source/ThirdParty/toluapp/src/bin/lua/basic.lua | 24 | 9103 | -- tolua: basic utility functions
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- Last update: Apr 2003
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Modified by Yao Wei Tjong for Urho3D
-- Basic C types and their corresponding Lua types
-- All occurrences of "char*" will be replaced by "_cstring",
-- and all occurrences of "void*" will be replaced by "_userdata"
_basic = {
['void'] = '',
['char'] = 'number',
['int'] = 'number',
['short'] = 'number',
['long'] = 'number',
['unsigned'] = 'number',
['float'] = 'number',
['double'] = 'number',
['_cstring'] = 'string',
['_userdata'] = 'userdata',
['char*'] = 'string',
['void*'] = 'userdata',
['bool'] = 'boolean',
['lua_Object'] = 'value',
['LUA_VALUE'] = 'value', -- for compatibility with tolua 4.0
['lua_State*'] = 'state',
['_lstate'] = 'state',
['lua_Function'] = 'value',
}
_basic_ctype = {
number = "lua_Number",
string = "const char*",
userdata = "void*",
boolean = "bool",
value = "int",
state = "lua_State*",
}
-- functions the are used to do a 'raw push' of basic types
_basic_raw_push = {}
-- List of user defined types
-- Each type corresponds to a variable name that stores its tag value.
_usertype = {}
-- List of types that have to be collected
_collect = {}
-- List of types
_global_types = {n=0}
_global_types_hash = {}
-- list of classes
_global_classes = {}
-- List of enum constants
_global_enums = {}
-- List of auto renaming
_renaming = {}
function appendrenaming (s)
local b,e,old,new = strfind(s,"%s*(.-)%s*@%s*(.-)%s*$")
if not b then
error("#Invalid renaming syntax; it should be of the form: pattern@pattern")
end
tinsert(_renaming,{old=old, new=new})
end
function applyrenaming (s)
for i=1,getn(_renaming) do
local m,n = gsub(s,_renaming[i].old,_renaming[i].new)
if n ~= 0 then
return m
end
end
return nil
end
-- Error handler
function tolua_error (s,f)
if _curr_code then
print("***curr code for error is "..tostring(_curr_code))
print(debug.traceback())
end
local out = _OUTPUT
_OUTPUT = _STDERR
if strsub(s,1,1) == '#' then
write("\n** tolua: "..strsub(s,2)..".\n\n")
if _curr_code then
local _,_,s = strfind(_curr_code,"^%s*(.-\n)") -- extract first line
if s==nil then s = _curr_code end
s = gsub(s,"_userdata","void*") -- return with 'void*'
s = gsub(s,"_cstring","char*") -- return with 'char*'
s = gsub(s,"_lstate","lua_State*") -- return with 'lua_State*'
write("Code being processed:\n"..s.."\n")
end
else
if not f then f = "(f is nil)" end
print("\n** tolua internal error: "..f..s..".\n\n")
return
end
_OUTPUT = out
end
function warning (msg)
if flags.q then return end
local out = _OUTPUT
_OUTPUT = _STDERR
write("\n** tolua warning: "..msg..".\n\n")
_OUTPUT = out
end
-- register an user defined type: returns full type
function regtype (t)
--if isbasic(t) then
-- return t
--end
local ft = findtype(t)
if not _usertype[ft] then
return appendusertype(t)
end
return ft
end
-- return type name: returns full type
function typevar(type)
if type == '' or type == 'void' then
return type
else
local ft = findtype(type)
if ft then
return ft
end
_usertype[type] = type
return type
end
end
-- check if basic type
function isbasic (type)
local t = gsub(type,'const ','')
local m,t = applytypedef('', t)
local b = _basic[t]
if b then
return b,_basic_ctype[b]
end
return nil
end
-- split string using a token
function split (s,t)
local l = {n=0}
local f = function (s)
l.n = l.n + 1
l[l.n] = s
return ""
end
local p = "%s*(.-)%s*"..t.."%s*"
s = gsub(s,"^%s+","")
s = gsub(s,"%s+$","")
s = gsub(s,p,f)
l.n = l.n + 1
l[l.n] = gsub(s,"(%s%s*)$","")
return l
end
-- splits a string using a pattern, considering the spacial cases of C code (templates, function parameters, etc)
-- pattern can't contain the '^' (as used to identify the begining of the line)
-- also strips whitespace
function split_c_tokens(s, pat)
s = string.gsub(s, "^%s*", "")
s = string.gsub(s, "%s*$", "")
local token_begin = 1
local token_end = 1
local ofs = 1
local ret = {n=0}
function add_token(ofs)
local t = string.sub(s, token_begin, ofs)
t = string.gsub(t, "^%s*", "")
t = string.gsub(t, "%s*$", "")
ret.n = ret.n + 1
ret[ret.n] = t
end
while ofs <= string.len(s) do
local sub = string.sub(s, ofs, -1)
local b,e = string.find(sub, "^"..pat)
if b then
add_token(ofs-1)
ofs = ofs+e
token_begin = ofs
else
local char = string.sub(s, ofs, ofs)
if char == "(" or char == "<" then
local block
if char == "(" then block = "^%b()" end
if char == "<" then block = "^%b<>" end
b,e = string.find(sub, block)
if not b then
-- unterminated block?
ofs = ofs+1
else
ofs = ofs + e
end
else
ofs = ofs+1
end
end
end
add_token(ofs)
--if ret.n == 0 then
-- ret.n=1
-- ret[1] = ""
--end
return ret
end
-- concatenate strings of a table
function concat (t,f,l,jstr)
jstr = jstr or " "
local s = ''
local i=f
while i<=l do
s = s..t[i]
i = i+1
if i <= l then s = s..jstr end
end
return s
end
-- Urho3D: replace deprecated arg usage
-- concatenate all parameters, following output rules
function concatparam (line, ...)
local i=1
while i<=select("#",...) do
if _cont and not strfind(_cont,'[%(,"]') and
strfind(select(i,...),"^[%a_~]") then
line = line .. ' '
end
line = line .. select(i,...)
if select(i,...) ~= '' then
_cont = strsub(select(i,...),-1,-1)
end
i = i+1
end
if strfind(select(select("#",...),...),"[%/%)%;%{%}]$") then
_cont=nil line = line .. '\n'
end
return line
end
-- output line
function output (...)
local i=1
while i<=select("#",...) do
if _cont and not strfind(_cont,'[%(,"]') and
strfind(select(i,...),"^[%a_~]") then
write(' ')
end
write((select(i,...)))
if select(i,...) ~= '' then
_cont = strsub(select(i,...),-1,-1)
end
i = i+1
end
if strfind(select(select("#",...),...),"[%/%)%;%{%}]$") then
_cont=nil write('\n')
end
end
function get_property_methods(ptype, name)
if get_property_methods_hook and get_property_methods_hook(ptype,name) then
return get_property_methods_hook(ptype, name)
end
if ptype == "default" then -- get_name, set_name
return "get_"..name, "set_"..name
end
if ptype == "qt" then -- name, setName
return name, "set"..string.upper(string.sub(name, 1, 1))..string.sub(name, 2, -1)
end
if ptype == "overload" then -- name, name
return name,name
end
return nil
end
-------------- the hooks
-- called right after processing the $[ichl]file directives,
-- right before processing anything else
-- takes the package object as the parameter
function preprocess_hook(p)
-- p.code has all the input code from the pkg
end
-- called for every $ifile directive
-- takes a table with a string called 'code' inside, the filename, and any extra arguments
-- passed to $ifile. no return value
function include_file_hook(t, filename, ...)
end
-- called after processing anything that's not code (like '$renaming', comments, etc)
-- and right before parsing the actual code.
-- takes the Package object with all the code on the 'code' key. no return value
function preparse_hook(package)
end
-- called before starting output
function pre_output_hook(package)
end
-- called after writing all the output.
-- takes the Package object
function post_output_hook(package)
end
-- called from 'get_property_methods' to get the methods to retrieve a property
-- according to its type
function get_property_methods_hook(property_type, name)
end
-- called from ClassContainer:doparse with the string being parsed
-- return nil, or a substring
function parser_hook(s)
return nil
end
-- called from classFunction:supcode, before the call to the function is output
function pre_call_hook(f)
end
-- called from classFunction:supcode, after the call to the function is output
function post_call_hook(f)
end
-- called before the register code is output
function pre_register_hook(package)
end
-- called to output an error message
function output_error_hook(...)
return string.format(...)
end
-- custom pushers
_push_functions = {}
_is_functions = {}
_to_functions = {}
_base_push_functions = {}
_base_is_functions = {}
_base_to_functions = {}
local function search_base(t, funcs)
local class = _global_classes[t]
while class do
if funcs[class.type] then
return funcs[class.type]
end
class = _global_classes[class.btype]
end
return nil
end
function get_push_function(t)
return _push_functions[t] or search_base(t, _base_push_functions) or "tolua_pushusertype"
end
function get_to_function(t)
return _to_functions[t] or search_base(t, _base_to_functions) or "tolua_tousertype"
end
function get_is_function(t)
return _is_functions[t] or search_base(t, _base_is_functions) or "tolua_isusertype"
end
| mit |
jacklanchantin/sclm | evaluate.lua | 1 | 1883 | require 'torch'
require 'nn'
require 'optim'
include('auRoc.lua')
torch.setdefaulttensortype('torch.FloatTensor')
local utils = require 'util.utils'
local unpack = unpack or table.unpack
local cmd = torch.CmdLine()
cmd:option('-file', './global_results.t7')
local opt = cmd:parse(arg)
results = torch.load(opt.file)
rnn_0 = torch.Tensor(results[0]['rnn'])
rnn_1 = torch.Tensor(results[1]['rnn'])
ngram_0 = torch.Tensor(results[0]['ngram'])
ngram_1 = torch.Tensor(results[1]['ngram'])
-- normalize
-- rnn_0 = (rnn_0-rnn_0:min())/rnn_0:max()
-- rnn_1 = (rnn_1-rnn_1:min())/rnn_1:max()
-- ngram_0 = (ngram_0-ngram_0:min())/ngram_0:max()
-- ngram_1 = (ngram_1-ngram_1:min())/ngram_1:max()
rnn_0_avg = rnn_0:sum()/rnn_0:size(1)
rnn_1_avg = rnn_1:sum()/rnn_1:size(1)
ngram_0_avg = ngram_0:sum()/ngram_0:size(1)
ngram_1_avg = ngram_1:sum()/ngram_1:size(1)
print('Non-buggy rnn: '..tostring(rnn_0_avg))
print('Buggy rnn: '..tostring(rnn_1_avg))
print('Difference: '..tostring(rnn_1_avg-rnn_0_avg))
print('')
print('Non-buggy ngram: '..tostring(ngram_0_avg))
print('Buggy ngram: '..tostring(ngram_1_avg))
print('Difference: '..tostring(ngram_1_avg-ngram_0_avg))
print('')
AUC = auRoc:new()
-- file = io.open("rnn_nonbuggy_entropy.txt", "w")
-- for i = 1,rnn_0:size(1) do
-- file:write(tostring(rnn_0[i])..'\n')
-- end
-- file:close()
-- file = io.open("rnn_buggy_entropy.txt", "w")
-- for i = 1,rnn_1:size(1) do
-- file:write(tostring(rnn_1[i])..'\n')
-- end
-- file:close()
-- os.exit()
for i = 1,rnn_0:size(1) do
AUC:add(rnn_0[i], -1)
end
for i = 1,rnn_1:size(1) do
AUC:add(rnn_1[i], 1)
end
AUROC = AUC:calculateAuc()
print('RNN AUROC: '..AUROC)
AUC:zero()
for i = 1,ngram_0:size(1) do
AUC:add(ngram_0[i], -1)
end
for i = 1,ngram_1:size(1) do
AUC:add(ngram_1[i], 1)
end
AUROC = AUC:calculateAuc()
print('ngram AUROC: '..AUROC)
AUC:zero()
| mit |
SonyWWS/SLED | tool/SledSyntaxEditor/Intellisense/Lua/StandardLibrary/basic.lua | 1 | 10155 | --[[
-- lua standard library -- Basic Functions
--]]
--[[
Issues an error when the value of its argument <em>v</em> is false (i.e., nil or false); otherwise, returns all its arguments.
<em>message</em> is an error message; when absent, it defaults to "assertion failed!"
--]]
function assert( v, message ) end
--[[
This function is a generic interface to the garbage collector. It performs different functions according to its first argument, opt:
* "collect": performs a full garbage-collection cycle. This is the default option.
* "stop": stops automatic execution of the garbage collector. The collector will run only when explicitly invoked, until a call to restart it.
* "restart": restarts automatic execution of the garbage collector.
* "count": returns the total memory in use by Lua (in Kbytes) and a second value with the total memory in bytes modulo 1024. The first value has a fractional part, so the following equality is always true:
k, b = collectgarbage("count")
assert(k*1024 == math.floor(k)*1024 + b)
(The second result is useful when Lua is compiled with a non floating-point type for numbers.)
* "step": performs a garbage-collection step. The step "size" is controlled by arg (larger values mean more steps) in a non-specified way. If you want to control the step size you must experimentally tune the value of arg. Returns true if the step finished a collection cycle.
* "setpause": sets arg as the new value for the pause of the collector (see §2.5). Returns the previous value for pause.
* "setstepmul": sets arg as the new value for the step multiplier of the collector (see §2.5). Returns the previous value for step.
* "isrunning": returns a boolean that tells whether the collector is running (i.e., not stopped).
* "generational": changes the collector to generational mode. This is an experimental feature (see §2.5).
* "incremental": changes the collector to incremental mode. This is the default mode.
--]]
function collectgarbage( opt, arg ) end
--[[
Opens the named file and executes its contents as a Lua chunk.
When called without arguments, dofile executes the contents of the standard input (stdin).
Returns all values returned by the chunk.
In case of errors, dofile propagates the error to its caller (that is, dofile does not run in protected mode).
--]]
function dofile( filename ) end
--[[
Terminates the last protected function called and returns message as the error message. Function error never returns.
Usually, error adds some information about the error position at the beginning of the message, if the message is a string. The level argument specifies how to get the error position. With level 1 (the default), the error position is where the error function was called. Level 2 points the error to where the function that called error was called; and so on. Passing a level 0 avoids the addition of error position information to the message.
--]]
function error( message, level ) end
--[[
A global variable (not a function) that holds the global environment. Lua itself does not use this variable; changing its value does not affect any environment, nor vice-versa.
--]]
_G = {}
--[[
If object does not have a metatable, returns nil. Otherwise, if the object's metatable has a "__metatable" field, returns the associated value. Otherwise, returns the metatable of the given object.
--]]
function getmetatable( object ) end
--[[
If t has a metamethod __ipairs, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: an iterator function, the table t, and 0, so that the construction
for i,v in ipairs(t) do body end
will iterate over the pairs (1,t[1]), (2,t[2]), ..., up to the first integer key absent from the table.
--]]
function ipairs( table ) end
--[[
Loads a chunk.
If ld is a string, the chunk is this string. If ld is a function, load calls it repeatedly to get the chunk pieces. Each call to ld must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.
If there are no syntactic errors, returns the compiled chunk as a function; otherwise, returns nil plus the error message.
If the resulting function has upvalues, the first upvalue is set to the value of the global environment or to env, if that parameter is given. When loading main chunks, the first upvalue will be the _ENV variable (see §2.2).
source is used as the source of the chunk for error messages and debug information (see §4.9). When absent, it defaults to ld, if ld is a string, or to "=(load)" otherwise.
The string mode controls whether the chunk can be text or binary (that is, a precompiled chunk). It may be the string "b" (only binary chunks), "t" (only text chunks), or "bt" (both binary and text). The default is "bt".
--]]
function load( ld, source, mode, env ) end
--[[
Similar to load, but gets the chunk from file filename or from the standard input, if no file name is given.
--]]
function loadfile( filename, mode, env ) end
--[[
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.
The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for.)
The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.
--]]
function next( table, index ) end
--[[
If t has a metamethod __pairs, calls it with t as argument and returns the first three results from the call.
Otherwise, returns three values: the next function, the table t, and nil, so that the construction
for k,v in pairs(t) do body end
will iterate over all key–value pairs of table t.
See function next for the caveats of modifying the table during its traversal.
--]]
function pairs( t ) end
--[[
Calls function f with the given arguments in protected mode. This means that any error inside f is not propagated; instead, pcall catches the error and returns a status code. Its first result is the status code (a boolean), which is true if the call succeeds without errors. In such case, pcall also returns all results from the call, after this first result. In case of any error, pcall returns false plus the error message.
--]]
function pcall( func, ... ) end
--[[
Receives any number of arguments and prints their values to stdout, using the tostring function to convert each argument to a string. print is not intended for formatted output, but only as a quick way to show a value, for instance for debugging. For complete control over the output, use string.format and io.write.
--]]
function print( ... ) end
--[[
Checks whether v1 is equal to v2, without invoking any metamethod. Returns a boolean.
--]]
function rawequal( v1, v2 ) end
--[[
Gets the real value of table[index], without invoking any metamethod. table must be a table; index may be any value.
--]]
function rawget( table, index) end
--[[
Returns the length of the object v, which must be a table or a string, without invoking any metamethod. Returns an integer number.
--]]
function rawlen( v ) end
--[[
Sets the real value of table[index] to value, without invoking any metamethod. table must be a table, index any value different from nil and NaN, and value any Lua value.
This function returns table.
--]]
function rawset( table, index, value ) end
--[[
If index is a number, returns all arguments after argument number index; a negative number indexes from the end (-1 is the last argument). Otherwise, index must be the string "#", and select returns the total number of extra arguments it received.
--]]
function select( index, ... ) end
--[[
Sets the metatable for the given table. (You cannot change the metatable of other types from Lua, only from C.) If metatable is nil, removes the metatable of the given table. If the original metatable has a "__metatable" field, raises an error.
This function returns table.
--]]
function setmetatable( table, metatable ) end
--[[
When called with no base, tonumber tries to convert its argument to a number. If the argument is already a number or a string convertible to a numbe, then tonumber returns this number; otherwise, it returns nil.
When called with base, then e should be a string to be interpreted as an integer numeral in that base. The base may be any integer between 2 and 36, inclusive. In bases above 10, the letter 'A' (in either upper or lower case) represents 10, 'B' represents 11, and so forth, with 'Z' representing 35. If the string e is not a valid numeral in the given base, the function returns nil.
--]]
function tonumber( e, base ) end
--[[
Receives a value of any type and converts it to a string in a reasonable format. (For complete control of how numbers are converted, use string.format.)
If the metatable of v has a "__tostring" field, then tostring calls the corresponding value with v as argument, and uses the result of the call as its result.
--]]
function tostring( v ) end
--[[
A global variable (not a function) that holds a string containing the current interpreter version. The current contents of this variable is "Lua 5.2".
--]]
_VERSION = __std.String
--[[
This function is similar to pcall, except that it sets a new message handler msgh.
--]]
function xpcall( f, msgh, arg1, ... ) end
--[[
Returns the type of the variable var.
--]]
function type( var ) return __std.String end
--[[
Returns the environment of object o.
--]]
function getfenv( o ) end
--[[
Sets the environment of the given object to the given table. Returns object.
--]]
function setfenv( object, table ) end
| apache-2.0 |
rlcevg/Zero-K | LuaRules/Gadgets/weapon_timed_replace.lua | 7 | 3216 | function gadget:GetInfo()
return {
name = "Weapon Timed Replace",
desc = "Replaces a projectile with another projectile a certain time after firing.",
author = "Google Frog",
date = "10 June 2014",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true,
}
end
-------------------------------------------------------------
-------------------------------------------------------------
if not (gadgetHandler:IsSyncedCode()) then
return false
end
-------------------------------------------------------------
-------------------------------------------------------------
local devCompatibility = Spring.Utilities.IsCurrentVersionNewerThan(100, 0)
local FEATURE = 102
local UNIT = 117
local weaponLoseTrackingFrames = {}
local projectiles = {}
local projectileAllyTeam = {}
function gadget:Initialize()
weaponLoseTrackingFrames[WeaponDefNames["bomberdive_bombsabot"].id] = 14
Script.SetWatchWeapon(WeaponDefNames["bomberdive_bombsabot"].id, true)
end
function gadget:GameFrame(n)
for proID, frame in pairs(projectiles) do
if n == frame then
local targetType, targetID = Spring.GetProjectileTarget(proID)
if targetType == UNIT then
local allyTeam = projectileAllyTeam[proID]
los = Spring.GetUnitLosState(targetID,allyTeam,false)
if los and los.los then
-- If the unit is visible then target the ground beneath it.
local x,_,z = Spring.GetUnitPosition(targetID)
local y = Spring.GetGroundHeight(x,z)
Spring.SetProjectileTarget(proID, x, y, z)
else
-- If the unit is not visible we have been homing onto a radar
-- dot. The radar dot position is unknown to lua so target
-- ground beneath the projectile.
local x,_,z = Spring.GetProjectilePosition(proID)
local y = Spring.GetGroundHeight(x,z)
Spring.SetProjectileTarget(proID, x, y, z)
end
elseif targetType == FEATURE then
local x,_,z = Spring.GetFeaturePosition(targetID)
local y = Spring.GetGroundHeight(x,z)
Spring.SetProjectileTarget(proID, x, y, z)
end
projectiles[proID] = nil
projectileAllyTeam[proID] = nil
--local x, _, z = Spring.GetProjectilePosition(proID)
--[[local x, y, z = Spring.GetProjectilePosition(proID)
local vx, vy, vz = Spring.GetProjectileVelocity(proID)
-- Create new projectile
Spring.SpawnProjectile(data.replacement, {
pos = {x, y, z},
speed = {vx, vy, vz},
ttl = 180,
tracking = false
})
-- Destroy old projectile
if devCompatibility then
Spring.DeleteProjectile(proID)
else
Spring.SetProjectilePosition(proID,-100000,-100000,-100000)
Spring.SetProjectileCollision(proID)
end
--]]
end
end
end
function gadget:ProjectileCreated(proID, proOwnerID, weaponID)
if weaponLoseTrackingFrames[weaponID] then
local x, y, z = Spring.GetProjectilePosition(proID)
projectiles[proID] = Spring.GetGameFrame() + weaponLoseTrackingFrames[weaponID]
if proOwnerID then
projectileAllyTeam[proID] = Spring.GetUnitAllyTeam(proOwnerID)
end
end
end
function gadget:ProjectileDestroyed(proID)
if projectiles[proID] then
projectiles[proID] = nil
projectileAllyTeam[proID] = nil
end
end
| gpl-2.0 |
Jennal/cocos2dx-3.2-qt | cocos/scripting/lua-bindings/auto/api/ComAttribute.lua | 7 | 2283 |
--------------------------------
-- @module ComAttribute
-- @extend Component
-- @parent_module ccs
--------------------------------
-- @function [parent=#ComAttribute] getFloat
-- @param self
-- @param #string str
-- @param #float float
-- @return float#float ret (return value: float)
--------------------------------
-- @function [parent=#ComAttribute] getString
-- @param self
-- @param #string str
-- @param #string str
-- @return string#string ret (return value: string)
--------------------------------
-- @function [parent=#ComAttribute] setFloat
-- @param self
-- @param #string str
-- @param #float float
--------------------------------
-- @function [parent=#ComAttribute] setString
-- @param self
-- @param #string str
-- @param #string str
--------------------------------
-- @function [parent=#ComAttribute] getBool
-- @param self
-- @param #string str
-- @param #bool bool
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ComAttribute] setInt
-- @param self
-- @param #string str
-- @param #int int
--------------------------------
-- @function [parent=#ComAttribute] parse
-- @param self
-- @param #string str
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ComAttribute] getInt
-- @param self
-- @param #string str
-- @param #int int
-- @return int#int ret (return value: int)
--------------------------------
-- @function [parent=#ComAttribute] setBool
-- @param self
-- @param #string str
-- @param #bool bool
--------------------------------
-- @function [parent=#ComAttribute] create
-- @param self
-- @return ComAttribute#ComAttribute ret (return value: ccs.ComAttribute)
--------------------------------
-- @function [parent=#ComAttribute] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
-- @function [parent=#ComAttribute] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- @function [parent=#ComAttribute] serialize
-- @param self
-- @param #void void
-- @return bool#bool ret (return value: bool)
return nil
| mit |
rlcevg/Zero-K | units/armaak.lua | 2 | 6778 | unitDef = {
unitname = [[armaak]],
name = [[Archangel]],
description = [[Heavy Anti-Air Jumper]],
acceleration = 0.18,
brakeRate = 0.2,
buildCostEnergy = 550,
buildCostMetal = 550,
buildPic = [[ARMAAK.png]],
buildTime = 550,
canMove = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[30 48 30]],
collisionVolumeTest = 1,
collisionVolumeType = [[cylY]],
corpse = [[DEAD]],
customParams = {
canjump = 1,
jump_range = 400,
jump_speed = 6,
jump_reload = 10,
jump_from_midair = 0,
description_bp = [[Robô anti-ar pesado]],
description_de = [[Flugabwehr Springer]],
description_fi = [[Korkeatehoinen ilmatorjuntarobotti]],
description_fr = [[Marcheur Anti-Air Lourd]],
description_pl = [[Ciezki robot przeciwlotniczy (skacze)]],
helptext = [[The Archangel packs twin anti-air lasers and an autocannon for slaying enemy aircraft rapidly. It can also jump to quickly access high ground or to escape.]],
helptext_de = [[Der Archangel besitzt ein Doppel-Anti-Air-Laser und eine automatische Kanone, um gegnerische Lufteinheiten zu zerstören. Der Archangel kann auch einen Sprung machen.]],
helptext_bp = [[]],
helptext_fi = [[Archangel:in kaksoislaserit sek? automaattitykki tuhoavat vihollisen ilma-alukset tehokkaasti ja nopeasti.]],
helptext_fr = [[L'Archangel est munis d'un laser double anti air et d'un autocannon similaire au packo pour pouvoir an?antire les avions enemis.]],
helptext_pl = [[Archangel posiada silne dzialko i lasery przeciwlotnicze, ktore zadaja lotnictwu ogromne straty. Posiada takze mozliwosc skoku.]],
modelradius = [[15]],
},
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[jumpjetaa]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
mass = 236,
maxDamage = 1500,
maxSlope = 36,
maxVelocity = 2.017,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT2]],
moveState = 0,
noChaseCategory = [[TERRAFORM LAND SINK TURRET SHIP SATELLITE SWIM FLOAT SUB HOVER]],
objectName = [[hunchback.s3o]],
script = [[armaak.lua]],
seismicSignature = 4,
selfDestructAs = [[BIG_UNITEX]],
side = [[ARM]],
sightDistance = 660,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 28,
turnRate = 1400,
upright = true,
weapons = {
{
def = [[LASER]],
--badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[GUNSHIP FIXEDWING]],
},
{
def = [[EMG]],
--badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING GUNSHIP]],
},
},
weaponDefs = {
EMG = {
name = [[Anti-Air Autocannon]],
accuracy = 512,
alphaDecay = 0.7,
areaOfEffect = 8,
canattackground = false,
craterBoost = 0,
craterMult = 0,
cylinderTargeting = 1,
customParams = {
isaa = [[1]],
},
damage = {
default = 0.78,
planes = 7.8,
subs = 0.5,
},
explosionGenerator = [[custom:ARCHPLOSION]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
intensity = 0.8,
interceptedByShieldType = 1,
predictBoost = 1,
proximityPriority = 4,
range = 1040,
reloadtime = 0.1,
rgbColor = [[1 0.95 0.4]],
separation = 1.5,
soundStart = [[weapon/cannon/brawler_emg]],
stages = 10,
sweepfire = false,
tolerance = 8192,
turret = true,
weaponTimer = 1,
weaponType = [[Cannon]],
weaponVelocity = 1500,
},
LASER = {
name = [[Anti-Air Laser Battery]],
areaOfEffect = 12,
beamDecay = 0.736,
beamTime = 0.01,
beamttl = 15,
canattackground = false,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
cylinderTargeting = 1,
customParams = {
isaa = [[1]],
},
damage = {
default = 1.636,
planes = 16.36,
subs = 0.94,
},
explosionGenerator = [[custom:flash_teal7]],
fireStarter = 100,
impactOnly = true,
impulseFactor = 0,
interceptedByShieldType = 1,
laserFlareSize = 3.25,
minIntensity = 1,
noSelfDamage = true,
range = 820,
reloadtime = 0.1,
rgbColor = [[0 1 1]],
soundStart = [[weapon/laser/rapid_laser]],
soundStartVolume = 4,
thickness = 2.165,
tolerance = 8192,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2200,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Archangel]],
blocking = true,
damage = 1500,
energy = 0,
featureDead = [[HEAP]],
footprintX = 4,
footprintZ = 4,
height = [[15]],
hitdensity = [[100]],
metal = 220,
object = [[hunchback_dead.s3o]],
reclaimable = true,
reclaimTime = 220,
},
HEAP = {
description = [[Debris - Archangel]],
blocking = false,
damage = 1500,
energy = 0,
footprintX = 4,
footprintZ = 4,
height = [[4]],
hitdensity = [[100]],
metal = 110,
object = [[debris4x4c.s3o]],
reclaimable = true,
reclaimTime = 110,
},
},
}
return lowerkeys({ armaak = unitDef })
| gpl-2.0 |
ViolyS/RayUI_VS | Interface/AddOns/Skada/modules/Enemies.lua | 1 | 12234 | Skada:AddLoadableModule("Enemies", nil, function(Skada, L)
if Skada.db.profile.modulesBlocked.Enemies then return end
local done = Skada:NewModule(L["Enemy damage done"])
local taken = Skada:NewModule(L["Enemy damage taken"])
local hdone = Skada:NewModule(L["Enemy healing done"])
local htaken = Skada:NewModule(L["Enemy healing taken"])
local hdonespells = Skada:NewModule(L["Enemy healing done"]..": "..L["Healing spell list"])
local htakenspells = Skada:NewModule(L["Enemy healing taken"]..": "..L["Healing spell list"])
local doneplayers = Skada:NewModule(L["Damage done per player"])
local takenplayers = Skada:NewModule(L["Damage taken per player"])
local function find_player(mob, name)
local player = mob.players[name]
if player then return player end
local _, playerClass = UnitClass(name)
local playerRole = UnitGroupRolesAssigned(name)
player = {done = 0, taken = 0, class = playerClass, role = playerRole}
mob.players[name] = player
return player
end
local function find_mob(set, name)
local mob = set.mobs[name]
if mob then return mob end
mob = {taken = 0, done = 0, players = {}, htaken = 0, hdone = 0, hdonespell = {}, htakenspell = {}}
set.mobs[name] = mob
return mob
end
local function log_damage_taken(set, dmg)
set.mobtaken = set.mobtaken + dmg.amount
local mob = find_mob(set,dmg.dstName)
mob.taken = mob.taken + dmg.amount
local player = find_player(mob, dmg.srcName)
player.taken = player.taken + dmg.amount
end
local function log_damage_done(set, dmg)
set.mobdone = set.mobdone + dmg.amount
local mob = find_mob(set,dmg.srcName)
mob.done = mob.done + dmg.amount
local player = find_player(mob, dmg.dstName)
player.done = player.done + dmg.amount
end
local function log_healspell(mob, entry, spellname, healing, overheal, crit)
local spell = mob[entry][spellname] or { hits = 0, crits = 0, healing = 0, overhealing = 0, min = nil, max = 0}
mob[entry][spellname] = spell
spell.hits = spell.hits + 1
if crit then
spell.crits = spell.crits + 1
end
spell.healing = spell.healing + healing
spell.overhealing = spell.overhealing + overheal
if not spell.min or healing < spell.min then
spell.min = healing
end
if not spell.max or healing > spell.max then
spell.max = healing
end
end
local function log_healing(set, dmg, ...)
local spellid, spellname,_,amount,overheal,absorb,crit = ...
local healing = math.max(0,amount - overheal) -- omit absorbs, which players inflict to mitigate healing
set.mobhdone = set.mobhdone + healing
if dmg.srcName then -- some enemy HoT's omit the true src (eg Cauterizing Bolt)
local smob = find_mob(set,dmg.srcName)
smob.hdone = smob.hdone + healing
log_healspell(smob, "hdonespell", spellname, healing, overheal, crit)
end
local dmob = find_mob(set,dmg.dstName)
dmob.htaken = dmob.htaken + healing
log_healspell(dmob, "htakenspell", spellname, healing, overheal, crit)
end
local dmg = {}
local function Healing(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
if dstName then -- we allow missing src (for some enemy HoTs)
dmg.dstName = dstName
dmg.srcName = srcName
log_healing(Skada.current, dmg, ...)
log_healing(Skada.total, dmg, ...)
end
end
local function SpellDamageTaken(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, spellId, spellName, spellSchool, amount)
if srcName and dstName then
srcGUID, srcName = Skada:FixMyPets(srcGUID, srcName)
dmg.dstName = dstName
dmg.srcName = srcName
dmg.amount = amount
log_damage_taken(Skada.current, dmg)
log_damage_taken(Skada.total, dmg)
end
end
local function SpellDamageDone(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, spellId, spellName, spellSchool, amount)
if srcName and dstName then
dmg.dstName = dstName
dmg.srcName = srcName
dmg.amount = amount
log_damage_done(Skada.current, dmg)
log_damage_done(Skada.total, dmg)
end
end
local function SwingDamageTaken(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, amount)
if srcName and dstName then
srcGUID, srcName = Skada:FixMyPets(srcGUID, srcName)
dmg.dstName = dstName
dmg.srcName = srcName
dmg.amount = amount
log_damage_taken(Skada.current, dmg)
log_damage_taken(Skada.total, dmg)
end
end
local function SwingDamageDone(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, amount)
if srcName and dstName then
dmg.dstName = dstName
dmg.srcName = srcName
dmg.amount = amount
log_damage_done(Skada.current, dmg)
log_damage_done(Skada.total, dmg)
end
end
-- Factored code for Enemy stat page - list mobs.
local function MobUpdate(stat)
return function (self, win, set)
local nr = 1
local max = 0
for name, mob in pairs(set.mobs) do
if (mob[stat] or 0) > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.value = mob[stat]
d.id = name
d.valuetext = Skada:FormatNumber(mob[stat])
d.label = name
if mob[stat] > max then
max = mob[stat]
end
nr = nr + 1
end
end
win.metadata.maxvalue = max
end
end
taken.Update = MobUpdate("taken")
done.Update = MobUpdate("done")
htaken.Update = MobUpdate("htaken")
hdone.Update = MobUpdate("hdone")
function doneplayers:Enter(win, id, label)
doneplayers.title = L["Damage from"].." "..label
doneplayers.mob = label
end
function doneplayers:Update(win, set)
local mob = self.mob and set.mobs[self.mob]
if mob then
local nr = 1
local max = 0
for name, player in pairs(mob.players) do
if player.done > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = name
d.label = name
d.value = player.done
d.valuetext = Skada:FormatNumber(player.done)..(" (%02.1f%%)"):format(player.done / mob.done * 100)
d.class = player.class
d.role = player.role
if player.done > max then
max = player.done
end
nr = nr + 1
end
end
win.metadata.maxvalue = max
end
end
function takenplayers:Enter(win, id, label)
takenplayers.title = L["Damage on"].." "..label
takenplayers.mob = label
end
function takenplayers:Update(win, set)
local mob = self.mob and set.mobs[self.mob]
if mob then
local nr = 1
local max = 0
for name, player in pairs(mob.players) do
if player.taken > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = name
d.label = name
d.value = player.taken
d.valuetext = Skada:FormatNumber(player.taken)..(" (%02.1f%%)"):format(player.taken / mob.taken * 100)
d.class = player.class
d.role = player.role
if player.taken > max then
max = player.taken
end
nr = nr + 1
end
end
win.metadata.maxvalue = max
end
end
local ttmob, ttentry
function hdonespells:Enter(win, id, label)
self.title = L["Enemy healing done"]..": "..label
self.mob = label
ttmob = label
ttentry = "hdonespell"
end
function htakenspells:Enter(win, id, label)
self.title = L["Enemy healing taken"]..": "..label
self.mob = label
ttmob = label
ttentry = "htakenspell"
end
local function SpellUpdate(entry)
return function (self, win, set)
local mob = self.mob and set.mobs[self.mob]
if mob then
local nr = 1
local max = 0
for name, info in pairs(mob[entry]) do
if info.hits > 0 then
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = name
d.label = name
d.value = info.healing
d.valuetext = Skada:FormatNumber(info.healing)..(" (%02.1f%%)"):format(info.healing / mob.hdone * 100)
if info.healing > max then
max = info.healing
end
nr = nr + 1
end
end
win.metadata.maxvalue = max
end
end
end
hdonespells.Update = SpellUpdate("hdonespell")
htakenspells.Update = SpellUpdate("htakenspell")
local function spell_tooltip(win, id, label, tooltip)
local mob = find_mob(win:get_selected_set(), ttmob)
if mob and ttentry then
local spell = mob[ttentry][label]
if spell and (spell.hits or 0) > 0 then
tooltip:AddLine(ttmob.." - "..label)
tooltip:AddDoubleLine(L["Hit"]..":", spell.hits, 255,255,255,255,255,255)
if spell.max and spell.min then
tooltip:AddDoubleLine(L["Minimum hit:"], Skada:FormatNumber(spell.min), 255,255,255,255,255,255)
tooltip:AddDoubleLine(L["Maximum hit:"], Skada:FormatNumber(spell.max), 255,255,255,255,255,255)
end
tooltip:AddDoubleLine(L["Average hit:"], Skada:FormatNumber(spell.healing / spell.hits), 255,255,255,255,255,255)
tooltip:AddDoubleLine(L["Critical"]..":", ("%02.1f%%"):format(spell.crits / spell.hits * 100), 255,255,255,255,255,255)
tooltip:AddDoubleLine(L["Overhealing"]..":", ("%02.1f%%"):format(spell.overhealing / (spell.overhealing + spell.healing) * 100), 255,255,255,255,255,255)
end
end
end
function done:OnEnable()
takenplayers.metadata = {showspots = true}
doneplayers.metadata = {showspots = true}
done.metadata = {click1 = doneplayers, icon = "Interface\\Icons\\Inv_misc_monsterclaw_01"}
taken.metadata = {click1 = takenplayers, icon = "Interface\\Icons\\Inv_shield_08"}
Skada:RegisterForCL(SpellDamageTaken, 'SPELL_DAMAGE', {src_is_interesting = true, dst_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageTaken, 'SPELL_PERIODIC_DAMAGE', {src_is_interesting = true, dst_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageTaken, 'SPELL_BUILDING_DAMAGE', {src_is_interesting = true, dst_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageTaken, 'RANGE_DAMAGE', {src_is_interesting = true, dst_is_not_interesting = true})
Skada:RegisterForCL(SwingDamageTaken, 'SWING_DAMAGE', {src_is_interesting = true, dst_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageDone, 'SPELL_DAMAGE', {dst_is_interesting_nopets = true, src_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageDone, 'SPELL_PERIODIC_DAMAGE', {dst_is_interesting_nopets = true, src_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageDone, 'SPELL_BUILDING_DAMAGE', {dst_is_interesting_nopets = true, src_is_not_interesting = true})
Skada:RegisterForCL(SpellDamageDone, 'RANGE_DAMAGE', {dst_is_interesting_nopets = true, src_is_not_interesting = true})
Skada:RegisterForCL(SwingDamageDone, 'SWING_DAMAGE', {dst_is_interesting_nopets = true, src_is_not_interesting = true})
Skada:AddMode(self, L["Damage"])
end
function done:OnDisable()
Skada:RemoveMode(self)
end
function taken:OnEnable()
Skada:AddMode(self, L["Damage"])
end
function taken:OnDisable()
Skada:RemoveMode(self)
end
function hdone:OnEnable()
hdonespells.metadata = {showspots = true, tooltip = spell_tooltip}
htakenspells.metadata = {showspots = true, tooltip = spell_tooltip}
hdone.metadata = {click1 = hdonespells, icon = "Interface\\Icons\\Inv_misc_bandage_12"}
htaken.metadata = {click1 = htakenspells, icon = "Interface\\Icons\\Spell_misc_emotionhappy"}
Skada:RegisterForCL(Healing, 'SPELL_HEAL', {dst_is_not_interesting = true})
Skada:RegisterForCL(Healing, 'SPELL_PERIODIC_HEAL', {dst_is_not_interesting = true})
Skada:RegisterForCL(Healing, 'SPELL_BUILDING_HEAL', {dst_is_not_interesting = true})
Skada:AddMode(self, L["Healing"])
end
function hdone:OnDisable()
Skada:RemoveMode(self)
end
function htaken:OnEnable()
Skada:AddMode(self, L["Healing"])
end
function htaken:OnDisable()
Skada:RemoveMode(self)
end
function done:GetSetSummary(set)
return Skada:FormatNumber(set.mobdone)
end
function taken:GetSetSummary(set)
return Skada:FormatNumber(set.mobtaken)
end
function hdone:GetSetSummary(set)
return Skada:FormatNumber(set.mobhdone)
end
function htaken:GetSetSummary(set)
return Skada:FormatNumber(set.mobhdone)
end
-- Called by Skada when a new set is created.
function done:AddSetAttributes(set)
if not set.mobs then
set.mobs = {}
set.mobdone = 0
set.mobtaken = 0
end
if not set.mobhdone then
set.mobhdone = 0
end
end
end)
| mit |
SneakyB/iceball | pkg/iceball/pmfedit/main_client.lua | 4 | 7945 | --[[
This file is part of Ice Lua Components.
Ice Lua Components is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Lua Components is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>.
]]
dofile("pkg/base/preconf.lua")
dofile("pkg/base/lib_gui.lua")
dofile("pkg/base/lib_pmf.lua")
dofile("pkg/base/lib_sdlkey.lua")
preload = ...
PMFEDIT_FNAME = "clsave/vol/editor.pmf"
BTSK_PMF_MOVEXN = SDLK_l
BTSK_PMF_MOVEXP = SDLK_j
BTSK_PMF_MOVEYN = SDLK_i
BTSK_PMF_MOVEYP = SDLK_k
BTSK_PMF_MOVEZN = SDLK_u
BTSK_PMF_MOVEZP = SDLK_o
BTSK_PMF_SIZEP = SDLK_EQUALS
BTSK_PMF_SIZEN = SDLK_MINUS
BTSK_PMF_ROTYN = SDLK_a
BTSK_PMF_ROTYP = SDLK_d
BTSK_PMF_ROTXN = SDLK_w
BTSK_PMF_ROTXP = SDLK_s
BTSK_PMF_ROTY2N = SDLK_q
BTSK_PMF_ROTY2P = SDLK_e
BTSK_QUIT = SDLK_ESCAPE
BTSK_COLORLEFT = SDLK_LEFT
BTSK_COLORRIGHT = SDLK_RIGHT
BTSK_COLORUP = SDLK_UP
BTSK_COLORDOWN = SDLK_DOWN
BTSK_PMF_BLKSET = SDLK_g
BTSK_PMF_BLKCLEAR = SDLK_b
BTSK_PMF_QUICKLOAD = SDLK_F3
BTSK_PMF_QUICKSAVE = SDLK_F10
pmfedit_x = 0
pmfedit_y = 0
pmfedit_z = 0
pmfedit_size = 16
pmfedit_data = {}
pmfedit_model = common.model_new(1)
pmfedit_idx = 1
pmfedit_model_bone = {}
pmfedit_model, pmfedit_model_bone[pmfedit_idx] = common.model_bone_new(pmfedit_model)
pmfedit_data[#pmfedit_data+1] = {x=0,y=0,z=0,r=0,g=0,b=0,radius=1}
pmfedit_ry = 0
pmfedit_rx = 0
pmfedit_ry2 = 0
blk_color = {128,128,128}
blk_color_x = 3
blk_color_y = 0
cpalette_base = {
0x7F,0x7F,0x7F,
0xFF,0x00,0x00,
0xFF,0x7F,0x00,
0xFF,0xFF,0x00,
0x00,0xFF,0x00,
0x00,0xFF,0xFF,
0x00,0x00,0xFF,
0xFF,0x00,0xFF,
}
cpalette = {}
do
local i,j
for i=0,7 do
local r,g,b
r = cpalette_base[i*3+1]
g = cpalette_base[i*3+2]
b = cpalette_base[i*3+3]
for j=0,3 do
local cr = math.floor((r*j)/3)
local cg = math.floor((g*j)/3)
local cb = math.floor((b*j)/3)
cpalette[#cpalette+1] = {cr,cg,cb}
end
for j=1,4 do
local cr = r + math.floor(((255-r)*j)/4)
local cg = g + math.floor(((255-g)*j)/4)
local cb = b + math.floor(((255-b)*j)/4)
cpalette[#cpalette+1] = {cr,cg,cb}
end
end
end
function client.hook_tick(sec_current, sec_delta)
blk_color = cpalette[(blk_color_y*8)+blk_color_x+1]
pmfedit_data[#pmfedit_data] = {
x=pmfedit_x,y=pmfedit_y,z=pmfedit_z-0.01,
r=math.sin(sec_current-2*math.pi/3)*127+128,
g=math.sin(sec_current)*127+128,
b=math.sin(sec_current+2*math.pi/3)*127+128,
radius=pmfedit_size}
common.model_bone_set(pmfedit_model, pmfedit_model_bone[pmfedit_idx], "edit", pmfedit_data)
return 0.005
end
function client.hook_key(key, state)
if state then
if key == BTSK_PMF_MOVEXN then
pmfedit_x = pmfedit_x - pmfedit_size
elseif key == BTSK_PMF_MOVEXP then
pmfedit_x = pmfedit_x + pmfedit_size
elseif key == BTSK_PMF_MOVEYN then
pmfedit_y = pmfedit_y - pmfedit_size
elseif key == BTSK_PMF_MOVEYP then
pmfedit_y = pmfedit_y + pmfedit_size
elseif key == BTSK_PMF_MOVEZN then
pmfedit_z = pmfedit_z - pmfedit_size
elseif key == BTSK_PMF_MOVEZP then
pmfedit_z = pmfedit_z + pmfedit_size
elseif key == BTSK_PMF_SIZEN and pmfedit_size > 1 then
pmfedit_size = pmfedit_size - 1
elseif key == BTSK_PMF_SIZEP and pmfedit_size < 65535 then
pmfedit_size = pmfedit_size + 1
elseif key == BTSK_COLORLEFT then
blk_color_x = blk_color_x - 1
if blk_color_x < 0 then
blk_color_x = 7
end
blk_color = cpalette[blk_color_x+blk_color_y*8+1]
elseif key == BTSK_COLORRIGHT then
blk_color_x = blk_color_x + 1
if blk_color_x > 7 then
blk_color_x = 0
end
blk_color = cpalette[blk_color_x+blk_color_y*8+1]
elseif key == BTSK_COLORUP then
blk_color_y = blk_color_y - 1
if blk_color_y < 0 then
blk_color_y = 7
end
blk_color = cpalette[blk_color_x+blk_color_y*8+1]
elseif key == BTSK_COLORDOWN then
blk_color_y = blk_color_y + 1
if blk_color_y > 7 then
blk_color_y = 0
end
blk_color = cpalette[blk_color_x+blk_color_y*8+1]
elseif key == BTSK_PMF_ROTYN then
pmfedit_ry = pmfedit_ry + math.pi/16
elseif key == BTSK_PMF_ROTYP then
pmfedit_ry = pmfedit_ry - math.pi/16
elseif key == BTSK_PMF_ROTXN then
pmfedit_rx = pmfedit_rx + math.pi/16
elseif key == BTSK_PMF_ROTXP then
pmfedit_rx = pmfedit_rx - math.pi/16
elseif key == BTSK_PMF_ROTY2N then
pmfedit_ry2 = pmfedit_ry2 + math.pi/16
elseif key == BTSK_PMF_ROTY2P then
pmfedit_ry2 = pmfedit_ry2 - math.pi/16
elseif key == BTSK_QUIT then
client.hook_tick = nil
elseif key == BTSK_PMF_BLKSET and #pmfedit_data < 4095 then
pmfedit_data[#pmfedit_data].r = blk_color[1]
pmfedit_data[#pmfedit_data].g = blk_color[2]
pmfedit_data[#pmfedit_data].b = blk_color[3]
pmfedit_data[#pmfedit_data+1] = pmfedit_data[#pmfedit_data]
elseif key == BTSK_PMF_BLKCLEAR then
if #pmfedit_data > 1 then
local i
local dx,dy,dz
local d
local mi,md
mi = 1
md = nil
-- find nearest piece
for i=1,#pmfedit_data-1 do
dx = pmfedit_data[i].x - pmfedit_x
dy = pmfedit_data[i].y - pmfedit_y
dz = pmfedit_data[i].z - pmfedit_z
d = dx*dx+dy*dy+dz*dz
if md == nil or d < md then
md = d
mi = i
end
end
-- delete it and move to it
pmfedit_x = pmfedit_data[mi].x
pmfedit_y = pmfedit_data[mi].y
pmfedit_z = pmfedit_data[mi].z
pmfedit_size = pmfedit_data[mi].radius
for i=mi,#pmfedit_data-1 do
pmfedit_data[i] = pmfedit_data[i+1]
end
pmfedit_data[#pmfedit_data] = nil
end
elseif key == BTSK_PMF_QUICKLOAD then
local xpmf = common.model_load_pmf(PMFEDIT_FNAME)
if xpmf then
common.model_free(pmfedit_model) -- YECCH! Forgot this line!
pmfedit_model = xpmf
pmfedit_model_bone[pmfedit_idx] = 0
local bname
bname, pmfedit_data = common.model_bone_get(pmfedit_model, pmfedit_model_bone[pmfedit_idx])
pmfedit_data[#pmfedit_data+1] = {}
print("loaded!")
else
print("error during loading - NOT LOADED")
end
elseif key == BTSK_PMF_QUICKSAVE then
local xpt = pmfedit_data[#pmfedit_data]
pmfedit_data[#pmfedit_data] = nil
local bname, blah
bname, blah = common.model_bone_get(pmfedit_model, pmfedit_model_bone[pmfedit_idx])
common.model_bone_set(pmfedit_model, pmfedit_model_bone[pmfedit_idx], bname, pmfedit_data)
if common.model_save_pmf(pmfedit_model, PMFEDIT_FNAME) then
print("saved!")
else
print("error during saving - NOT SAVED")
end
pmfedit_data[#pmfedit_data+1] = xpt
end
end
end
function client.hook_render()
local c = 0xFF000000+256*(256*blk_color[1]+blk_color[2])+blk_color[3]
font_mini.print(4,40,c,string.format(
"PMF - size: %-6i x: %-6i y: %6i z: %-6i - COUNT: %6i / rot: %3f, %3f, %3f"
,pmfedit_size
,pmfedit_x
,pmfedit_y
,pmfedit_z
,#pmfedit_data-1
,pmfedit_ry
,pmfedit_rx
,pmfedit_ry2))
client.model_render_bone_local(pmfedit_model, pmfedit_model_bone[pmfedit_idx],
0,0,1,
pmfedit_ry,pmfedit_rx,pmfedit_ry2,
0.7)
end
if preload then
local xpmf = common.model_load_pmf(preload)
if xpmf then
common.model_free(pmfedit_model) -- YECCH! Forgot this line!
pmfedit_model = xpmf
pmfedit_model_bone[pmfedit_idx] = 0
local bname
bname, pmfedit_data = common.model_bone_get(pmfedit_model, pmfedit_model_bone[pmfedit_idx])
pmfedit_data[#pmfedit_data+1] = {}
print("loaded!")
else
print("error during loading - NOT LOADED")
end
end
client.map_fog_set(32, 32, 32, 60)
print("pmfedit successfully loaded!")
| gpl-3.0 |
ikstream/Minstrel-Blues | measurement/minstrel-measurement/tests/tshark.lua | 2 | 1753 | require ('misc')
local tshark_bin = "/usr/bin/tshark"
--local fname = "/home/denis/data-udp-07.04.2017-HT40-40-far-all.bak/tp4300/tp4300-14-4-10-10M-1.pcap"
--local fname = "/home/denis/data-udp-27.04.2017-C13-HT20-noani-ldpc/tp3600/tp3600-7-10-d10-10M-1.pcap"
local fname = "/home/denis/data-udp-27.04.2017-C13-HT20-ani-noldpc/tp3600/tp3600-7-10-d10-10M-1.pcap"
local mac = "64:70:02:aa:b8:df"
local macs = {}
macs [1] = "f4:f2:6d:22:7c:f0"
local filter = ""
--filter = filter .. "wlan.fc.type==2"
if ( macs ~= nil and macs ~= {} ) then
-- filter = filter .. " and ( ( ( "
filter = filter .. " ( ( ( "
end
for i, mac in ipairs ( macs ) do
if ( i ~= 1 ) then filter = filter .. " or " end
filter = filter .. "wlan.ra==" .. mac
end
if ( macs ~= nil and macs ~= {} ) then
filter = filter .. " ) "
end
filter = filter .. "and wlan.ta==" .. mac
filter = filter .. " ) or ( "
filter = filter .. "wlan.ra==" .. mac
if ( macs ~= nil and macs ~= {} ) then
filter = filter .. " and ( "
end
for i, mac in ipairs ( macs ) do
if ( i ~= 1 ) then filter = filter .. " or " end
filter = filter .. "wlan.ta==" .. mac
end
if ( macs ~= nil and macs ~= {} ) then
filter = filter .. " ) ) )"
end
filter = filter .. ""
print ( tshark_bin .. " -r " .. fname .. " -Y " .. filter .. " -T " .. "fields"
.. " -e " .. "radiotap.dbm_antsignal" )
print ()
local content, exit_code = Misc.execute_nonblock ( nil, nil, tshark_bin, "-r", fname, "-Y", filter, "-T", "fields"
, "-e", "radiotap.dbm_antsignal", "-e", "wlan.fc.type", "-e", "wlan.fc.type_subtype"
, "-e", "wlan_radio.data_rate")
print ( exit_code )
print ( "content: " .. ( content or "none" ) )
| gpl-2.0 |
SonyWWS/SLED | src/sledluaplugin/libsce_sledluaplugin-5.1.4.lua | 1 | 1209 | -- Copyright (C) Sony Computer Entertainment America LLC.
-- All Rights Reserved.
--
-- Dependencies
--
include "../../wws_lua/lua-5.1.4/src/lua-5.1.4.lua"
--
-- Premake build script for the libsce_sledluaplugin-5.1.4 library
--
sdk_project "libsce_sledluaplugin-5.1.4"
sdk_location "."
sdk_kind "Library"
targetname "sce_sledluaplugin-5.1.4"
configurations { sdk.DEBUG, sdk.RELEASE }
platforms { sdk.WIN_STATIC_ALL }
uuid "C3E72BF5-432B-460B-AC15-1EB234123416"
files {
"errorcodes.h",
"luautils.h",
"luautils_5.1.4.cpp",
"luautils_common.cpp",
"luavariable.h",
"params.h",
"profilestack.*",
"scmp.*",
"sledluaplugin.*",
"sledluaplugin_class.cpp",
"sledluaplugin_class.h",
"sledluaplugin_class_5.1.4.cpp",
"varfilter.*",
"../sledcore/*.h",
"../sledcore/windows/*.h"
}
vpaths { ["Headers"] = {"*.h"} }
vpaths { ["Source/*"] = {"**.h", "**.cpp"} }
includedirs { "../../", "../../../" }
objdir(path.join(sdk.rootdir, "tmp/sce_sled/%{prj.name}/%{sdk.platform(cfg)}"))
defines { "SCE_LUA_VER=514", "WWS_LUA_VER=514" }
configuration { "Debug*" }
defines { "SCE_SLED_ASSERT_ENABLED=1" }
configuration { "Win*" }
linkoptions { "/ignore:4221" }
| apache-2.0 |
rlcevg/Zero-K | LuaRules/Gadgets/CustomUnitShaders/UnitMaterials/1_normalmapping.lua | 17 | 4460 | -- $Id$
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local materials = {
normalMappedS3o = {
shaderDefinitions = {
"#define use_perspective_correct_shadows",
"#define use_normalmapping",
--"#define flip_normalmap",
},
shader = include(GADGET_DIR .. "UnitMaterials/Shaders/default.lua"),
usecamera = false,
culling = GL.BACK,
predl = nil,
postdl = nil,
texunits = {
[0] = '%%UNITDEFID:0',
[1] = '%%UNITDEFID:1',
[2] = '$shadow',
[3] = '$specular',
[4] = '$reflection',
[5] = '%NORMALTEX',
},
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Automated normalmap detection
local unitMaterials = {}
local function FindNormalmap(tex1, tex2)
local normaltex
--// check if there is a corresponding _normals.dds file
if (VFS.FileExists(tex1)) then
local basefilename = tex1:gsub("%....","")
if (tonumber(basefilename:sub(-1,-1))) then
basefilename = basefilename:sub(1,-2)
end
if (basefilename:sub(-1,-1) == "_") then
basefilename = basefilename:sub(1,-2)
end
normaltex = basefilename .. "_normals.dds"
if (not VFS.FileExists(normaltex)) then
normaltex = nil
end
end --if FileExists
if (not normaltex) and tex2 and (VFS.FileExists(tex2)) then
local basefilename = tex2:gsub("%....","")
if (tonumber(basefilename:sub(-1,-1))) then
basefilename = basefilename:sub(1,-2)
end
if (basefilename:sub(-1,-1) == "_") then
basefilename = basefilename:sub(1,-2)
end
normaltex = basefilename .. "_normals.dds"
if (not VFS.FileExists(normaltex)) then
normaltex = nil
end
end
return normaltex
end
for i=1,#UnitDefs do
local udef = UnitDefs[i]
if (udef.customParams.normaltex and VFS.FileExists(udef.customParams.normaltex)) then
unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = udef.customParams.normaltex}
elseif (udef.model.type == "s3o") then
local modelpath = udef.model.path
if (modelpath) then
--// udef.model.textures is empty at gamestart, so read the texture filenames from the s3o directly
local rawstr = VFS.LoadFile(modelpath)
local header = rawstr:sub(1,60)
local texPtrs = VFS.UnpackU32(header, 45, 2)
local tex1,tex2
if (texPtrs[2] > 0)
then tex2 = "unittextures/" .. rawstr:sub(texPtrs[2]+1, rawstr:len()-1)
else texPtrs[2] = rawstr:len() end
if (texPtrs[1] > 0)
then tex1 = "unittextures/" .. rawstr:sub(texPtrs[1]+1, texPtrs[2]-1) end
-- output units without tex2
if not tex2 then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, "CustomUnitShaders: " .. udef.name .. " no tex2")
end
local normaltex = FindNormalmap(tex1,tex2)
if (normaltex and not unitMaterials[udef.name]) then
unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = normaltex}
end
end --if model
elseif (udef.model.type == "obj") then
local modelinfopath = udef.model.path
if (modelinfopath) then
modelinfopath = modelinfopath .. ".lua"
if (VFS.FileExists(modelinfopath)) then
local infoTbl = Include(modelinfopath)
if (infoTbl) then
local tex1 = "unittextures/" .. (infoTbl.tex1 or "")
local tex2 = "unittextures/" .. (infoTbl.tex2 or "")
-- output units without tex2
if not tex2 then
Spring.Log(gadget:GetInfo().name, LOG.WARNING, "CustomUnitShaders: " .. udef.name .. " no tex2")
end
local normaltex = FindNormalmap(tex1,tex2)
if (normaltex and not unitMaterials[udef.name]) then
unitMaterials[udef.name] = {"normalMappedS3o", NORMALTEX = normaltex}
end
end
end
end
end --elseif
end --for
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
return materials, unitMaterials
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
EliHar/Pattern_recognition | torch1/extra/cudnn/SpatialSoftMax.lua | 1 | 3323 | local SpatialSoftMax, parent = torch.class('cudnn.SpatialSoftMax', 'nn.Module')
local errcheck = cudnn.errcheck
function SpatialSoftMax:__init(fast)
parent.__init(self)
if fast then
self.algorithm = 'CUDNN_SOFTMAX_FAST'
else
self.algorithm = 'CUDNN_SOFTMAX_ACCURATE'
end
end
function SpatialSoftMax:createIODescriptors(input)
self.mode = self.mode or 'CUDNN_SOFTMAX_MODE_CHANNEL'
-- after converting from nn use accurate
self.algorithm = self.algorithm or 'CUDNN_SOFTMAX_ACCURATE'
self.iSize = self.iSize or torch.LongStorage(4):fill(0)
local batch = true
local singleDim = false
if input:dim() == 1 then
singleDim = true
batch = false
input = input:view(1, input:size(1), 1, 1)
elseif input:dim() == 2 then
singleDim = true
input = input:view(input:size(1), input:size(2), 1, 1)
elseif input:dim() == 3 then
input = input:view(1, input:size(1), input:size(2), input:size(3))
batch = false
end
assert(input:dim() == 4 and input:isContiguous());
if not self.iDesc or not self.oDesc or
input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4] then
self.iSize = input:size()
self.output:resizeAs(input)
self.iDesc = cudnn.toDescriptor(input)
self.oDesc = cudnn.toDescriptor(self.output)
if not singleDim and not batch then
self.output = self.output:view(self.output:size(2),
self.output:size(3),
self.output:size(4))
elseif singleDim and not batch then
self.output = self.output:view(self.output:size(2))
elseif singleDim and batch then
self.output = self.output:view(self.output:size(1), self.output:size(2))
end
end
end
local one = torch.FloatTensor({1});
local zero = torch.FloatTensor({0});
function SpatialSoftMax:updateOutput(input)
self:createIODescriptors(input)
errcheck('cudnnSoftmaxForward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.iDesc[0], input:data(),
zero:data(),
self.oDesc[0], self.output:data());
return self.output
end
function SpatialSoftMax:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
self:createIODescriptors(input)
errcheck('cudnnSoftmaxBackward',
cudnn.getHandle(),
self.algorithm, self.mode,
one:data(),
self.oDesc[0], self.output:data(),
self.oDesc[0], gradOutput:data(),
zero:data(),
self.iDesc[0], self.gradInput:data());
return self.gradInput
end
function SpatialSoftMax:clearDesc()
self.iDesc = nil
self.oDesc = nil
end
function SpatialSoftMax:write(f)
self:clearDesc()
local var = {}
for k,v in pairs(self) do
var[k] = v
end
f:writeObject(var)
end
function SpatialSoftMax:clearState()
self:clearDesc()
nn.utils.clear(self, '_gradOutput')
return parent.clearState(self)
end
| mit |
EliHar/Pattern_recognition | torch1/install/share/lua/5.1/optim/adadelta.lua | 6 | 2125 | --[[ ADADELTA implementation for SGD http://arxiv.org/abs/1212.5701
ARGS:
- `opfunc` : a function that takes a single input (X), the point of
evaluation, and returns f(X) and df/dX
- `x` : the initial point
- `config` : a table of hyper-parameters
- `config.rho` : interpolation parameter
- `config.eps` : for numerical stability
- `config.weightDecay` : weight decay
- `state` : a table describing the state of the optimizer; after each
call the state is modified
- `state.paramVariance` : vector of temporal variances of parameters
- `state.accDelta` : vector of accummulated delta of gradients
RETURN:
- `x` : the new x vector
- `f(x)` : the function, evaluated before the update
]]
function optim.adadelta(opfunc, x, config, state)
-- (0) get/update state
if config == nil and state == nil then
print('no state table, ADADELTA initializing')
end
local config = config or {}
local state = state or config
local rho = config.rho or 0.9
local eps = config.eps or 1e-6
local wd = config.weightDecay or 0
state.evalCounter = state.evalCounter or 0
-- (1) evaluate f(x) and df/dx
local fx,dfdx = opfunc(x)
-- (2) weight decay
if wd ~= 0 then
dfdx:add(wd, x)
end
-- (3) parameter update
if not state.paramVariance then
state.paramVariance = torch.Tensor():typeAs(x):resizeAs(dfdx):zero()
state.paramStd = torch.Tensor():typeAs(x):resizeAs(dfdx):zero()
state.delta = torch.Tensor():typeAs(x):resizeAs(dfdx):zero()
state.accDelta = torch.Tensor():typeAs(x):resizeAs(dfdx):zero()
end
state.paramVariance:mul(rho):addcmul(1-rho,dfdx,dfdx)
state.paramStd:resizeAs(state.paramVariance):copy(state.paramVariance):add(eps):sqrt()
state.delta:resizeAs(state.paramVariance):copy(state.accDelta):add(eps):sqrt():cdiv(state.paramStd):cmul(dfdx)
x:add(-1, state.delta)
state.accDelta:mul(rho):addcmul(1-rho, state.delta, state.delta)
-- (4) update evaluation counter
state.evalCounter = state.evalCounter + 1
-- return x*, f(x) before optimization
return x,{fx}
end
| mit |
Satoshi-t/Re-SBS | lua/ai/bgm-ai.lua | 1 | 46165 | sgs.ai_skill_invoke.chongzhen = function(self, data)
local target = data:toPlayer()
if self:isFriend(target) then
if hasManjuanEffect(self.player) then return false end
if self:needKongcheng(target) and target:getHandcardNum() == 1 then return true end
if self:getOverflow(target) > 2 then return true end
return false
else
return not (self:needKongcheng(target) and target:getHandcardNum() == 1)
end
end
sgs.ai_choicemade_filter.skillInvoke.chongzhen = function(self, player, promptlist)
local target
for _, p in sgs.qlist(self.room:getOtherPlayers(player)) do
if p:hasFlag("ChongzhenTarget") then
target = p
break
end
end
if target then
local intention = 60
if promptlist[3] == "yes" then
if not self:hasLoseHandcardEffective(target) or (self:needKongcheng(target) and target:getHandcardNum() == 1) then
intention = 0
end
if self:getOverflow(target) > 2 then intention = 0 end
sgs.updateIntention(player, target, intention)
else
if self:needKongcheng(target) and target:getHandcardNum() == 1 then intention = 0 end
sgs.updateIntention(player, target, -intention)
end
end
end
sgs.ai_slash_prohibit.chongzhen = function(self, from, to, card)
if self:isFriend(to, from) then return false end
if from:hasSkill("tieji") or self:canLiegong(to, from) then
return false
end
if to:hasSkill("longdan") and to:getHandcardNum() >= 3 and from:getHandcardNum() > 1 then return true end
return false
end
local lihun_skill = {}
lihun_skill.name = "lihun"
table.insert(sgs.ai_skills, lihun_skill)
lihun_skill.getTurnUseCard = function(self)
if self.player:hasUsed("LihunCard") or self.player:isNude() then return end
local card_id
local cards = self.player:getHandcards()
cards = sgs.QList2Table(cards)
self:sortByKeepValue(cards)
local lightning = self:getCard("Lightning")
if self:needToThrowArmor() then
card_id = self.player:getArmor():getId()
elseif self.player:getHandcardNum() > self.player:getHp() then
if lightning and not self:willUseLightning(lightning) then
card_id = lightning:getEffectiveId()
else
for _, acard in ipairs(cards) do
if (acard:isKindOf("BasicCard") or acard:isKindOf("EquipCard") or acard:isKindOf("AmazingGrace"))
and not acard:isKindOf("Peach") then
card_id = acard:getEffectiveId()
break
end
end
end
elseif not self.player:getEquips():isEmpty() then
local player = self.player
if player:getWeapon() then card_id = player:getWeapon():getId()
elseif player:getOffensiveHorse() then card_id = player:getOffensiveHorse():getId()
elseif player:getDefensiveHorse() then card_id = player:getDefensiveHorse():getId()
elseif player:getArmor() and player:getHandcardNum() <= 1 then card_id = player:getArmor():getId()
end
end
if not card_id then
if lightning and not self:willUseLightning(lightning) then
card_id = lightning:getEffectiveId()
else
for _, acard in ipairs(cards) do
if (acard:isKindOf("BasicCard") or acard:isKindOf("EquipCard") or acard:isKindOf("AmazingGrace"))
and not acard:isKindOf("Peach") then
card_id = acard:getEffectiveId()
break
end
end
end
end
if not card_id then
return nil
else
return sgs.Card_Parse("@LihunCard=" .. card_id)
end
end
sgs.ai_skill_use_func.LihunCard = function(card,use,self)
local cards = self.player:getHandcards()
cards = sgs.QList2Table(cards)
if not self.player:hasUsed("LihunCard") then
self:sort(self.enemies, "handcard")
self.enemies = sgs.reverse(self.enemies)
local target
local jwfy = self.room:findPlayerBySkillName("shoucheng")
for _, enemy in ipairs(self.enemies) do
if enemy:isMale() and not enemy:hasSkill("kongcheng") then
if ((enemy:hasSkill("lianying") or (jwfy and self:isFriend(jwfy, enemy))) and self:damageMinusHp(self, enemy, 1) > 0)
or (enemy:getHp() < 3 and self:damageMinusHp(self, enemy, 0) > 0 and enemy:getHandcardNum() > 0)
or (enemy:getHandcardNum() >= enemy:getHp() and enemy:getHp() > 2 and self:damageMinusHp(self, enemy, 0) >= -1)
or (enemy:getHandcardNum() - enemy:getHp() > 2) then
target = enemy
break
end
end
end
if not self.player:faceUp() and not target then
for _, enemy in ipairs(self.enemies) do
if enemy:isMale() and not enemy:isKongcheng() then
if enemy:getHandcardNum() >= enemy:getHp() then
target = enemy
break
end
end
end
end
if not target and (self:hasCrossbowEffect() or self:getCardsNum("Crossbow") > 0) then
local slash = self:getCard("Slash") or sgs.Sanguosha:cloneCard("slash")
for _, enemy in ipairs(self.enemies) do
if enemy:isMale() and not enemy:isKongcheng() and self:slashIsEffective(slash, enemy) and self.player:distanceTo(enemy) == 1
and not enemy:hasSkills("fenyong|zhichi|fankui|vsganglie|ganglie|neoganglie|enyuan|nosenyuan|langgu|guixin|kongcheng")
and self:getCardsNum("Slash") + getKnownCard(enemy, self.player, "Slash") >= 3 then
target = enemy
break
end
end
end
if target then
use.card = card
if use.to then use.to:append(target) end
end
end
end
function SmartAI:isLihunTarget(player, drawCardNum)
player = player or self.player
drawCardNum = drawCardNum or 1
if type(player) == "table" then
if #player == 0 then return false end
for _, ap in ipairs(player) do
if self:isLihunTarget(ap, drawCardNum) then return true end
end
return false
end
local handCardNum = player:getHandcardNum() + drawCardNum
if not player:isMale() then return false end
local sb_diaochan = self.room:findPlayerBySkillName("lihun")
local lihun = sb_diaochan and not sb_diaochan:hasUsed("LihunCard") and not self:isFriend(sb_diaochan)
if not lihun then return false end
if sb_diaochan:getPhase() == sgs.Player_Play then
if (handCardNum - player:getHp() >= 2)
or (handCardNum > 0 and handCardNum - player:getHp() >= -1 and not sb_diaochan:faceUp()) then
return true
end
else
if sb_diaochan:faceUp() and not self:willSkipPlayPhase(sb_diaochan)
and self:playerGetRound(player) > self:playerGetRound(sb_diaochan) and handCardNum >= player:getHp() + 2 then
return true
end
end
return false
end
sgs.ai_skill_discard.lihun = function(self, discard_num, min_num, optional, include_equip)
local to_discard = {}
local cards = sgs.QList2Table(self.player:getCards("he"))
self:sortByKeepValue(cards)
local card_ids = {}
for _,card in ipairs(cards) do
table.insert(card_ids, card:getEffectiveId())
end
local temp = table.copyFrom(card_ids)
for i = 1, #temp, 1 do
local card = sgs.Sanguosha:getCard(temp[i])
if self.player:getArmor() and temp[i] == self.player:getArmor():getEffectiveId() and self:needToThrowArmor() then
table.insert(to_discard, temp[i])
table.removeOne(card_ids, temp[i])
if #to_discard == discard_num then
return to_discard
end
end
end
temp = table.copyFrom(card_ids)
for i = 1, #card_ids, 1 do
local card = sgs.Sanguosha:getCard(card_ids[i])
table.insert(to_discard, card_ids[i])
if #to_discard == discard_num then
return to_discard
end
end
if #to_discard < discard_num then return {} end
end
sgs.ai_use_value.LihunCard = 8.5
sgs.ai_use_priority.LihunCard = 6
sgs.ai_card_intention.LihunCard = 80
function sgs.ai_skill_invoke.kuiwei(self, data)
local weapon = 0
local sbdiaochan = self.room:findPlayerBySkillName("lihun")
if sbdiaochan and sbdiaochan:faceUp() and not self:willSkipPlayPhase(sbdiaochan)
and (self:isEnemy(sbdiaochan) or sgs.turncount <= 1 and sgs.evaluatePlayerRole(sbdiaochan) == "neutral") then return false end
if not self.player:faceUp() then return true end
for _, friend in ipairs(self.friends) do
if friend:hasSkills("fangzhu|jilve") then return true end
if friend:hasSkill("junxing") and friend:faceUp() and not self:willSkipPlayPhase(friend)
and not (friend:isKongcheng() and self:willSkipDrawPhase(friend)) then
return true
end
end
for _, aplayer in sgs.qlist(self.room:getAlivePlayers()) do
if aplayer:getWeapon() then weapon = weapon + 1 end
end
if weapon > 1 then return true end
return self:isWeak()
end
sgs.ai_view_as.yanzheng = function(card, player, card_place)
local suit = card:getSuitString()
local number = card:getNumberString()
local card_id = card:getEffectiveId()
if card_place == sgs.Player_PlaceEquip and player:getHandcardNum() > player:getHp() then
return ("nullification:yanzheng[%s:%s]=%d"):format(suit, number, card_id)
end
end
sgs.ai_skill_invoke.manjuan = true
sgs.ai_skill_invoke.zuixiang = function(self)
if self.player:hasFlag("AI_doNotInvoke_zuixiang") then
self.player:setFlags("-AI_doNotInvoke_zuixiang")
return
end
end
sgs.ai_skill_askforag.manjuan = function(self, card_ids)
local cards = {}
for _, card_id in ipairs(card_ids) do
table.insert(cards, sgs.Sanguosha:getCard(card_id))
end
for _, card in ipairs(cards) do
if card:isKindOf("ExNihilo") then return card:getEffectiveId() end
if card:isKindOf("IronChain") then return card:getEffectiveId() end
end
for _, card in ipairs(cards) do
if card:isKindOf("Snatch") and #self.enemies > 0 then
self:sort(self.enemies,"defense")
if sgs.getDefense(self.enemies[1]) >= 8 then self:sort(self.enemies, "threat") end
local enemies = self:exclude(self.enemies, card)
for _,enemy in ipairs(enemies) do
if self:hasTrickEffective(card, enemy) then
return card:getEffectiveId()
end
end
end
end
for _, card in ipairs(cards) do
if card:isKindOf("Peach") and self.player:isWounded() and self:getCardsNum("Peach") < self.player:getLostHp() then return card:getEffectiveId() end
end
for _, card in ipairs(cards) do
if card:isKindOf("AOE") and self:getAoeValue(card) > 0 then return card:getEffectiveId() end
end
self:sortByCardNeed(cards)
return cards[#cards]:getEffectiveId()
end
function hasManjuanEffect(player)
return player:hasSkill("manjuan") and player:getPhase() == sgs.Player_NotActive
end
sgs.ai_cardneed.jie = function(to, card)
return card:isRed() and isCard("Slash", card, to)
end
local dahe_skill = {}
dahe_skill.name = "dahe"
table.insert(sgs.ai_skills,dahe_skill)
dahe_skill.getTurnUseCard = function(self)
if self:needBear() then return end
if not self.player:hasUsed("DaheCard") and not self.player:isKongcheng() then return sgs.Card_Parse("@DaheCard=.") end
end
sgs.ai_skill_use_func.DaheCard=function(card,use,self)
self:sort(self.enemies, "handcard")
local max_card = self:getMaxCard(self.player)
local max_point = max_card:getNumber()
local slashcount = self:getCardsNum("Slash")
if max_card:isKindOf("Slash") then slashcount = slashcount - 1 end
if self.player:hasSkill("kongcheng") and self.player:getHandcardNum() == 1 then
for _, enemy in ipairs(self.enemies) do
if not enemy:isKongcheng() then
self.dahe_card = max_card:getId()
use.card = sgs.Card_Parse("@DaheCard=.")
if use.to then use.to:append(enemy) end
return
end
end
end
if slashcount > 0 then
local slash = self:getCard("Slash")
assert(slash)
local dummy_use = {isDummy = true}
self:useBasicCard(slash, dummy_use)
for _, enemy in ipairs(self.enemies) do
if not (enemy:hasSkill("kongcheng") and enemy:getHandcardNum() == 1 and enemy:getHp() > self.player:getHp())
and not enemy:isKongcheng() and self.player:canSlash(enemy, nil, true) then
local enemy_max_card = self:getMaxCard(enemy)
local allknown = 0
if self:getKnownNum(enemy) == enemy:getHandcardNum() then
allknown = allknown + 1
end
if (enemy_max_card and max_point > enemy_max_card:getNumber() and allknown > 0)
or (enemy_max_card and max_point > enemy_max_card:getNumber() and allknown < 1 and max_point > 10)
or (not enemy_max_card and max_point > 10) then
self.dahe_card = max_card:getId()
use.card = sgs.Card_Parse("@DaheCard=.")
if use.to then use.to:append(enemy) end
return
end
end
end
end
end
function sgs.ai_skill_pindian.dahe(minusecard, self, requestor)
if self:isFriend(requestor) then return minusecard end
return self:getMaxCard(self.player):getId()
end
sgs.ai_skill_playerchosen.dahe = function(self, targets)
targets = sgs.QList2Table(targets)
self:sort(targets, "defense")
for _, target in ipairs(targets) do
if target:hasSkill("kongcheng") and target:isKongcheng()
and target:hasFlag("dahe") then
return target
end
end
for _, target in ipairs(targets) do
if self:isFriend(target) and not self:needKongcheng(target, true) then return target end
end
return nil
end
sgs.ai_cardneed.dahe = sgs.ai_cardneed.bignumber
sgs.ai_card_intention.DaheCard = 60
sgs.dynamic_value.control_card.DaheCard = true
sgs.ai_use_value.DaheCard = 8.5
sgs.ai_use_priority.DaheCard = 8
local tanhu_skill = {}
tanhu_skill.name = "tanhu"
table.insert(sgs.ai_skills, tanhu_skill)
tanhu_skill.getTurnUseCard = function(self)
if not self.player:hasUsed("TanhuCard") and not self.player:isKongcheng() then return sgs.Card_Parse("@TanhuCard=.") end
end
sgs.ai_skill_use_func.TanhuCard = function(card, use, self)
local max_card = self:getMaxCard()
local max_point = max_card:getNumber()
local ptarget = self:getPriorTarget()
if not ptarget then return end
local slashcount = self:getCardsNum("Slash")
if max_card:isKindOf("Slash") then slashcount = slashcount - 1 end
if not ptarget:isKongcheng() and slashcount > 0 and self.player:canSlash(ptarget, nil, false)
and not (ptarget:hasSkill("kongcheng") and ptarget:getHandcardNum() == 1) then
self.tanhu_card = max_card:getEffectiveId()
use.card = sgs.Card_Parse("@TanhuCard=.")
if use.to then use.to:append(ptarget) end
return
end
self:sort(self.enemies, "defense")
for _, enemy in ipairs(self.enemies) do
if self:getCardsNum("Snatch") > 0 and not enemy:isKongcheng() then
local enemy_max_card = self:getMaxCard(enemy)
local allknown = 0
if self:getKnownNum(enemy) == enemy:getHandcardNum() then
allknown = allknown + 1
end
if (enemy_max_card and max_point > enemy_max_card:getNumber() and allknown > 0)
or (enemy_max_card and max_point > enemy_max_card:getNumber() and allknown < 1 and max_point > 10)
or (not enemy_max_card and max_point > 10)
and (self:getDangerousCard(enemy) or self:getValuableCard(enemy)) then
self.tanhu_card = max_card:getEffectiveId()
use.card = sgs.Card_Parse("@TanhuCard=.")
if use.to then use.to:append(enemy) end
return
end
end
end
local cards = sgs.QList2Table(self.player:getHandcards())
self:sortByUseValue(cards, true)
if self:getUseValue(cards[1]) >= 6 or self:getKeepValue(cards[1]) >= 6 then return end
if self:getOverflow() > 0 then
if not ptarget:isKongcheng() then
self.tanhu_card = max_card:getEffectiveId()
use.card = sgs.Card_Parse("@TanhuCard=.")
if use.to then use.to:append(ptarget) end
return
end
for _, enemy in ipairs(self.enemies) do
if not (enemy:hasSkill("kongcheng") and enemy:getHandcardNum() == 1) and not enemy:isKongcheng() and not enemy:hasSkills("tuntian+zaoxian") then
self.tanhu_card = cards[1]:getId()
use.card = sgs.Card_Parse("@TanhuCard=.")
if use.to then use.to:append(enemy) end
return
end
end
end
end
sgs.ai_cardneed.tanhu = sgs.ai_cardneed.bignumber
sgs.ai_card_intention.TanhuCard = 30
sgs.dynamic_value.control_card.TanhuCard = true
sgs.ai_use_priority.TanhuCard = 8
function sgs.ai_skill_pindian.tanhu(minusecard, self, requestor)
if requestor:getHandcardNum() == 1 then
local cards = sgs.QList2Table(self.player:getHandcards())
self:sortByKeepValue(cards)
return cards[1]
end
end
local function need_mouduan(self)
local cardsCount = self.player:getHandcardNum()
if cardsCount <= 3 then return false end
local current = self.room:getCurrent()
local slash = sgs.Sanguosha:cloneCard("slash")
if current:objectName() == self.player:objectName() then
if (self:hasCrossbowEffect() or self:getCardsNum("Crossbow") > 0)
and self:getCardsNum("Slash") >= 3
and (not self:willSkipPlayPhase() or self.player:hasSkill("dangxian")) then
local hasTarget = false
for _, enemy in ipairs(self.enemies) do
if not self:slashProhibit(slash, enemy) and self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self, true) then
hasTarget = true
break
end
end
return hasTarget
end
elseif (cardsCount == 4 or cardsCount == 5) and #self.enemies > 1 then
return true
end
return false
end
sgs.ai_skill_cardask["@mouduan"] = function(self, data)
if not need_mouduan(self) then return "." end
local to_discard = self:askForDiscard("mouduan", 1, 1, false, true)
if #to_discard > 0 then return "$" .. to_discard[1] else return "." end
end
sgs.ai_skill_playerchosen.zhaolie = function(self, targets)
if self.player:hasFlag("AI_doNotInvoke_zhaolie") then
self.player:setFlags("-AI_doNotInvoke_zhaolie")
return
end
targets = sgs.QList2Table(targets)
self:sort(targets, "hp")
for _, target in ipairs(targets) do
if self:isEnemy(target) and self:damageIsEffective(target) and sgs.isGoodTarget(target, targets, self) and not self:doNotDiscard(target)
and not (self:isWeak() and (target:getHp() > 1 or target:getCardCount() >= 3)) then
return target
end
end
return nil
end
local function will_discard_zhaolie(self, nobasic)
local spliubei = self.room:getCurrent()
if not spliubei or not spliubei:isAlive() then return true end
if not self:damageIsEffective(self.player, sgs.DamageStruct_Normal, spliubei) then return false end
local damage_num = nobasic
if nobasic > 0 and not spliubei:hasSkill("jueqing") then
if self.player:hasSkill("tianxiang") then
local dmgStr = { damage = damage_num, nature = sgs.DamageStruct_Normal }
local willTianxiang = sgs.ai_skill_use["@@tianxiang"](self, dmgStr, sgs.Card_MethodDiscard)
if willTianxiang ~= "." then damage_num = 0 end
end
if self.player:hasSkill("mingshi") and spliubei:getEquips():length() <= self.player:getEquips():length() and damage_num > 0 then
damage_num = damage_num - 1
end
if self.player:hasArmorEffect("silver_lion") and damage_num > 1 then damage_num = 1 end
end
if not spliubei:hasSkill("jueqing") and self.player:hasSkill("wuhun") and self.role == "rebel" then
local mark = 0
local spmark = spliubei:isLord() and spliubei:getMark("@nightmare") or 0
for _, ap in sgs.qlist(self.room:getOtherPlayers(spliubei)) do
if ap:getMark("@nightmare") > mark then
mark = ap:getMark("@nightmare")
end
end
if mark == 0 and spliubei:isLord() then return false end
if mark < damage_num + spmark then return false end
end
if self.player:hasSkill("manjuan") then
if self:isFriend(spliubei) then return true
else
return not (damage_num == 0 or self.player:getHp() - damage_num >= getBestHp(self.player))
end
end
if damage_num == 0 then return false end
if damage_num < 2 and self.player:getHp() > 1 then return false else return true end
end
sgs.ai_skill_discard.zhaolie = function(self, discard_num, min_num, optional, include_equip)
if not will_discard_zhaolie(self, discard_num) then return {} end
local to_discard = {}
local cards = sgs.QList2Table(self.player:getCards("he"))
local index = 0
self:sortByKeepValue(cards)
cards = sgs.reverse(cards)
for i = #cards, 1, -1 do
local card = cards[i]
if not self.player:isJilei(card) then
table.insert(to_discard, card:getEffectiveId())
table.remove(cards, i)
index = index + 1
if index == discard_num then break end
end
end
if #to_discard < min_num then return {} else return to_discard end
end
sgs.ai_skill_invoke.zhaolie_obtain = function(self, data)
return will_discard_zhaolie(self, 0)
end
local function will_invoke_shichou(self)
local shu,enemynum = 0, 0
local first = self.player:hasFlag("Global_FirstRound")
local players = self.room:getOtherPlayers(self.player)
local shenguanyu = self.room:findPlayerBySkillName("wuhun");
if shenguanyu ~= nil then
if shenguanyu:getKingdom() == "shu" then return true end
end
for _, player in sgs.qlist(players) do
if player:getKingdom() == "shu" then
shu = shu + 1
if self:isEnemy(player) then
enemynum = enemynum + 1
end
end
end
if self.role=="rebel" and self.room:getLord():getKingdom()=="shu" then
return true
end
if shu ==0 then return false end
if enemynum >0 or shu == 1 then return true end
if first and shu > 1 and not self:isWeak() then return false end
return self:isWeak() and shu >0
end
local function player_chosen_shichou(self, targets)
if not self.room:getLord() then return false end
targets = sgs.QList2Table(targets)
self:sort(targets, "hp")
targets = sgs.reverse(targets)
if self.role=="rebel" and self.room:getLord():getKingdom()=="shu" then
return self.room:getLord()
end
for _, target in ipairs(targets) do
if target:hasSkill("wuhun") then
return target
end
end
for _, target in ipairs(targets) do
if self:isEnemy(target) then
return target
end
end
for _, target in ipairs(targets) do
if self:hasSkills("zaiqi|nosenyuan|kofkuanggu|kuanggu|enyuan",target) and target:getHp()>=2 then
return target
end
end
return targets[1]
end
sgs.ai_skill_use["@@shichou"] = function(self, prompt)
if will_invoke_shichou(self) then
local to_discard = self:askForDiscard("shichou", 2, 2, false, true)
if #to_discard == 2 then
local shu_generals = sgs.SPlayerList()
for _, p in sgs.qlist(self.room:getOtherPlayers(self.player)) do
if p:getKingdom() == "shu" then shu_generals:append(p) end
end
if shu_generals:length() == 0 then return "." end
local target = player_chosen_shichou(self, shu_generals)
if target then
return ("@ShichouCard=%d+%d->%s"):format(to_discard[1], to_discard[2], target:objectName())
end
end
end
return "."
end
sgs.ai_need_damaged.shichou = function(self, attacker, player)
if player:hasLordSkill("shichou") then
local victim
for _, p in sgs.qlist(self.room:getOtherPlayers(player)) do
if p:getMark("hate_" .. player:objectName()) > 0 and p:getMark("@hate_to") > 0 then
victim = p
break
end
end
if victim ~= nil then
local role
if sgs.isRolePredictable() and sgs.evaluatePlayerRole(player) == "rebel" or sgs.compareRoleEvaluation(player, "rebel", "loyalist") == "rebel" then
role = "rebel"
end
local need_damage = false
if (sgs.evaluatePlayerRole(player) == "loyalist" or player:isLord()) and role == "rebel" then need_damage = true end
if sgs.evaluatePlayerRole(player) == "rebel" and role ~= "rebel" then need_damage = true end
if sgs.evaluatePlayerRole(player) == "renegade" then need_damage = true end
if victim:isAlive() and need_damage then
return victim:hasSkill("wuhun") and 2 or 1
end
end
end
return false
end
sgs.ai_card_intention.ShichouCard = function(self, card, from, tos)
if from:hasSkill("weidi") and tos[1]:isLord() then
sgs.updateIntention(from, tos[1], 80)
end
end
sgs.ai_skill_use_func.YanxiaoCard = function(card, use, self)
local players = self.room:getOtherPlayers(self.player)
local tricks
self:sort(self.friends_noself, "defense")
for _, friend in ipairs(self.friends_noself) do
local need_yanxiao = (friend:containsTrick("lightning") and self:getFinalRetrial(friend) == 2)
or friend:containsTrick("indulgence") or friend:containsTrick("supply_shortage")
if need_yanxiao and not friend:containsTrick("YanxiaoCard") then
use.card = card
if use.to then use.to:append(friend) end
return
end
end
if self:getOverflow() > 0 then
if not self.player:containsTrick("YanxiaoCard") then
use.card = card
if use.to then use.to:append(self.player) end
return
end
local lord = self.room:getLord()
if lord and self:isFriend(lord) and not lord:containsTrick("YanxiaoCard") then
use.card = card
if use.to then use.to:append(lord) end
return
end
for _, friend in ipairs(self.friends_noself) do
if not friend:containsTrick("YanxiaoCard") then
use.card = card
if use.to then use.to:append(friend) end
return
end
end
end
end
sgs.ai_use_priority.YanxiaoCard = 3.9
sgs.ai_card_intention.YanxiaoCard = -80
local yanxiao_skill={}
yanxiao_skill.name="yanxiao"
table.insert(sgs.ai_skills,yanxiao_skill)
yanxiao_skill.getTurnUseCard = function(self)
local cards = self.player:getCards("he")
cards=sgs.QList2Table(cards)
local diamond_card
self:sortByUseValue(cards,true)
for _,card in ipairs(cards) do
if card:getSuit() == sgs.Card_Diamond then
diamond_card = card
break
end
end
if diamond_card then
local suit = diamond_card:getSuitString()
local number = diamond_card:getNumberString()
local card_id = diamond_card:getEffectiveId()
local card_str = ("YanxiaoCard:yanxiao[%s:%s]=%d"):format(suit, number, card_id)
local yanxiaocard = sgs.Card_Parse(card_str)
assert(yanxiaocard)
return yanxiaocard
end
end
sgs.yanxiao_suit_value = {
diamond = 3.9
}
function sgs.ai_cardneed.yanxiao(to, card)
return card:getSuit() == sgs.Card_Diamond
end
sgs.ai_skill_invoke.anxian = function(self, data)
local damage = data:toDamage()
local target = damage.to
if self:isFriend(target) and not (self:getDamagedEffects(target, self.player) or self:needToLoseHp(target, self.player, nil, true)) then return true end
if self:hasHeavySlashDamage(self.player, damage.card, damage.to) then return false end
if self:isEnemy(target) and self:getDamagedEffects(target, self.player) and not self:doNotDiscard(target, "h") then return true end
return false
end
sgs.ai_skill_cardask["@anxian-discard"] = function(self, data)
local use = data:toCardUse()
local from = use.from
local to = self.player
if self.player:isKongcheng() then return "." end
local cards = self.player:getHandcards()
cards = sgs.QList2Table(cards)
self:sortByKeepValue(cards)
if self:hasHeavySlashDamage(from, use.card, self.player) and self:canHit(to, from, true) then
return "$" .. cards[1]:getEffectiveId()
end
if self:getDamagedEffects(self.player, use.from, true) then
return "."
end
if self:needToLoseHp(self.player, use.from, true) then
return "."
end
if self:isFriend(to, from) then return "$" .. cards[1]:getEffectiveId() end
if self:needToLoseHp(self.player, use.from, true, true) then
return "."
end
if self:canHit(to, from) then
for _, card in ipairs(cards) do
if not isCard("Peach", card, self.player) then
return "$" .. card:getEffectiveId()
end
end
end
if self:getCardsNum("Jink") > 0 then
return "."
end
if #cards == self:getCardsNum("Peach") then return "." end
for _, card in ipairs(cards) do
if not isCard("Peach", card, self.player) then
return "$" .. card:getEffectiveId()
end
end
return "."
end
local yinling_skill = {}
yinling_skill.name = "yinling"
table.insert(sgs.ai_skills, yinling_skill)
yinling_skill.getTurnUseCard = function(self, inclusive)
if self.player:getPile("brocade"):length() >= 4 then return end
local cards = self.player:getCards("he")
cards = sgs.QList2Table(cards)
self:sortByUseValue(cards, true)
local black_card
local has_weapon = false
for _,card in ipairs(cards) do
if card:isKindOf("Weapon") and card:isBlack() then has_weapon=true end
end
for _,card in ipairs(cards) do
if card:isBlack() and ((self:getUseValue(card) < sgs.ai_use_value.YinlingCard) or inclusive or self:getOverflow() > 0) then
local shouldUse = true
if card:isKindOf("Armor") then
if not self.player:getArmor() then shouldUse = false
elseif self.player:hasEquip(card) and not (card:isKindOf("SilverLion") and self.player:isWounded()) then shouldUse = false
end
end
if card:isKindOf("Weapon") then
if not self.player:getWeapon() then shouldUse = false
elseif self.player:hasEquip(card) and not has_weapon then shouldUse=false
end
end
if card:isKindOf("Slash") then
local dummy_use = {isDummy = true}
if self:getCardsNum("Slash") == 1 then
self:useBasicCard(card, dummy_use)
if dummy_use.card then shouldUse = false end
end
end
if self:getUseValue(card) > sgs.ai_use_value.YinlingCard and card:isKindOf("TrickCard") then
local dummy_use = {isDummy = true}
self:useTrickCard(card, dummy_use)
if dummy_use.card then shouldUse = false end
end
if shouldUse then
black_card = card
break
end
end
end
if black_card then
local card_id = black_card:getEffectiveId()
local card_str = ("@YinlingCard="..card_id)
local yinling = sgs.Card_Parse(card_str)
assert(yinling)
return yinling
end
end
sgs.ai_skill_use_func.YinlingCard = function(card, use, self)
self:useCardSnatchOrDismantlement(card, use)
end
sgs.ai_use_value.YinlingCard = sgs.ai_use_value.Dismantlement + 1
sgs.ai_use_priority.YinlingCard = sgs.ai_use_priority.Dismantlement + 1
sgs.ai_card_intention.YinlingCard = 0 -- update later
sgs.ai_choicemade_filter.cardChosen.yinling = sgs.ai_choicemade_filter.cardChosen.snatch
sgs.ai_skill_use["@@junwei"] = function(self, data, method)
if not method then method = sgs.Card_MethodNone end
if data ~= "junwei-invoke" then return "." end
local pile = sgs.QList2Table(self.player:getPile("brocade"))
if #pile >= 3 then
local tos = {}
for _, target in ipairs(self.enemies) do
if not (target:hasEquip() and self:doNotDiscard(target, "e")) then
table.insert(tos, target)
end
end
if #tos > 0 then
self:sort(tos, "defense")
if (tos[1]) then
return "@JunweiCard=" .. tostring(pile[1]) .. "+" .. tostring(pile[2]) .. "+" .. tostring(pile[3]) .. "->" .. tos[1]:objectName()
end
end
end
return "."
end
sgs.ai_skill_invoke.junwei = function(self, data)
for _, enemy in ipairs(self.enemies) do
if not (enemy:hasEquip() and self:doNotDiscard(enemy, "e")) then return true end
end
end
sgs.ai_playerchosen_intention.junwei = 80
sgs.ai_skill_playerchosen.junweigive = function(self, targets)
local tos = {}
for _, target in sgs.qlist(targets) do
if self:isFriend(target) and not target:hasSkill("manjuan") and not self:needKongcheng(target, true) then
table.insert(tos, target)
end
end
if #tos > 0 then
for _, to in ipairs(tos) do
if to:hasSkills("leiji|nosleiji") then return to end
end
self:sort(tos, "defense")
return tos[1]
end
end
sgs.ai_playerchosen_intention.junweigive = -80
sgs.ai_skill_cardask["@junwei-show"] = function(self, data)
if self.player:hasArmorEffect("silver_lion") and self.player:getEquips():length() == 1 then return "." end
local ganning = data:toPlayer()
local cards = self.player:getHandcards()
cards = sgs.QList2Table(cards)
for _,card in ipairs(cards) do
if card:isKindOf("Jink") then
return "$" .. card:getEffectiveId()
end
end
return "."
end
sgs.yinling_suit_value = {
spade = 3.9,
club = 3.9
}
sgs.ai_skill_invoke.fenyong = function(self, data)
self.fenyong_choice = nil
if sgs.turncount <= 1 and #self.enemies == 0 then return end
local current = self.room:getCurrent()
if not current or current:getPhase() >= sgs.Player_Finish then return true end
if self:isFriend(current) then
self:sort(self.enemies, "defenseSlash")
for _, enemy in ipairs(self.enemies) do
local def = sgs.getDefenseSlash(enemy, self)
local slash = sgs.Sanguosha:cloneCard("slash", sgs.Card_NoSuit, 0)
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if self.player:canSlash(enemy, nil, false) and not self:slashProhibit(nil, enemy) and eff and def < 5 then
return true
end
if self.player:getLostHp() == 1 and self:needToThrowArmor(current) then return true end
end
return false
end
return true
end
function sgs.ai_slash_prohibit.fenyong(self, from, to)
if from:hasSkill("jueqing") or (from:hasSkill("nosqianxi") and from:distanceTo(to) == 1) then return false end
if from:hasFlag("NosJiefanUsed") then return false end
return to:getMark("@fenyong") > 0 and to:hasSkill("fenyong")
end
sgs.ai_need_damaged.fenyong = function (self, attacker, player)
if not player:hasSkill("fenyong") then return false end
if not player:hasSkill("xuehen") then return false end
for _, enemy in ipairs(self.enemies) do
local def = sgs.getDefenseSlash(enemy, self)
local slash = sgs.Sanguosha:cloneCard("slash", sgs.Card_NoSuit, 0)
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if self.player:canSlash(enemy, nil, false) and not self:slashProhibit(nil, enemy) and eff and def < 6 then
return true
end
end
return false
end
sgs.ai_skill_choice.xuehen = function(self, choices)
if self.fenyong_choice then return self.fenyong_choice end
local current = self.room:getCurrent()
local n = self.player:getLostHp()
if self:isEnemy(current) then
if n >= 3 and current:getCardCount(true) >= 3 and not (self:needKongcheng(current) and current:getCards("e"):length() < 3)
and not (self:hasSkills(sgs.lose_equip_skill, current) and current:getHandcardNum() < n) then
return "discard"
end
if self:hasSkills("jijiu|tuntian+zaoxian|beige", current) and n >= 2 and current:getCardCount(true) >= 2 then return "discard" end
end
self:sort(self.enemies, "defenseSlash")
for _, enemy in ipairs(self.enemies) do
local def = sgs.getDefenseSlash(enemy, self)
local slash = sgs.Sanguosha:cloneCard("slash")
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if self.player:canSlash(enemy, nil, false) and not self:slashProhibit(nil, enemy) and eff and def < 6 then
self.xuehentarget = enemy
return "slash"
end
end
if self:isEnemy(current) then
for _, enemy in ipairs(self.enemies) do
local slash = sgs.Sanguosha:cloneCard("slash")
local eff = self:slashIsEffective(slash, enemy)
if self.player:canSlash(enemy, nil, false) and not self:slashProhibit(nil, enemy) and self:hasHeavySlashDamage(self.player, slash, enemy) then
self.xuehentarget = enemy
return "slash"
end
end
local armor = current:getArmor()
if armor and self:evaluateArmor(armor, current) >= 3 and not self:doNotDiscard(current, "e") and n <= 2 then return "discard" end
end
if self:isFriend(current) then
if n == 1 and self:needToThrowArmor(current) then return "discard" end
for _, enemy in ipairs(self.enemies) do
local slash = sgs.Sanguosha:cloneCard("slash")
local eff = self:slashIsEffective(slash, enemy)
if self.player:canSlash(enemy, nil, false) and not self:slashProhibit(nil, enemy) then
self.xuehentarget = enemy
return "slash"
end
end
end
return "discard"
end
sgs.ai_skill_playerchosen.xuehen = function(self, targets)
local to = self.xuehentarget
if to then
self.xuehentarget = nil
return to
end
to = sgs.ai_skill_playerchosen.zero_card_as_slash(self, targets)
return to or targets[1]
end
sgs.ai_suit_priority.jie = "club|spade|diamond|heart"
sgs.ai_suit_priority.yanxiao = "club|spade|heart|diamond"
sgs.ai_suit_priority.yinling = "diamond|heart|club|spade"
--AI for DIY generals
sgs.ai_skill_use["@@zhaoxin"] = function(self, prompt)
local target
self:sort(self.enemies, "defenseSlash")
for _, enemy in ipairs(self.enemies) do
local slash = sgs.Sanguosha:cloneCard("slash", sgs.Card_NoSuit, 0)
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if eff and self.player:canSlash(enemy) and not self:slashProhibit(nil, enemy) then
return "@ZhaoxinCard=.->" .. enemy:objectName()
end
end
return "."
end
sgs.ai_card_intention.ZhaoxinCard = 80
sgs.ai_skill_invoke.langgu = function(self, data)
local damage = data:toDamage()
return damage.from and not self:isFriend(damage.from)
end
sgs.ai_choicemade_filter.skillInvoke.langgu = function(self, player, promptlist)
local damage = self.room:getTag("CurrentDamageStruct"):toDamage()
if damage.from and promptlist[3] == "yes" then
sgs.updateIntention(player, damage.from, 10)
end
end
sgs.ai_skill_askforag.langgu = function(self, card_ids)
return -1
end
sgs.ai_skill_cardask["@langgu-card"] = function(self, data)
local judge = data:toJudge()
local retrialForHongyan
local damage = self.room:getTag("CurrentDamageStruct"):toDamage()
if damage.from and damage.from:isAlive() and not damage.from:isKongcheng() and damage.from:hasSkill("hongyan")
and getKnownCard(damage.from, self.player, "diamond", false) + getKnownCard(damage.from, self.player, "club", false) < damage.from:getHandcardNum() then
retrialForHongyan = true
end
if retrialForHongyan then
local cards = sgs.QList2Table(self.player:getHandcards())
for _, card in ipairs(cards) do
if card:getSuit() == sgs.Card_Heart and not isCard("Peach", card, self.player) then
return "$" .. card:getId()
end
end
if judge.card:getSuit() == sgs.Card_Spade then
self:sortByKeepValue(cards)
for _, card in ipairs(cards) do
if card:getSuit() ~= sgs.Card_Spade and not isCard("Peach", card, self.player) then
return "$" .. card:getId()
end
end
end
end
return "."
end
local fuluan_skill = {}
fuluan_skill.name = "fuluan"
table.insert(sgs.ai_skills, fuluan_skill)
fuluan_skill.getTurnUseCard = function(self)
if self.player:hasUsed("FuluanCard") or self.player:hasFlag("ForbidFuluan") then return end
local first_found, second_found, third_found = false, false, false
local first_card, second_card, third_card
if self.player:getCards("he"):length() >= 3 then
local cards = self.player:getCards("he")
local same_suit = false
cards = sgs.QList2Table(cards)
for _, fcard in ipairs(cards) do
if not isCard("Peach", fcard, self.player) and not isCard("ExNihilo", fcard, self.player) then
first_card = fcard
first_found = true
for _, scard in ipairs(cards) do
if first_card ~= scard and scard:getSuit() == first_card:getSuit()
and not isCard("Peach", scard, self.player) and not isCard("ExNihilo", scard, self.player) then
second_card = scard
second_found = true
for _, tcard in ipairs(cards) do
if first_card ~= tcard and second_card ~= tcard and tcard:getSuit() == first_card:getSuit()
and not isCard("Peach", tcard, self.player) and not isCard("ExNihilo", tcard, self.player) then
third_card = tcard
third_found = true
break
end
end
end
if third_found then break end
end
end
if third_found and second_found then break end
end
end
if first_found and second_found and third_found then
local card_str = ("@FuluanCard=%d+%d+%d"):format(first_card:getId(), second_card:getId(), third_card:getId())
assert(card_str)
return sgs.Card_Parse(card_str)
end
end
local function can_be_selected_as_target_fuluan(self, card, who)
local subcards = card:getSubcards()
if self.player:getWeapon() and subcards:contains(self.player:getWeapon():getId()) then
local distance_fix = sgs.weapon_range[self.player:getWeapon():getClassName()] - self.player:getAttackRange(false)
if self.player:getOffensiveHorse() and subcards:contains(self.player:getOffensiveHorse():getId()) then
distance_fix = distance_fix + 1
end
return self.player:distanceTo(who, distance_fix) <= self.player:getAttackRange()
elseif self.player:getOffensiveHorse() and subcards:contains(self.player:getOffensiveHorse():getId()) then
return self.player:distanceTo(who, 1) <= self.player:getAttackRange()
elseif self.player:inMyAttackRange(who) then
return true
end
return false
end
sgs.ai_skill_use_func.FuluanCard = function(card, use, self)
local subcards = card:getSubcards()
self:sort(self.friends_noself)
for _, friend in ipairs(self.friends_noself) do
if not self:toTurnOver(friend, 0) then
if can_be_selected_as_target_fuluan(self, card, friend) then
use.card = card
if use.to then use.to:append(friend) end
return
end
end
end
self:sort(self.enemies, "defense")
for _, enemy in ipairs(self.enemies) do
if self:toTurnOver(enemy, 0) then
if can_be_selected_as_target_fuluan(self, card, enemy) then
use.card = card
if use.to then use.to:append(enemy) end
return
end
end
end
end
sgs.ai_use_priority.FuluanCard = 2.3
sgs.ai_card_intention.FuluanCard = function(self, card, from, tos)
sgs.updateIntention(from, tos[1], tos[1]:faceUp() and 80 or -80)
end
local function need_huangen(self, who)
local use = self.player:getTag("huangen"):toCardUse()
local card, from = use.card, use.from
if self:isEnemy(who) then
if card:isKindOf("GodSalvation") and who:isWounded() and who:getHp() < getBestHp(who) and self:hasTrickEffective(card, who, from) then
if hasManjuanEffect(who) then return true end
if self:isWeak(who) then return true end
if who:hasSkills(sgs.masochism_skill) then return true end
end
if card:isKindOf("ExNihilo") then return true end
return false
elseif self:isFriend(who) then
if who:hasSkill("noswuyan") and from:objectName() ~= who:objectName() then return true end
if card:isKindOf("GodSalvation") and not who:isWounded() then
if hasManjuanEffect(who) then return false end
if self:needKongcheng(who, true) then return false end
return true
end
if card:isKindOf("GodSalvation") and who:isWounded() and self:hasTrickEffective(card, who, from) then
if who:getHp() > getBestHp(who) and not self:needKongcheng(who, true) then return true end
return false
end
if card:isKindOf("IronChain") and (self:needKongcheng(who, true) or (who:isChained() and self:hasTrickEffective(card, who, from))) then
return false
end
if card:isKindOf("AmazingGrace") then return not self:hasTrickEffective(card, who, from) end
if card:isKindOf("ExNihilo") then return false end
return true
end
end
sgs.ai_skill_use["@@huangen"] = function(self, prompt)
local card = self.player:getTag("huangen"):toCardUse().card
local players = sgs.QList2Table(self.room:getAllPlayers())
self:sort(players, "defense")
local target_table = {}
local targetslist = self.player:property("huangen_targets"):toString():split("+")
for _, player in ipairs(players) do
if table.contains(targetslist, player:objectName()) and need_huangen(self, player) then
table.insert(target_table, player:objectName())
if #target_table == self.player:getHp() then break end
end
end
if #target_table == 0 then return "." end
return "@HuangenCard=.->" .. table.concat(target_table, "+")
end
sgs.ai_card_intention.HuangenCard = function(self, card, from, tos)
local cardx = self.player:getTag("huangen"):toCardUse().card
if not cardx then return end
for _, to in ipairs(tos) do
local intention = -80
if cardx:isKindOf("GodSalvation") and to:isWounded() and (hasManjuanEffect(to) or self:isWeak(to)) then intention = 50 end
if self:needKongcheng(to, true) then intention = 0 end
if cardx:isKindOf("AmazingGrace") and self:hasTrickEffective(cardx, to) then intention = 0 end
sgs.updateIntention(from, to, intention)
end
end
sgs.ai_skill_invoke.hantong = true
sgs.ai_skill_invoke.hantong_acquire = function(self, data)
local skill = data:toString()
if skill == "hujia" and not self.player:hasSkill("hujia") then
local can_invoke = false
for _, friend in ipairs(self.friends_noself) do
if friend:getKingdom() == "wei" and getCardsNum("Jink", friend, self.player) > 0 then can_invoke = true end
end
if can_invoke then
local origin_data = self.player:getTag("HantongOriginData")
return sgs.ai_skill_invoke.hujia(self, origin_data)
end
elseif skill == "jijiang" and not self.player:hasSkill("jijiang") then
local can_invoke = false
for _, friend in ipairs(self.friends_noself) do
if friend:getKingdom() == "shu" and getCardsNum("Slash", friend, self.player) > 0 then can_invoke = true end
end
if can_invoke then
local origin_data = self.player:getTag("HantongOriginData")
return sgs.ai_skill_invoke.jijiang(self, origin_data)
end
elseif skill == "jiuyuan" and not self.player:hasSkill("jiuyuan") then
return true
elseif skill == "xueyi" and not self.player:hasSkill("xueyi") then
local maxcards = self.player:getMaxCards()
local can_invoke = false
for _, player in sgs.qlist(self.room:getOtherPlayers(self.player)) do
if player:getKingdom() == "qun" then can_invoke = true end
end
if can_invoke then return self.player:getHandcardNum() > maxcards end
end
return false
end
local hantong_skill = {}
hantong_skill.name = "hantong"
table.insert(sgs.ai_skills, hantong_skill)
hantong_skill.getTurnUseCard = function(self)
if self.player:hasLordSkill("jijiang") or self.player:getPile("edict"):isEmpty() or not self:slashIsAvailable() then return end
local can_invoke = false
for _, friend in ipairs(self.friends_noself) do
if friend:getKingdom() == "shu" and getCardsNum("Slash", friend) > 0 then can_invoke = true end
end
if not can_invoke then return end
return sgs.Card_Parse("@HantongCard=.")
end
sgs.ai_skill_use_func.HantongCard = function(card, use, self)
local jcard = sgs.Card_Parse("@JijiangCard=.")
local dummy_use = { isDummy = true }
self:useSkillCard(jcard, dummy_use)
if dummy_use.card then use.card = card end
end
sgs.ai_use_value.HantongCard = sgs.ai_use_value.JijiangCard
sgs.ai_use_priority.HantongCard = sgs.ai_use_priority.JijiangCard
sgs.ai_card_intention.HantongCard = sgs.ai_card_intention.JijiangCard
function sgs.ai_cardsview_valuable.hantong(self, class_name, player)
if class_name == "Slash" and player:getPile("edict"):length() > 0 and not player:hasSkill("jijiang") then
local ret = sgs.ai_cardsview_valuable.jijiang(self, class_name, player, false)
if ret then return "@HantongCard=." end
end
end
sgs.ai_skill_use["@@diyyicong"] = function(self, prompt)
local yicongcards = {}
if self:needToThrowArmor() then
return "@DIYYicongCard=" .. self.player:getArmor():getId() .. "->."
end
local cards = self.player:getCards("he")
cards = sgs.QList2Table(cards)
self:sortByKeepValue(cards)
for _, card in ipairs(cards) do
if self:getKeepValue(card) < 6
and (not self.player:getArmor() or card:getId() ~= self.player:getArmor():getEffectiveId())
and (not self.player:getDefensiveHorse() or card:getId() ~= self.player:getDefensiveHorse():getEffectiveId()) then
table.insert(yicongcards, card:getId())
break
end
end
if #yicongcards > 0 then
return "@DIYYicongCard=" .. table.concat(yicongcards, "+") .. "->."
end
return "."
end
| gpl-3.0 |
TeleBang/bangtg | plugins/fun.lua | 7 | 31685 |
do
--------------------------
local function savefile(extra, success, result)
local msg = extra.msg
local name = extra.name
local adress = extra.adress
local receiver = get_receiver(msg)
if success then
local file = './'..adress..'/'..name..''
print('File saving to:', result)
os.rename(result, file)
print('File moved to:', file)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
--------------------------
local function clean_msg(extra, suc, result)
for i=1, #result do
delete_msg(result[i].id, ok_cb, false)
end
if tonumber(extra.con) == #result then
send_msg(extra.chatid, ''..#result..' messages were deleted', ok_cb, false)
else
send_msg(extra.chatid, 'Error Deleting messages', ok_cb, false)
end
end
-----------------------
local function topng(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/topng/'..msg.from.id..'.png'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_document(get_receiver(msg), file, ok_cb, false)
redis:del("photo:png")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-----------------------
local function toaudio(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/toaudio/'..msg.from.id..'.mp3'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_audio(get_receiver(msg), file, ok_cb, false)
redis:del("video:audio")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-----------------------
local function tomkv(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/tomkv/'..msg.from.id..'.mkv'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_document(get_receiver(msg), file, ok_cb, false)
redis:del("video:document")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-----------------------
local function togif(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/togif/'..msg.from.id..'.mp4'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_document(get_receiver(msg), file, ok_cb, false)
redis:del("video:gif")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-----------------------
local function tovideo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/tovideo/'..msg.from.id..'.gif'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_video(get_receiver(msg), file, ok_cb, false)
redis:del("gif:video")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-----------------------
local function toimage(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/tophoto/'..msg.from.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_photo(get_receiver(msg), file, ok_cb, false)
redis:del("sticker:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-----------------------
local function tosticker(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = './data/tosticker/'..msg.from.id..'.webp'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_document(get_receiver(msg), file, ok_cb, false)
redis:del("photo:sticker")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
------------------------
local function get_weather(location)
print("Finding weather in ", location)
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local url = BASE_URL
url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b'
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد\n____________________'
local conditions = 'شرایط فعلی آب و هوا : '
if weather.weather[1].main == 'Clear' then
conditions = conditions .. 'آفتابی☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. 'ابری ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. 'بارانی ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. 'طوفانی ☔☔☔☔'
elseif weather.weather[1].main == 'Mist' then
conditions = conditions .. 'مه 💨'
end
return temp .. '\n' .. conditions
end
--------------------------
local function calc(exp)
url = 'http://api.mathjs.org/v1/'
url = url..'?expr='..URL.escape(exp)
b,c = http.request(url)
text = nil
if c == 200 then
text = 'Result = '..b..'\n_____________________'
elseif c == 400 then
text = b
else
text = 'Unexpected error\n'
..'Is api.mathjs.org up?'
end
return text
end
--------------------------
function run(msg, matches)
--------------------------
if matches[1] == 'rmsg'or matches[1] =='حذف پیام' and is_momod(msg) then
if msg.to.type == "user" then
return
end
if msg.to.type == 'chat' then
return "Only in the Super Group"
end
if not is_owner(msg) then
return "You Are Not Allow To clean Msgs!"
end
if tonumber(matches[3]) > 100 or tonumber(matches[3]) < 10 then
return "Minimum clean 10 and maximum clean is 100"
end
get_history(msg.to.peer_id, matches[3] + 1 , clean_msg , { chatid = msg.to.peer_id,con = matches[3]})
end
--------------------------
if matches[1] == 'addplugin' and is_sudo(msg) then
if not is_sudo(msg) then
return "You Are Not Allow To Add Plugin"
end
name = matches[2]
text = matches[3]
file = io.open("./plugins/"..name, "w")
file:write(text)
file:flush()
file:close()
return "Add plugin successful "
end
------------------------
if matches[1] == "mean" then
http = http.request('http://api.vajehyab.com/v2/public/?q='..URL.escape(matches[2]))
data = json:decode(http)
return 'واژه : '..(data.data.title or data.search.q)..'\n\nترجمه : '..(data.data.text or '----' )..'\n\nمنبع : '..(data.data.source or '----' )..'\n\n'..(data.error.message or '')..'\n..\n____________________'
end
--------------------------
if matches[1] == "dl"or matches[1] =='ح' and matches[2] == "plugin" and is_sudo(msg) then
if not is_sudo(msg) then
return "You Are Not Allow To Download Plugins!"
end
receiver = get_receiver(msg)
send_document(receiver, "./plugins/"..matches[3]..".lua", ok_cb, false)
send_document(receiver, "./plugins/"..matches[3], ok_cb, false)
end
--------------------------
if matches[1] == "calc"or matches[1] =="ماشین حساب" and matches[2] then
if msg.to.type == "user" then
return
end
return calc(matches[2])
end
--------------------------
if matches[1] == 'weather' then
city = matches[2]
local wtext = get_weather(city)
if not wtext then
wtext = 'مکان وارد شده صحیح نیست'
end
return wtext
end
---------------------
if matches[1] == 'time' or matches[1] =='زمان' then
local url , res = http.request('http://api.gpmod.ir/time/')
if res ~= 200 then
return "No connection"
end
local colors = {'blue','green','yellow','magenta','Orange','DarkOrange','red'}
local fonts = {'mathbf','mathit','mathfrak','mathrm'}
local jdat = json:decode(url)
local url = 'http://latex.codecogs.com/png.download?'..'\\dpi{600}%20\\huge%20\\'..fonts[math.random(#fonts)]..'{{\\color{'..colors[math.random(#colors)]..'}'..jdat.ENtime..'}}'
local file = download_to_file(url,'time.webp')
send_document(get_receiver(msg) , file, ok_cb, false)
end
--------------------
if matches[1] == 'voice'or matches[1] == 'وویس' then
local text = matches[2]
local b = 1
while b ~= 0 do
textc = text:trim()
text,b = text:gsub(' ','.')
if msg.to.type == 'user' then
return nil
else
local url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..textc
local receiver = get_receiver(msg)
local file = download_to_file(url,'mohamad.ogg')
send_audio('channel#id'..msg.to.id, file, ok_cb , false)
end
end
end
--------------------------
if matches[1] == "tr" then
url = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a&format=plain&lang='..URL.escape(matches[2])..'&text='..URL.escape(matches[3]))
data = json:decode(url)
return 'زبان : '..data.lang..'\nترجمه : '..data.text[1]..'\n____________________\n'
end
-----------------------
if matches[1] == 'short'or matches[1] == 'کوتاه کردن' then
local yon = http.request('http://api.yon.ir/?url='..URL.escape(matches[2]))
local jdat = json:decode(yon)
local bitly = https.request('https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl='..URL.escape(matches[2]))
local data = json:decode(bitly)
local yeo = http.request('http://yeo.ir/api.php?url='..URL.escape(matches[2])..'=')
local opizo = http.request('http://api.gpmod.ir/shorten/?url='..URL.escape(matches[2])..'&username=mersad565@gmail.com')
local u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(matches[2]))
local llink = http.request('http://llink.ir/yourls-api.php?signature=a13360d6d8&action=shorturl&url='..URL.escape(matches[2])..'&format=simple')
return ' 🌐لینک اصلی :\n'..data.data.long_url..'\n\nلینکهای کوتاه شده با 6 سایت کوتاه ساز لینک : \n》کوتاه شده با bitly :\n___________________________\n'..data.data.url..'\n___________________________\n》کوتاه شده با yeo :\n'..yeo..'\n___________________________\n》کوتاه شده با اوپیزو :\n'..opizo..'\n___________________________\n》کوتاه شده با u2s :\n'..u2s..'\n___________________________\n》کوتاه شده با llink : \n'..llink..'\n___________________________\n》لینک کوتاه شده با yon : \nyon.ir/'..jdat.output..'\n____________________\n'
end
------------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'document' and redis:get("sticker:photo") then
if redis:set("sticker:photo", "waiting") then
end
end
if matches[1]:lower() == "photo"or matches[1] == 'عکس' then
redis:get("sticker:photo")
send_large_msg(receiver, '', ok_cb, false)
load_document(msg.reply_id, toimage, msg)
end
end
------------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'photo' and redis:get("photo:sticker") then
if redis:set("photo:sticker", "waiting") then
end
end
if matches[1]:lower() == "sticker" or matches[1] =="استیکر" then
redis:get("photo:sticker")
send_large_msg(receiver, '', ok_cb, false)
load_photo(msg.reply_id, tosticker, msg)
end
end
-------------------------
-------------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'video' or matches[1] =='فیلم' and redis:get("video:audio") then
if redis:set("video:audio", "waiting") then
end
end
if matches[1]:lower() == "audio" or matches[1] =="آهنگ" then
redis:get("video:audio")
send_large_msg(receiver, '', ok_cb, false)
load_audio(msg.reply_id, toaudio, msg)
end
end
-----------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'document' and redis:get("gif:video") then
if redis:set("gif:video", "waiting") then
end
end
if matches[1]:lower() == "video" or matches[1] =="فیلم" then
redis:get("gif:video")
send_large_msg(receiver, '', ok_cb, false)
load_document(msg.reply_id, tovideo, msg)
end
end
------------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'video' and redis:get("video:document") then
if redis:set("video:document", "waiting") then
end
end
if matches[1]:lower() == "mkv" then
redis:get("video:document")
send_large_msg(receiver, '', ok_cb, false)
load_video(msg.reply_id, tomkv, msg)
end
end
------------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'video' and redis:get("video:gif") then
if redis:set("video:gif", "waiting") then
end
end
if matches[1]:lower() == "gif" or matches[1] =="گیف" then
redis:get("video:gif")
send_large_msg(receiver, '', ok_cb, false)
load_video(msg.reply_id, togif, msg)
end
end
------------------------
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
if msg.to.type == 'photo' and redis:get("photo:sticker") then
if redis:set("photo:png", "waiting") then
end
end
if matches[1]:lower() == "png" then
redis:get("photo:png")
send_large_msg(receiver, '', ok_cb, false)
load_photo(msg.reply_id, topng, msg)
end
end
------------------------
if matches[1] == "delplugin" and is_sudo(msg) then
if not is_sudo(msg) then
return "You Are Not Allow To Delete Plugins!"
end
io.popen("cd plugins && rm "..matches[2]..".lua")
return "Delete plugin by "..msg.from.id.." is successful"
end
---------------------
if matches[1] == "sticker"or matches[1] =="استیکر" then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "150"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = get_receiver(msg)
local file = download_to_file(url,'text.webp')
send_document('channel#id'..msg.to.id, file, ok_cb , false)
end
--------------------------
if matches[1] == "gif"or matches[1] =="گیف" then
local text = URL.escape(matches[2])
local url2 = 'http://www.flamingtext.com/net-fu/image_output.cgi?_comBuyRedirect=false&script=blue-fire&text='..text..'&symbol_tagname=popular&fontsize=70&fontname=futura_poster&fontname_tagname=cool&textBorder=15&growSize=0&antialias=on&hinting=on&justify=2&letterSpacing=0&lineSpacing=0&textSlant=0&textVerticalSlant=0&textAngle=0&textOutline=off&textOutline=false&textOutlineSize=2&textColor=%230000CC&angle=0&blueFlame=on&blueFlame=false&framerate=75&frames=5&pframes=5&oframes=4&distance=2&transparent=off&transparent=false&extAnim=gif&animLoop=on&animLoop=false&defaultFrameRate=75&doScale=off&scaleWidth=240&scaleHeight=120&&_=1469943010141'
local title , res = http.request(url2)
local jdat = json:decode(title)
local gif = jdat.src
local file = download_to_file(gif,'t2g.gif')
send_document(get_receiver(msg), file, ok_cb, false)
end
---------------------------
if matches[1] == "stickerpro"or matches[1] =="استیکرنوشته" then
local text1 = ""
local text2 = matches[2]
local text3 = matches[3]
if not matches[2] then
text2 = " "
end
if not matches[3] then
text3 = " "
end
if not matches[2] and not matches[3] then
text2 = " "
text3 = " "
end
text4 = "[pika]"
local url = URL.escape(text1.." "..text2.." "..text3)
local answers = {'https://assets.imgix.net/examples/clouds.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/redleaf.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/blueberries.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/butterfly.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/espresso.jpg?blur=200&w=1000&h=400&fit=crop&txt=',
'https://assets.imgix.net/unsplash/transport.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/unsplash/coffee.JPG?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/unsplash/citystreet.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'http://assets.imgix.net/examples/vista.png?blur=200&w=1300&h=600&fit=crop&txt='}
local fonts = {'American%20Typewriter%2CBold','Arial%2CBoldItalicMT','Arial%2CBoldMT','Athelas%2CBold',
'Baskerville%2CBoldItalic','Charter%2CBoldItalic','DIN%20Alternate%2CBold','Gill%20Sans%2CUltraBold',
'PT%20Sans%2CBold','Seravek%2CBoldItalic','Verdana%2CBold','Yuanti%20SC%2CBold','Avenir%20Next%2CBoldItalic',
'Lucida%20Grande%2CBold','American%20Typewriter%20Condensed%2CBold','rial%20Rounded%20MT%2CBold','Chalkboard%20SE%2CBold',
'Courier%20New%2CBoldItalic','Charter%20Black%2CItalic','American%20Typewriter%20Light'}
local colors = {'00FF00','6699FF','CC99CC','CC66FF','0066FF','000000','CC0066','FF33CC','FF0000','FFCCCC','FF66CC','33FF00','FFFFFF','00FF00'}
local f = fonts[math.random(#fonts)]
local c = colors[math.random(#colors)]
local url = answers[math.random(#answers)]..url.."&txtsize=120&txtclr="..c.."&txtalign=middle,center&txtfont="..f.."%20Condensed%20Medium&mono=ff6598cc=?markscale=60&markalign=center%2Cdown"
local randoms = math.random(1000,900000)
local randomd = randoms..".webp"
local cb_extra = {file_path=file}
local receiver = get_receiver(msg)
local file = download_to_file(url,randomd)
send_document(receiver, file, rmtmp_cb, cb_extra)
end
--------------------------
if matches[1] == "imagepro"or matches[1] =="عکس نوشته" then
local text1 = ""
local text2 = matches[2]
local text3 = matches[3]
if not matches[2] then
text2 = " "
end
if not matches[3] then
text3 = " "
end
if not matches[2] and not matches[3] then
text2 = " "
text3 = " "
end
text4 = "[pika]"
local url = URL.escape(text1.." "..text2.." "..text3)
local answers = {'https://assets.imgix.net/examples/clouds.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/redleaf.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/blueberries.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/butterfly.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/examples/espresso.jpg?blur=200&w=1000&h=400&fit=crop&txt=',
'https://assets.imgix.net/unsplash/transport.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/unsplash/coffee.JPG?blur=200&w=1300&h=600&fit=crop&txt=',
'https://assets.imgix.net/unsplash/citystreet.jpg?blur=200&w=1300&h=600&fit=crop&txt=',
'http://assets.imgix.net/examples/vista.png?blur=200&w=1300&h=600&fit=crop&txt='}
local fonts = {'American%20Typewriter%2CBold','Arial%2CBoldItalicMT','Arial%2CBoldMT','Athelas%2CBold',
'Baskerville%2CBoldItalic','Charter%2CBoldItalic','DIN%20Alternate%2CBold','Gill%20Sans%2CUltraBold',
'PT%20Sans%2CBold','Seravek%2CBoldItalic','Verdana%2CBold','Yuanti%20SC%2CBold','Avenir%20Next%2CBoldItalic',
'Lucida%20Grande%2CBold','American%20Typewriter%20Condensed%2CBold','rial%20Rounded%20MT%2CBold','Chalkboard%20SE%2CBold',
'Courier%20New%2CBoldItalic','Charter%20Black%2CItalic','American%20Typewriter%20Light'}
local colors = {'00FF00','6699FF','CC99CC','CC66FF','0066FF','000000','CC0066','FF33CC','FF0000','FFCCCC','FF66CC','33FF00','FFFFFF','00FF00'}
local f = fonts[math.random(#fonts)]
local c = colors[math.random(#colors)]
local url = answers[math.random(#answers)]..url.."&txtsize=120&txtclr="..c.."&txtalign=middle,center&txtfont="..f.."%20Condensed%20Medium&mono=ff6598cc=?markscale=60&markalign=center%2Cdown"
local randoms = math.random(1000,900000)
local randomd = randoms..".jpg"
local cb_extra = {file_path=file}
local receiver = get_receiver(msg)
local file = download_to_file(url,randomd)
send_photo(receiver, file, rmtmp_cb, cb_extra)
end
---------------------
if matches[1] == 'love'or matches[1] == 'عشق' then
local text1 = matches[1]
local text2 = matches[2]
local url = "http://www.iloveheartstudio.com/-/p.php?t="..text1.."%20%EE%BB%AE%20"..text2.."&bc=FFFFFF&tc=000000&hc=ff0000&f=c&uc=true&ts=true&ff=PNG&w=500&ps=sq"
local file = download_to_file(url,'love.webp')
send_document(get_receiver(msg), file, ok_cb, false)
end
--------------------
if matches[1] == "get" then
local file = matches[2]
if is_sudo(msg) or is_vip(msg) then
local receiver = get_receiver(msg)
send_document(receiver, "./plugins/"..file..".lua", ok_cb, false)
end
end
--------------------
if matches[1] == "note" and matches[2] then
local text = matches[2]
local b = 1
while b ~= 0 do
text = text:trim()
text,b = text:gsub('^!+','')
end
local file = io.open("./system/adv/note/"..msg.from.id..".txt", "w")
file:write(text)
file:flush()
file:close()
return "You can use it:\n!mynote\n\nYour note has been changed to:\n"..text
end
if matches[1] == "mynote" then
local note = io.open("./system/adv/note/"..msg.from.id..".txt", "r")
local mn = note:read("*all")
if matches[1] == "mynote" then
return mn
else
return "You havent any note."
end
end
--------------------
-------------------
-------------------
if matches[1] == 'broadcast' then
if is_sudo(msg) then -- Only sudo !
local data = load_data(_config.moderation.data)
local groups = 'groups'
local response = matches[2]
for k,v in pairs(data[tostring(groups)]) do
chat_id = v
local chat = 'chat#id'..chat_id
local channel = 'channel#id'..chat_id
send_large_msg(chat, response)
send_large_msg(channel, response)
end
end
end
--------------------
if matches[1]:lower() == 'app' then
local url = http.request('http://api.magic-team.ir/plazza/search.php?key='..URL.escape(matches[2]))
local jdat = json:decode(url)
items = jdat
local text = ''
local msgss = 0
for item in pairs(items) do
msgss = msgss + 1
text = text..msgss..' 📦 عنوان: '..items[msgss].title..' 🔰 Package Id: '..items[msgss].pack..'\n\n'
local hash = 'app:'..msg.from.id..msgss
local hash1 = 'img:'..msg.from.id..msgss
redis:set(hash, items[msgss].pack)
redis:set(hash1, items[msgss].icon)
end
return text..'برای دریافت اطلاعات برنامه از دستور زیر استفاده کنید\n/appinfo number\n(example): /appinfo 1'
end
if matches[1]:lower() == 'appinfo' then
local hash = 'app:'..msg.from.id..matches[2]
local hash1 = 'img:'..msg.from.id..matches[2]
pp = redis:get(hash)
pp1 = redis:get(hash1)
local url = http.request('http://api.magic-team.ir/plazza/info.php?key='..pp)
local jdat = json:decode(url)
if jdat.needroot == "false" then
root = 'خیر'
else
root = 'بله'
end
ple = math.floor(jdat.dlsize / 1024)
text = 'عنوان: \n'..jdat.title..'\nنام پکیج :\n'..pp..'\nدرباره: \n'..jdat.info..'\nورژن: \n'..jdat.version..'\nنیاز به روت : '..root..'\nسایز : '..ple..'\n تصویر : '..pp1..'\nلینک دانلود : '..jdat.dlurl
return text
end
--------------------
if matches[1] == "news" or matches[1] =="اخبار" then
local url = http.request('http://api.avirateam.ir/irna/cli/index.php?pass=dN@-Sy1k$mKB2PgWoj)7/9vbDL0VCpfA')
return url
end
--------------------
if matches[1] == "mobile"or matches[1] == 'جدیدترین موبایل ها' then
local pass = 'dram1135'
local url = 'http://api.avirateam.ir/mobile/cli/index.php?pass='..pass
local req = http.request(url)
return req..' @antispamandhack'
end
--------------------
if matches[1] == "alexa" then
local url = http.request('http://api.tarfandbazar.ir/alexa.php?url='..matches[2]..'')
local photo = 'http://api.tarfandbazar.ir/alexaphoto.php?url='..matches[2]
return url.."\n\n"..photo
end
--------------------
if matches[1] == "earz"or matches[1] == 'معادل' then
local url = 'http://exchange.nalbandan.com/api.php?action=json'
local jstr, res = http.request(url)
local arz = json:decode(jstr)
local text = 'مبلغ مورد نظر شما : '..matches[2]..' هزار تومان است که '
text = text..'\nمعادل '..arz.dollar.value * matches[2]..' دلار'
text = text..'\nمعادل '..arz.dollar_rasmi.value * matches[2]..' دلار رسمی'
text = text..'\nمعادل '..arz.euro.value * matches[2]..' یورو'
text = text..'\nمعادل '..arz.derham.value * matches[2]..' درهم'
text = text..'\nمعادل '..arz.pond.value * matches[2]..' پوند میباشد'
return text
end
--------------------
if matches[1]:lower() == 'del'or matches[1] =='' then
if not is_sudo(msg) then
return ""
end
if matches[2] == 'gbanlist' then
local hash = 'gbanned'
send_large_msg(get_receiver(msg), "لیست سوپر بن پاک شد.")
redis:del(hash)
end
end
----------------------
if matches[1] == "rev" then
local rev = string.reverse(matches[1])
return "Reverse:\n"..rev
end
---------------------
if matches[1] == "let" then
local let = string.len(matches[1])
return "Letters:\n"..let
end
------------------
if matches[1]:lower() == 'aparat'or matches[1] =='جستجوی' then
local url = http.request('http://www.aparat.com/etc/api/videoBySearch/text/'..URL.escape(matches[2]))
local jdat = json:decode(url)
local items = jdat.videobysearch
text = 'نتیجه جستوجو در آپارات: \n'
for i = 1, #items do
text = text..'\n'..i..'- '..items[i].title..' - تعداد بازدید: '..items[i].visit_cnt..'\n لینک: aparat.com/v/'..items[i].uid
end
text = text..'\n'
return text
end
--------------------
if matches[1]:lower() == 'joke' then
local database = 'http://vip.opload.ir/vipdl/94/11/amirhmz/'
local res = http.request(database.."joke.db")
local joke = res:split(",")
return joke[math.random(#joke)]
end
--------------
if matches[1] == "photo"or matches[1] =="عکس" then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "150"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = get_receiver(msg)
local file = download_to_file(url,'text.jpg')
send_photo('channel#id'..msg.to.id, file, ok_cb , false)
end
end
end
return {
patterns = {
"^[!/#]([Mm][Oo][Bb][Ii][Ll][Ee])$",
"^[!#/](جدیدترین موبایل ها)$",
"^[/#!](aparat) (.*)$",
"^[!#/](جستجوی) (.*)$",
"[/!#]rev (.*)",
"[/!#]let (.*)",
"[!/#]([Dd]el) (.*)$",
'^[#!/]([Aa]bout) (.*)$',
"^[/#!](earz) (%d+)$",
"^[!#/](معادل) (%d+)$",
"^[/#!]alexa (.*)$",
"^[!/#]([Nn][Ee][Ww][Ss])$",
"^[!#/](اخبار)$",
"^[/#!](app) (.*)$",
"^[/#!](appinfo) (.*)$",
"^[#!/](broadcast) +(.+)$",
--"^[!/#]([Ff]ile) (.*) (.*)$",
"^[!/#](get) (.*)$",
"^[#!/]([Aa]ddplugin) (.+) (.*)$",
"^[#!/]([Dd]l) ([Pp]lugin) (.*)$",
"^[!#/](حذف پیام) (%d*)$",
"^[!#/]([Dd]elplugin) (.*)$",
"^[#!/](calc) (.*)$",
"^[!#/](ماشین حساب) (.*)$",
"^[#!/](time)$",
"^[#!/](زمان)$",
-- "^[#!/](info)$",
-- "^[#!/](me)$",
"^[!/#](voice) +(.*)$",
"^[!#/](وویس) +(.*)$",
"^[!/#]([Mm]ean) (.*)$",
"^[!#/]([Ss]hort) (.*)$",
"^[!#/](کوتاه کردن) (.*)$",
"^[#!/]([Ss]ticker)$",
"^[#!/](photo)$",
"^[#!/](gif)$",
"^[#!/](video)$",
"^[#!/](mkv)$",
"^[#!/](audio)$",
"^[#!/](love) (.+) (.+)$",
"^[!#/](استیکر)$",
"^[!#/](عکس)$",
"^[!#/](گیف)$",
"^[!#/](فیلم)$",
"^[!#/](آهنگ)$",
"^[!#/](عشق) (.+) (.+)$",
"^[#!/](gif) (.*)$",
"^[#!/](stickerpro) (.+)$",
"^[!#/]([Nn]ote) (.*)$",
"^[!#/]([Mm]ynote)$",
"^[#!/](stickerpro) (.+) (.+)$",
"^[#!/](stickerpro) (.+) (.+) (.+)$",
"^[#!/](stickerpro) (.+) (.+) (.+) (.+)$",
"^[#!/](imagepro) (.+)$",
"^[!#/](عکس نوشته) (.+)$",
"^[!#/](استیکرنوشته) (.+) (.+)$",
"^[!#/](استیکرنوشته) (.+) (.+) (.+)$",
"^[!#/](استیکرنوشته) (.+) (.+) (.+) (.+)$",
"^[!#/](گیف) (.*)$",
"^[!#/](استیکرنوشته) (.+)$",
"^[!#/](استیکر)$",
"^[!#/](عکس)$",
"^[#!/](imagepro) (.+) (.+)$",
"^[#!/](imagepro) (.+) (.+) (.+)$",
"^[#!/](imagepro) (.+) (.+) (.+) (.+)$",
"^[#!/](png)$",
"^([Pp]hoto)$",
"^[!#/](عکس)$",
"^[!#/](استیکر)$",
"^[!#/](استیکر) (.*)$",
"^[!#/](عکس نوشته) (.+) (.+)$",
"^[!#/](عکس نوشته) (.+) (.+) (.+)$",
"^[!#/](عکس نوشته) (.+) (.+) (.+) (.+)$",
"^([Ss]ticker)$",
"^([Ss]ticker) (.*)$",
"^([Pp]hoto) (.*)$",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
},
run = run,
}
-- @antispamandhack
-- باز نویسی توسط @sudo1
-- ادیت توسط @mrr619 | agpl-3.0 |
zhuhangyu/ABTestingGateway | lib/abtesting/error/errcode.lua | 22 | 1583 | local modulename = 'abtestingErrorInfo'
local _M = {}
_M._VERSION = '0.0.1'
_M.info = {
-- index code desc
-- SUCCESS
["SUCCESS"] = { 200, 'success '},
-- System Level ERROR
['REDIS_ERROR'] = { 40101, 'redis error for '},
['POLICY_DB_ERROR'] = { 40102, 'policy in db error '},
['RUNTIME_DB_ERROR'] = { 40103, 'runtime info in db error '},
['LUA_RUNTIME_ERROR'] = { 40201, 'lua runtime error '},
['BLANK_INFO_ERROR'] = { 40202, 'errinfo blank in handler '},
-- Service Level ERROR
-- input or parameter error
['PARAMETER_NONE'] = { 50101, 'expected parameter for '},
['PARAMETER_ERROR'] = { 50102, 'parameter error for '},
['PARAMETER_NEEDED'] = { 50103, 'need parameter for '},
['PARAMETER_TYPE_ERROR'] = { 50104, 'parameter type error for '},
-- input policy error
['POLICY_INVALID_ERROR'] = { 50201, 'policies invalid for ' },
['POLICY_BUSY_ERROR'] = { 50202, 'policy is busy and policyID is ' },
-- redis connect error
['REDIS_CONNECT_ERROR'] = { 50301, 'redis connect error for '},
['REDIS_KEEPALIVE_ERROR'] = { 50302, 'redis keepalive error for '},
-- runtime error
['POLICY_BLANK_ERROR'] = { 50401, 'policy contains no data '},
['RUNTIME_BLANK_ERROR'] = { 50402, 'expect runtime info for '},
['MODULE_BLANK_ERROR'] = { 50403, 'no required module for '},
['USERINFO_BLANK_ERROR'] = { 50404, 'no userinfo fetched from '},
-- unknown reason
['UNKNOWN_ERROR'] = { 50501, 'unknown reason '},
}
return _M
| mit |
rlcevg/Zero-K | LuaRules/Configs/StartBoxes/Terra.lua | 1 | 2335 | local layout = {
[0] = {{
{Game.mapSizeX / 2, 1},
{0, 1},
{0, 2233.623046875},
{59.700881958008, 2221.083984375},
{151.52703857422, 2230.8056640625},
{261.55853271484, 2215.4636230469},
{426.48919677734, 2209.6975097656},
{575.38916015625, 2204.8198242188},
{710.96252441406, 2178.3088378906},
{887.04809570313, 2102.4580078125},
{1026.9443359375, 2061.7414550781},
{1207.2326660156, 2041.4616699219},
{1329.3731689453, 2044.3474121094},
{1377.5572509766, 2056.9152832031},
{1439.2751464844, 2042.11328125},
{1493.8967285156, 1999.1975097656},
{1552.9796142578, 1958.8890380859},
{1652.7087402344, 1949.1638183594},
{1867.1486816406, 1951.6938476563},
{2049.1938476563, 1977.9096679688},
{2213.1767578125, 1989.9997558594},
{2425.9243164063, 1944.3190917969},
{2541.1896972656, 1873.3225097656},
{2667.5539550781, 1730.0690917969},
{2818.4304199219, 1612.1125488281},
{2973.16796875, 1529.4005126953},
{3096.7036132813, 1468.0083007813},
{3264.8745117188, 1429.5474853516},
{3410.97265625, 1416.5157470703},
{3539.0751953125, 1436.7961425781},
{3661.8193359375, 1475.3693847656},
{3788.0444335938, 1536.0512695313},
{3943.1005859375, 1568.7149658203},
{4080.9250488281, 1614.5035400391},
{4209.1069335938, 1661.9660644531},
{4301.833984375, 1740.7491455078},
{4402.5595703125, 1830.8984375},
{4480.4130859375, 1903.6414794922},
{4643.1669921875, 1997.1549072266},
{4737.5502929688, 2077.0715332031},
{4876.8369140625, 2148.4423828125},
{5051.58984375, 2193.7766113281},
{5212.0249023438, 2204.3935546875},
{5383.8452148438, 2184.8349609375},
{5559.373046875, 2148.1403808594},
{5737.6186523438, 2120.4594726563},
{5913.1743164063, 2123.4367675781},
{6019.5913085938, 2158.5681152344},
{Game.mapSizeX, 2186.7470703125},
{Game.mapSizeX, 1},
}},
[1] = {{ }}, -- mirrored automatically
}
local startpos = {
[0] = {
{3333, 623},
{2400, 1490},
{ 984, 427},
{5638, 590},
},
[1] = {} -- mirrored
}
for i = 1, #layout[0][1] do
layout[1][1][i] = { Game.mapSizeX - layout[0][1][i][1], Game.mapSizeZ - layout[0][1][i][2] }
end
for i = 1, #startpos[0] do
startpos[1][i] = { Game.mapSizeX - startpos[0][i][1], Game.mapSizeZ - startpos[0][i][2]}
end
return layout, startpos, {2} | gpl-2.0 |
joaocc/ta3d-git | src/ta3d/src/luajit/src/host/genminilua.lua | 73 | 11943 | ----------------------------------------------------------------------------
-- Lua script to generate a customized, minified version of Lua.
-- The resulting 'minilua' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local sub, match, gsub = string.sub, string.match, string.gsub
local LUA_VERSION = "5.1.5"
local LUA_SOURCE
local function usage()
io.stderr:write("Usage: ", arg and arg[0] or "genminilua",
" lua-", LUA_VERSION, "-source-dir\n")
os.exit(1)
end
local function find_sources()
LUA_SOURCE = arg and arg[1]
if not LUA_SOURCE then usage() end
if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end
local fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then
LUA_SOURCE = LUA_SOURCE.."src/"
fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then usage() end
end
local all = fp:read("*a")
fp:close()
if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then
io.stderr:write("Error: version mismatch\n")
usage()
end
end
local LUA_FILES = {
"lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c",
"lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c",
"llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c",
"lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c",
}
local REMOVE_LIB = {}
gsub([[
collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset
select tostring xpcall
foreach foreachi getn maxn setn
popen tmpfile seek setvbuf __tostring
clock date difftime execute getenv rename setlocale time tmpname
dump gfind len reverse
LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME
]], "%S+", function(name)
REMOVE_LIB[name] = true
end)
local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, }
local CUSTOM_MAIN = [[
typedef unsigned int UB;
static UB barg(lua_State *L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State *L){
BRET(barg(L,1))}
static int bnot(lua_State *L){
BRET(~barg(L,1))}
static int band(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State *L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State *L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char *hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[] = {
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc, char **argv){
lua_State *L = luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L, "bit", bitlib);
if (argc < 2) return sizeof(void *);
lua_createtable(L, 0, 1);
lua_pushstring(L, argv[1]);
lua_rawseti(L, -2, 0);
lua_setglobal(L, "arg");
if (luaL_loadfile(L, argv[1]))
goto err;
for (i = 2; i < argc; i++)
lua_pushstring(L, argv[i]);
if (lua_pcall(L, argc - 2, 0, 0)) {
err:
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
lua_close(L);
return 0;
}
]]
local function read_sources()
local t = {}
for i, name in ipairs(LUA_FILES) do
local fp = assert(io.open(LUA_SOURCE..name, "r"))
t[i] = fp:read("*a")
assert(fp:close())
end
t[#t+1] = CUSTOM_MAIN
return table.concat(t)
end
local includes = {}
local function merge_includes(src)
return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name)
if includes[name] then return "" end
includes[name] = true
local fp = assert(io.open(LUA_SOURCE..name, "r"))
local src = fp:read("*a")
assert(fp:close())
src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "")
src = gsub(src, "#endif%s*$", "")
return merge_includes(src)
end)
end
local function get_license(src)
return match(src, "/%*+\n%* Copyright %(.-%*/\n")
end
local function fold_lines(src)
return gsub(src, "\\\n", " ")
end
local strings = {}
local function save_str(str)
local n = #strings+1
strings[n] = str
return "\1"..n.."\2"
end
local function save_strings(src)
src = gsub(src, '"[^"\n]*"', save_str)
return gsub(src, "'[^'\n]*'", save_str)
end
local function restore_strings(src)
return gsub(src, "\1(%d+)\2", function(numstr)
return strings[tonumber(numstr)]
end)
end
local function def_istrue(def)
return def == "INT_MAX > 2147483640L" or
def == "LUAI_BITSINT >= 32" or
def == "SIZE_Bx < LUAI_BITSINT-1" or
def == "cast" or
def == "defined(LUA_CORE)" or
def == "MINSTRTABSIZE" or
def == "LUA_MINBUFFER" or
def == "HARDSTACKTESTS" or
def == "UNUSED"
end
local head, defs = {[[
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
]]}, {}
local function preprocess(src)
local t = { match(src, "^(.-)#") }
local lvl, on, oldon = 0, true, {}
for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do
if pp == "if" or pp == "ifdef" or pp == "ifndef" then
lvl = lvl + 1
oldon[lvl] = on
on = def_istrue(def)
elseif pp == "else" then
if oldon[lvl] then
if on == false then on = true else on = false end
end
elseif pp == "elif" then
if oldon[lvl] then
on = def_istrue(def)
end
elseif pp == "endif" then
on = oldon[lvl]
lvl = lvl - 1
elseif on then
if pp == "include" then
if not head[def] and not REMOVE_EXTINC[def] then
head[def] = true
head[#head+1] = "#include "..def.."\n"
end
elseif pp == "define" then
local k, sp, v = match(def, "([%w_]+)(%s*)(.*)")
if k and not (sp == "" and sub(v, 1, 1) == "(") then
defs[k] = gsub(v, "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
else
t[#t+1] = "#define "..def.."\n"
end
elseif pp ~= "undef" then
error("unexpected directive: "..pp.." "..def)
end
end
if on then t[#t+1] = txt end
end
return gsub(table.concat(t), "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
end
local function merge_header(src, license)
local hdr = string.format([[
/* This is a heavily customized and minimized copy of Lua %s. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
]], LUA_VERSION)
return hdr..license..table.concat(head)..src
end
local function strip_unused1(src)
return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func)
return REMOVE_LIB[func] and "" or line
end)
end
local function strip_unused2(src)
return gsub(src, "Symbolic Execution.-}=", "")
end
local function strip_unused3(src)
src = gsub(src, "extern", "static")
src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(")
src = gsub(src, "#define lua_assert[^\n]*\n", "")
src = gsub(src, "lua_assert%b();?", "")
src = gsub(src, "default:\n}", "default:;\n}")
src = gsub(src, "lua_lock%b();", "")
src = gsub(src, "lua_unlock%b();", "")
src = gsub(src, "luai_threadyield%b();", "")
src = gsub(src, "luai_userstateopen%b();", "{}")
src = gsub(src, "luai_userstate%w+%b();", "")
src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser")
src = gsub(src, "trydecpoint%(ls,seminfo%)",
"luaX_lexerror(ls,\"malformed number\",TK_NUMBER)")
src = gsub(src, "int c=luaZ_lookahead%b();", "")
src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;",
"return 1;")
src = gsub(src, "getfuncname%b():", "NULL:")
src = gsub(src, "getobjname%b():", "NULL:")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "")
src = gsub(src, "(twoto%b()%()", "%1(size_t)")
src = gsub(src, "i<sizenode", "i<(int)sizenode")
return gsub(src, "\n\n+", "\n")
end
local function strip_comments(src)
return gsub(src, "/%*.-%*/", " ")
end
local function strip_whitespace(src)
src = gsub(src, "^%s+", "")
src = gsub(src, "%s*\n%s*", "\n")
src = gsub(src, "[ \t]+", " ")
src = gsub(src, "(%W) ", "%1")
return gsub(src, " (%W)", "%1")
end
local function rename_tokens1(src)
src = gsub(src, "getline", "getline_")
src = gsub(src, "struct ([%w_]+)", "ZX%1")
return gsub(src, "union ([%w_]+)", "ZY%1")
end
local function rename_tokens2(src)
src = gsub(src, "ZX([%w_]+)", "struct %1")
return gsub(src, "ZY([%w_]+)", "union %1")
end
local function func_gather(src)
local nodes, list = {}, {}
local pos, len = 1, #src
while pos < len do
local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos)
if d then
local n = #list+1
list[n] = d
nodes[w] = n
else
local s
d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos)
if not d then
d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos)
if not d then d = match(src, "^[^\n]*\n", pos) end
end
if s == "{" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
if sub(d, -2) == "{\n" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
end
end
local k, v = nil, d
if w == "typedef" then
if match(d, "^typedef enum") then
head[#head+1] = d
else
k = match(d, "([%w_]+);\n$")
if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end
end
elseif w == "enum" then
head[#head+1] = v
elseif w ~= nil then
k = match(d, "^[^\n]-([%w_]+)[(%[=]")
if k then
if w ~= "static" and k ~= "main" then v = "static "..d end
else
k = w
end
end
if w and k then
local o = nodes[k]
if o then nodes["*"..k] = o end
local n = #list+1
list[n] = v
nodes[k] = n
end
end
pos = pos + #d
end
return nodes, list
end
local function func_visit(nodes, list, used, n)
local i = nodes[n]
for m in string.gmatch(list[i], "[%w_]+") do
if nodes[m] then
local j = used[m]
if not j then
used[m] = i
func_visit(nodes, list, used, m)
elseif i < j then
used[m] = i
end
end
end
end
local function func_collect(src)
local nodes, list = func_gather(src)
local used = {}
func_visit(nodes, list, used, "main")
for n,i in pairs(nodes) do
local j = used[n]
if j and j < i then used["*"..n] = j end
end
for n,i in pairs(nodes) do
if not used[n] then list[i] = "" end
end
return table.concat(list)
end
find_sources()
local src = read_sources()
src = merge_includes(src)
local license = get_license(src)
src = fold_lines(src)
src = strip_unused1(src)
src = save_strings(src)
src = strip_unused2(src)
src = strip_comments(src)
src = preprocess(src)
src = strip_whitespace(src)
src = strip_unused3(src)
src = rename_tokens1(src)
src = func_collect(src)
src = rename_tokens2(src)
src = restore_strings(src)
src = merge_header(src, license)
io.write(src)
| gpl-2.0 |
soniccol/OpenRedAlert_TW | mods/common/lua/supportpowers.lua | 3 | 1963 | SupportPowers = { }
SupportPowers.Airstrike = function(owner, planeName, enterLocation, bombLocation)
local facing = { Map.GetFacing(CPos.op_Subtraction(bombLocation, enterLocation), 0), "Int32" }
local center = WPos.op_Addition(Map.CenterOfCell(enterLocation), WVec.New(0, 0, Rules.InitialAltitude(planeName)))
local plane = Actor.Create(planeName, { Location = enterLocation, Owner = owner, Facing = facing, CenterPosition = center })
local bombLoc = Map.CenterOfCell(bombLocation)
Actor.Trait(plane, "AttackBomber"):SetTarget(bombLoc)
Actor.Fly(plane, bombLoc)
Actor.FlyOffMap(plane)
Actor.RemoveSelf(plane)
return plane
end
SupportPowers.Paradrop = function(owner, planeName, passengerNames, enterLocation, dropLocation)
local facing = { Map.GetFacing(CPos.op_Subtraction(dropLocation, enterLocation), 0), "Int32" }
local center = WPos.op_Addition(Map.CenterOfCell(enterLocation), WVec.New(0, 0, Rules.InitialAltitude(planeName)))
local plane = Actor.Create(planeName, { Location = enterLocation, Owner = owner, Facing = facing, CenterPosition = center })
Actor.Fly(plane, Map.CenterOfCell(dropLocation))
Actor.Trait(plane, "ParaDrop"):SetLZ(dropLocation, true)
Actor.FlyOffMap(plane)
Actor.RemoveSelf(plane)
local cargo = Actor.Trait(plane, "Cargo")
local passengers = { }
for i, passengerName in ipairs(passengerNames) do
local passenger = Actor.Create(passengerName, { AddToWorld = false, Owner = owner })
passengers[i] = passenger
cargo:Load(plane, passenger)
end
return plane, passengers
end
SupportPowers.Chronoshift = function(unitLocationPairs, chronosphere, duration, killCargo)
duration = duration or -1
killCargo = killCargo or true
Utils.Do(unitLocationPairs, function(pair)
local unit = pair[1]
local cell = pair[2]
local cs = Actor.TraitOrDefault(unit, "Chronoshiftable")
if cs ~= nil and cs:CanChronoshiftTo(unit, cell) then
cs:Teleport(unit, cell, duration, killCargo, chronosphere)
end
end)
end
| gpl-3.0 |
VladimirTyrin/wireshark | epan/wslua/dtd_gen.lua | 38 | 8369 | -- dtd_gen.lua
--
-- a DTD generator for wireshark
--
-- (c) 2006 Luis E. Garcia Ontanon <luis@ontanon.org>
--
-- Wireshark - Network traffic analyzer
-- By Gerald Combs <gerald@wireshark.org>
-- Copyright 1998 Gerald Combs
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
if gui_enabled() then
local xml_fld = Field.new("xml")
local function dtd_generator()
local displayed = {} -- whether or not a dtd is already displayed
local dtds = {} -- the dtds
local changed = {} -- whether or not a dtd has been modified
local dtd -- the dtd being dealt with
local dtd_name -- its name
-- we'll tap onto every frame that has xml
local ws = {} -- the windows for each dtd
local w = TextWindow.new("DTD Generator")
local function help()
local wh = TextWindow.new("DTD Generator Help")
-- XXX write help
wh:set('DTD Generator Help\n')
end
local function get_dtd_from_xml(text,d,parent)
-- obtains dtd information from xml
-- text: xml to be parsed
-- d: the current dtd (if any)
-- parent: parent entity (if any)
-- cleanup the text from useless chars
text = string.gsub(text ,"%s*<%s*","<");
text = string.gsub(text ,"%s*>%s*",">");
text = string.gsub(text ,"<%-%-(.-)%-%->"," ");
text = string.gsub(text ,"%s+"," ");
while true do
-- find the first tag
local open_tag = string.match(text,"%b<>")
if open_tag == nil then
-- no more tags, we're done
return true
end
local name = string.match(open_tag,"[%w%d_-]+")
local this_ent = nil
if d == nil then
-- there's no current dtd, this is entity is it
d = dtds[name]
if d == nil then
d = {ents = {}, attrs = {}}
dtds[name] = d
end
dtd = d
dtd_name = name
end
this_ent = d[name]
if this_ent == nil then
-- no entity by this name in this dtd, create it
this_ent = {ents = {}, attrs = {}}
d.ents[name] = this_ent
changed[dtd_name] = true
end
if parent ~= nil then
-- add this entity to its parent
parent.ents[name] = 1
changed[dtd_name] = true
end
-- add the attrs to the entity
for att in string.gmatch(open_tag, "([%w%d_-]+)%s*=") do
if not this_ent.attrs[att] then
changed[dtd_name] = true
this_ent.attrs[att] = true
end
end
if string.match(open_tag,"/>") then
-- this tag is "self closed" just remove it and continue
text = string.gsub(text,"%b<>","",1)
else
local close_tag_pat = "</%s*" .. name .. "%s*>"
if not string.match(text,close_tag_pat) then return false end
local span,left = string.match(text,"%b<>(.-)" .. close_tag_pat .. "(.*)")
if span ~= nil then
-- recurse to find child entities
if not get_dtd_from_xml(span,d,this_ent) then
return false
end
end
-- continue with what's left
text = left
end
end
return true
end
local function entity_tostring(name,entity_data)
-- name: the name of the entity
-- entity_data: a table containg the entity data
-- returns the dtd text for that entity
local text = ''
text = text .. '\t<!ELEMENT ' .. name .. ' (' --)
for e,j in pairs(entity_data.ents) do
text = text .. " " .. e .. ' |'
end
text = text .. " #PCDATA ) >\n"
text = text .. "\t<!ATTLIST " .. name
for a,j in pairs(entity_data.attrs) do
text = text .. "\n\t\t" .. a .. ' CDTATA #IMPLIED'
end
text = text .. " >\n\n"
text = string.gsub(text,"<!ATTLIST " .. name .. " >\n","")
return text
end
local function dtd_tostring(name,doctype)
local text = '<? wireshark:protocol proto_name="' .. name ..'" hierarchy="yes" ?>\n\n'
local root = doctype.ents[name]
doctype.ents[name] = nil
text = text .. entity_tostring(name,root)
for n,es in pairs(doctype.ents) do
text = text .. entity_tostring(n,es)
end
doctype.ents[name] = root
return text
end
local function element_body(name,text)
-- get the entity's children from dtd text
-- name: the name of the element
-- text: the list of children
text = string.gsub(text,"[%s%?%*%#%+%(%)]","")
text = string.gsub(text,"$","|")
text = string.gsub(text,
"^(.-)|",
function(s)
if dtd.ents[name] == nil then
dtd.ents[name] = {ents={},attrs={}}
end
dtd.ents[name].ents[s] = true
return ""
end
)
return ''
end
local function attlist_body(name,text)
-- get the entity's attributes from dtd text
-- name: the name of the element
-- text: the list of attributes
text = string.gsub(text,"([%w%d_-]+) [A-Z]+ #[A-Z]+",
function(s)
dtd.atts[s] = true
return ""
end
)
return ''
end
local function dtd_body(buff)
-- get the dtd's entities from dtd text
-- buff: the dtd text
local old_buff = buff
buff = string.gsub(buff,"<!ELEMENT ([%w%d_-]+) (%b())>%s*",element_body)
buff = string.gsub(buff,"<!ATTLIST ([%w%d_-]+) (.-)>%s*",attlist_body)
end
local function load_dtd(filename)
local dtd_filename = USER_DIR .. "/dtds/" .. filename
local buff = ''
local wireshark_info
dtd_name = nil
dtd = nil
for line in io.lines(dtd_filename) do
buff = buff .. line
end
buff = string.gsub(buff ,"%s*<%!%s*","<!");
buff = string.gsub(buff ,"%s*>%s*",">");
buff = string.gsub(buff ,"<!%-%-(.-)%-%->"," ");
buff = string.gsub(buff ,"%s+"," ");
buff = string.gsub(buff ,"^%s+","");
buff = string.gsub(buff,'(<%?%s*wireshark:protocol%s+.-%s*%?>)',
function(s)
wireshark_info = s
end
)
buff = string.gsub(buff,"^<!DOCTYPE ([%w%d_-]+) (%b[])%s*>",
function(name,body)
dtd = { ents = {}, attrs = {}}
dtd_name = name
dtds[name] = dtd
dtd_body(body)
return ""
end
)
if not dtd then
dtd_body(buff)
end
if wireshark_info then
dtd.wstag = wireshark_info
end
end
local function load_dtds()
-- loads all existing dtds in the user directory
local dirname = persconffile_path("dtds")
local status, dir = pcall(Dir.open,dirname,".dtd")
w:set('Loading DTDs from ' .. dirname .. ' \n')
if not status then
w:append("Error: could not open the directory" .. dirname .. " , make sure it exists.\n")
return
end
for dtd_filename in dir do
w:append("File:" .. dtd_filename .. "\n")
load_dtd(dtd_filename)
end
end
local function dtd_window(name)
return function()
local wd = TextWindow.new(name .. '.dtd')
wd:set(dtd_tostring(name,dtds[name]))
wd:set_editable()
local function save()
local file = io.open(persconffile_path("dtds/") .. name .. ".dtd" ,"w")
file:write(wd:get_text())
file:close()
end
wd:add_button("Save",save)
end
end
local function close()
if li ~= nil then
li:remove()
li = nil
end
end
w:set_atclose(close)
-- w:add_button("Help",help)
load_dtds()
local li = Listener.new("frame","xml")
w:append('Running')
function li.packet()
w:append('.')
local txt = xml_fld().range:string();
get_dtd_from_xml(txt)
end
function li.draw()
for name,j in pairs(changed) do
w:append("\n" .. name .. " has changed\n")
if not displayed[name] then
w:add_button(name,dtd_window(name))
displayed[name] = true
end
end
end
retap_packets()
w:append(t2s(dtds))
w:append('\n')
end
register_menu("DTD Generator",dtd_generator,MENU_TOOLS_UNSORTED)
end
| gpl-2.0 |
Satoshi-t/Re-SBS | lua/ai/wind-ai.lua | 1 | 34230 | sgs.ai_skill_use["@@shensu1"]=function(self,prompt)
self:updatePlayers()
self:sort(self.enemies,"defense")
if self.player:containsTrick("lightning") and self.player:getCards("j"):length()==1
and self:hasWizard(self.friends) and not self:hasWizard(self.enemies, true) then
return "."
end
if self:needBear() then return "." end
local selfSub = self.player:getHp() - self.player:getHandcardNum()
local selfDef = sgs.getDefense(self.player)
for _,enemy in ipairs(self.enemies) do
local def = sgs.getDefenseSlash(enemy, self)
local slash = sgs.Sanguosha:cloneCard("slash")
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if not self.player:canSlash(enemy, slash, false) then
elseif self:slashProhibit(nil, enemy) then
elseif def < 6 and eff then return "@ShensuCard=.->"..enemy:objectName()
elseif selfSub >= 2 then return "."
elseif selfDef < 6 then return "." end
end
for _,enemy in ipairs(self.enemies) do
local def=sgs.getDefense(enemy)
local slash = sgs.Sanguosha:cloneCard("slash")
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if not self.player:canSlash(enemy, slash, false) then
elseif self:slashProhibit(nil, enemy) then
elseif eff and def < 8 then return "@ShensuCard=.->"..enemy:objectName()
else return "." end
end
return "."
end
sgs.ai_get_cardType = function(card)
if card:isKindOf("Weapon") then return 1 end
if card:isKindOf("Armor") then return 2 end
if card:isKindOf("DefensiveHorse") then return 3 end
if card:isKindOf("OffensiveHorse")then return 4 end
end
sgs.ai_skill_use["@@shensu2"] = function(self, prompt, method)
self:updatePlayers()
self:sort(self.enemies, "defenseSlash")
local selfSub = self.player:getHp() - self.player:getHandcardNum()
local selfDef = sgs.getDefense(self.player)
local cards = self.player:getCards("he")
cards = sgs.QList2Table(cards)
local eCard
local hasCard = { 0, 0, 0, 0 }
if self:needToThrowArmor() and not self.player:isCardLimited(self.player:getArmor(), method) then
eCard = self.player:getArmor()
end
if not eCard then
for _, card in ipairs(cards) do
if card:isKindOf("EquipCard") then
hasCard[sgs.ai_get_cardType(card)] = hasCard[sgs.ai_get_cardType(card)] + 1
end
end
for _, card in ipairs(cards) do
if card:isKindOf("EquipCard") and hasCard[sgs.ai_get_cardType(card)] > 1 then
eCard = card
break
end
end
if not eCard then
for _, card in ipairs(cards) do
if card:isKindOf("EquipCard") and sgs.ai_get_cardType(card) > 3 and not self.player:isCardLimited(card, method) then
eCard = card
break
end
end
end
if not eCard then
for _, card in ipairs(cards) do
if card:isKindOf("EquipCard") and not card:isKindOf("Armor") and not self.player:isCardLimited(card, method) then
eCard = card
break
end
end
end
end
if not eCard then return "." end
local effectslash, best_target, target, throw_weapon
local defense = 6
local weapon = self.player:getWeapon()
if weapon and eCard:getId() == weapon:getId() and (eCard:isKindOf("fan") or eCard:isKindOf("QinggangSword")) then throw_weapon = true end
for _, enemy in ipairs(self.enemies) do
local def = sgs.getDefense(enemy)
local slash = sgs.Sanguosha:cloneCard("slash")
local eff = self:slashIsEffective(slash, enemy) and sgs.isGoodTarget(enemy, self.enemies, self)
if not self.player:canSlash(enemy, slash, false) then
elseif throw_weapon and enemy:hasArmorEffect("vine") and not self.player:hasSkill("zonghuo") then
elseif self:slashProhibit(nil, enemy) then
elseif eff then
if enemy:getHp() == 1 and getCardsNum("Jink", enemy) == 0 then best_target = enemy break end
if def < defense then
best_target = enemy
defense = def
end
target = enemy
end
if selfSub < 0 then return "." end
end
if best_target then return "@ShensuCard="..eCard:getEffectiveId().."->"..best_target:objectName() end
if target then return "@ShensuCard="..eCard:getEffectiveId().."->"..target:objectName() end
return "."
end
sgs.ai_cardneed.shensu = function(to, card, self)
return card:getTypeId() == sgs.Card_TypeEquip and getKnownCard(to, self.player, "EquipCard", false) < 2
end
sgs.ai_card_intention.ShensuCard = sgs.ai_card_intention.Slash
sgs.shensu_keep_value = sgs.xiaoji_keep_value
function sgs.ai_skill_invoke.jushou(self, data)
if not self.player:faceUp() then return true end
for _, friend in ipairs(self.friends) do
if friend:hasSkills("fangzhu|jilve") and not self:isWeak(friend) then return true end
if friend:hasSkill("junxing") and friend:faceUp() and not self:willSkipPlayPhase(friend)
and not (friend:isKongcheng() and self:willSkipDrawPhase(friend)) then
return true
end
end
if not self.player:hasSkill("jiewei") then return false end
for _, card in sgs.qlist(self.player:getHandcards()) do
if card:getTypeId() == sgs.Card_TypeTrick and not card:isKindOf("Nullification") then
local dummy_use = { isDummy = true }
self:useTrickCard(card, dummy_use)
if dummy_use.card then return true end
elseif card:getTypeId() == sgs.Card_TypeEquip then
local dummy_use = { isDummy = true }
self:useEquipCard(card, dummy_use)
if dummy_use.card then return true end
end
end
local Rate = math.random() + self.player:getCardCount()/10 + self.player:getHp()/10
if Rate > 1.1 then return true end
return false
end
sgs.ai_skill_invoke.jiewei = true
sgs.ai_skill_use["TrickCard+^Nullification,EquipCard|.|.|hand"] = function(self, prompt, method)
local cards = sgs.QList2Table(self.player:getHandcards())
self:sortByUseValue(cards)
for _, card in ipairs(cards) do
if card:getTypeId() == sgs.Card_TypeTrick and not card:isKindOf("Nullification") then
local dummy_use = { isDummy = true, to = sgs.SPlayerList() }
self:useTrickCard(card, dummy_use)
if dummy_use.card then
self.jiewei_type = sgs.Card_TypeTrick
if dummy_use.to:isEmpty() then
return dummy_use.card:toString()
else
local target_objectname = {}
for _, p in sgs.qlist(dummy_use.to) do
table.insert(target_objectname, p:objectName())
end
return dummy_use.card:toString() .. "->" .. table.concat(target_objectname, "+")
end
end
elseif card:getTypeId() == sgs.Card_TypeEquip then
local dummy_use = { isDummy = true }
self:useEquipCard(card, dummy_use)
if dummy_use.card then
self.jiewei_type = sgs.Card_TypeEquip
return dummy_use.card:toString()
end
end
end
return "."
end
sgs.ai_skill_playerchosen.jiewei = function(self, targets)
if self.jiewei_type == sgs.Card_TypeTrick then return self:findPlayerToDiscard("j", true, true, targets)
elseif self.jiewei_type == sgs.Card_TypeEquip then return self:findPlayerToDiscard("e", true, true, targets) end
end
sgs.ai_skill_invoke.liegong = function(self, data)
local target = data:toPlayer()
return not self:isFriend(target)
end
function SmartAI:canLiegong(to, from)
from = from or self.room:getCurrent()
to = to or self.player
if not from then return false end
if from:hasSkill("liegong") and from:getPhase() == sgs.Player_Play and (to:getHandcardNum() >= from:getHp() or to:getHandcardNum() <= from:getAttackRange()) then return true end
if from:hasSkill("kofliegong") and from:getPhase() == sgs.Player_Play and to:getHandcardNum() >= from:getHp() then return true end
return false
end
sgs.ai_skill_cardask["@guidao-card"]=function(self, data)
local judge = data:toJudge()
local all_cards = self.player:getCards("he")
if all_cards:isEmpty() then return "." end
local needTokeep = judge.card:getSuit() ~= sgs.Card_Spade and (not self.player:hasSkill("leiji") or judge.card:getSuit() ~= sgs.Card_Club)
and sgs.ai_AOE_data and self:playerGetRound(judge.who) < self:playerGetRound(self.player) and self:findLeijiTarget(self.player, 50)
and (self:getCardsNum("Jink") > 0 or self:hasEightDiagramEffect()) and self:getFinalRetrial() == 1
if not needTokeep then
local who = judge.who
if who:getPhase() == sgs.Player_Judge and not who:getJudgingArea():isEmpty() and who:containsTrick("lightning") and judge.reason ~= "lightning" then
needTokeep = true
end
end
local keptspade, keptblack = 0, 0
if needTokeep then
if self.player:hasSkill("nosleiji") then keptspade = 2 end
if self.player:hasSkill("leiji") then keptblack = 2 end
end
local cards = {}
for _, card in sgs.qlist(all_cards) do
if card:isBlack() and not card:hasFlag("using") then
if card:getSuit() == sgs.Card_Spade then keptspade = keptspade - 1 end
keptblack = keptblack - 1
table.insert(cards, card)
end
end
if #cards == 0 then return "." end
if keptblack == 1 then return "." end
if keptspade == 1 and not self.player:hasSkill("leiji") then return "." end
local card_id = self:getRetrialCardId(cards, judge)
if card_id == -1 then
if self:needRetrial(judge) and judge.reason ~= "beige" then
if self:needToThrowArmor() then return "$" .. self.player:getArmor():getEffectiveId() end
self:sortByUseValue(cards, true)
if self:getUseValue(judge.card) > self:getUseValue(cards[1]) then
return "$" .. cards[1]:getId()
end
end
elseif self:needRetrial(judge) or self:getUseValue(judge.card) > self:getUseValue(sgs.Sanguosha:getCard(card_id)) then
local card = sgs.Sanguosha:getCard(card_id)
return "$" .. card_id
end
return "."
end
function sgs.ai_cardneed.guidao(to, card, self)
for _, player in sgs.qlist(self.room:getAllPlayers()) do
if self:getFinalRetrial(to) == 1 then
if player:containsTrick("lightning") and not player:containsTrick("YanxiaoCard") then
return card:getSuit() == sgs.Card_Spade and card:getNumber() >= 2 and card:getNumber() <= 9 and not self:hasSkills("hongyan|wuyan")
end
if self:isFriend(player) and self:willSkipDrawPhase(player) then
return card:getSuit() == sgs.Card_Club and self:hasSuit("club", true, to)
end
end
end
if self:getFinalRetrial(to) == 1 then
if to:hasSkill("nosleiji") then
return card:getSuit() == sgs.Card_Spade
end
if to:hasSkill("leiji") then
return card:isBlack()
end
end
end
function SmartAI:findLeijiTarget(player, leiji_value, slasher, latest_version)
if not latest_version then
return self:findLeijiTarget(player, leiji_value, slasher, 1) or self:findLeijiTarget(player, leiji_value, slasher, -1)
end
if not player:hasSkill(latest_version == 1 and "leiji" or "nosleiji") then return nil end
if slasher then
if not self:slashIsEffective(sgs.Sanguosha:cloneCard("slash"), player, slasher, slasher:hasWeapon("qinggang_sword")) then return nil end
if slasher:hasSkill("liegong") and slasher:getPhase() == sgs.Player_Play and self:isEnemy(player, slasher)
and (player:getHandcardNum() >= slasher:getHp() or player:getHandcardNum() <= slasher:getAttackRange()) then
return nil
end
if slasher:hasSkill("kofliegong") and slasher:getPhase() == sgs.Player_Play
and self:isEnemy(player, slasher) and player:getHandcardNum() >= slasher:getHp() then
return nil
end
if not latest_version then
if not self:hasSuit("spade", true, player) and player:getHandcardNum() < 3 then return nil end
else
if not self:hasSuit("black", true, player) and player:getHandcardNum() < 2 then return nil end
end
if not (getKnownCard(player, self.player, "Jink", true) > 0
or (getCardsNum("Jink", player, self.player) >= 1 and sgs.card_lack[player:objectName()]["Jink"] ~= 1 and player:getHandcardNum() >= 4)
or (not self:isWeak(player) and self:hasEightDiagramEffect(player) and not slasher:hasWeapon("qinggang_sword") and sgs.card_lack[player:objectName()]["Jink"] ~= 1)) then
return nil
end
end
local getCmpValue = function(enemy)
local value = 0
if not self:damageIsEffective(enemy, sgs.DamageStruct_Thunder, player) then return 99 end
if enemy:hasSkill("hongyan") then
if latest_version == -1 then return 99
elseif not self:hasSuit("club", true, player) and player:getHandcardNum() < 3 then value = value + 80
else value = value + 70 end
end
if self:cantbeHurt(enemy, player, latest_version == 1 and 1 or 2) or self:objectiveLevel(enemy) < 3
or (enemy:isChained() and not self:isGoodChainTarget(enemy, player, sgs.DamageStruct_Thunder, latest_version == 1 and 1 or 2)) then return 100 end
if not sgs.isGoodTarget(enemy, self.enemies, self) then value = value + 50 end
if not latest_version and enemy:hasArmorEffect("silver_lion") then value = value + 20 end
if enemy:hasSkills(sgs.exclusive_skill) then value = value + 10 end
if enemy:hasSkills(sgs.masochism_skill) then value = value + 5 end
if enemy:isChained() and self:isGoodChainTarget(enemy, player, sgs.DamageStruct_Thunder, latest_version == 1 and 1 or 2) and #(self:getChainedEnemies(player)) > 1 then value = value - 25 end
if enemy:isLord() then value = value - 5 end
value = value + enemy:getHp() + sgs.getDefenseSlash(enemy, self) * 0.01
if latest_version and player:isWounded() and not self:needToLoseHp(player) then value = value + 15 end
return value
end
local cmp = function(a, b)
return getCmpValue(a) < getCmpValue(b)
end
local enemies = self:getEnemies(player)
table.sort(enemies, cmp)
for _,enemy in ipairs(enemies) do
if getCmpValue(enemy) < leiji_value then return enemy end
end
return nil
end
sgs.ai_skill_playerchosen.leiji = function(self, targets)
local mode = self.room:getMode()
if mode:find("_mini_17") or mode:find("_mini_19") or mode:find("_mini_20") or mode:find("_mini_26") then
local players = self.room:getAllPlayers();
for _, aplayer in sgs.qlist(players) do
if aplayer:getState() ~= "robot" then
return aplayer
end
end
end
self:updatePlayers()
return self:findLeijiTarget(self.player, 100, nil, 1)
end
function SmartAI:needLeiji(to, from)
return self:findLeijiTarget(to, 50, from, -1)
end
sgs.ai_playerchosen_intention.leiji = 80
function sgs.ai_slash_prohibit.leiji(self, from, to, card) -- @todo: Qianxi flag name
if self:isFriend(to) then return false end
if to:hasFlag("QianxiTarget") and (not self:hasEightDiagramEffect(to) or self.player:hasWeapon("qinggang_sword")) then return false end
local hcard = to:getHandcardNum()
if self:canLiegong(to, from) then return false end
if from:getRole() == "rebel" and to:isLord() then
local other_rebel
for _, player in sgs.qlist(self.room:getOtherPlayers(from)) do
if sgs.evaluatePlayerRole(player) == "rebel" or sgs.compareRoleEvaluation(player, "rebel", "loyalist") == "rebel" then
other_rebel = player
break
end
end
if not other_rebel and (self:hasSkills("hongyan") or self.player:getHp() >= 4) and (self:getCardsNum("Peach") > 0 or self.player:hasSkills("hongyan|ganglie|neoganglie")) then
return false
end
end
if sgs.card_lack[to:objectName()]["Jink"] == 2 then return true end
if getKnownCard(to, self.player, "Jink", true) >= 1 or (self:hasSuit("spade", true, to) and hcard >= 2) or hcard >= 4 then return true end
if not from then
from = self.room:getCurrent()
end
if self:hasEightDiagramEffect(to) and not IgnoreArmor(from, to) then return true end
end
local huangtianv_skill = {}
huangtianv_skill.name = "huangtian_attach"
table.insert(sgs.ai_skills, huangtianv_skill)
huangtianv_skill.getTurnUseCard = function(self)
if self.player:hasFlag("ForbidHuangtian") then return nil end
if self.player:getKingdom() ~= "qun" then return nil end
local cards = self.player:getCards("h")
cards = sgs.QList2Table(cards)
local card
self:sortByUseValue(cards,true)
for _,acard in ipairs(cards) do
if acard:isKindOf("Jink") then
card = acard
break
end
end
if not card then return nil end
local card_id = card:getEffectiveId()
local card_str = "@HuangtianCard="..card_id
local skillcard = sgs.Card_Parse(card_str)
assert(skillcard)
return skillcard
end
sgs.ai_skill_use_func.HuangtianCard = function(card, use, self)
if self:needBear() or self:getCardsNum("Jink", "h") <= 1 then
return "."
end
local targets = {}
for _,friend in ipairs(self.friends_noself) do
if friend:hasLordSkill("huangtian") then
if not friend:hasFlag("HuangtianInvoked") then
if not friend:hasSkill("manjuan") then
table.insert(targets, friend)
end
end
end
end
if #targets > 0 then --黄天己方
use.card = card
self:sort(targets, "defense")
if use.to then
use.to:append(targets[1])
end
elseif self:getCardsNum("Slash", "he") >= 2 then --黄天对方
for _,enemy in ipairs(self.enemies) do
if enemy:hasLordSkill("huangtian") then
if not enemy:hasFlag("HuangtianInvoked") then
if not enemy:hasSkill("manjuan") then
if enemy:isKongcheng() and not enemy:hasSkill("kongcheng") and not enemy:hasSkills("tuntian+zaoxian") then --必须保证对方空城,以保证天义/陷阵的拼点成功
table.insert(targets, enemy)
end
end
end
end
end
if #targets > 0 then
local flag = false
if self.player:hasSkill("tianyi") and not self.player:hasUsed("TianyiCard") then
flag = true
elseif self.player:hasSkill("xianzhen") and not self.player:hasUsed("XianzhenCard") then
flag = true
end
if flag then
local maxCard = self:getMaxCard(self.player) --最大点数的手牌
if maxCard:getNumber() > card:getNumber() then --可以保证拼点成功
self:sort(targets, "defense", true)
for _,enemy in ipairs(targets) do
if self.player:canSlash(enemy, nil, false, 0) then --可以发动天义或陷阵
use.card = card
enemy:setFlags("AI_HuangtianPindian")
if use.to then
use.to:append(enemy)
end
break
end
end
end
end
end
end
end
sgs.ai_card_intention.HuangtianCard = function(self, card, from, tos)
if tos[1]:isKongcheng() and ((from:hasSkill("tianyi") and not from:hasUsed("TianyiCard"))
or (from:hasSkill("xianzhen") and not from:hasUsed("XianzhenCard"))) then
else
sgs.updateIntention(from, tos[1], -80)
end
end
sgs.ai_use_priority.HuangtianCard = 10
sgs.ai_use_value.HuangtianCard = 8.5
sgs.guidao_suit_value = {
spade = 3.9,
club = 2.7
}
sgs.ai_skill_invoke.fenji = function(self, data)
local move = data:toMoveOneTime()
local from = findPlayerByObjectName(self.room, move.from:objectName())
if self:isWeak() or not from or not self:isFriend(from)
or hasManjuanEffect(from)
or self:needKongcheng(from, true) then return false end
local skill_name = move.reason.m_skillName
if skill_name == "rende" or skill_name == "nosrende" then return true end
return from:getHandcardNum() < (self.player:getHp() <= 1 and 3 or 5)
end
sgs.ai_choicemade_filter.skillInvoke.fenji = function(self, player, promptlist)
if sgs.ai_fenji_target then
if promptlist[3] == "yes" then
sgs.updateIntention(player, sgs.ai_fenji_target, -10)
end
sgs.ai_fenji_target = nil
end
end
sgs.ai_skill_use["@@tianxiang"] = function(self, data, method)
if not method then method = sgs.Card_MethodDiscard end
local friend_lost_hp = 10
local friend_hp = 0
local card_id
local target
local cant_use_skill
local dmg
if data == "@tianxiang-card" then
dmg = self.player:getTag("TianxiangDamage"):toDamage()
else
dmg = data
end
if not dmg then self.room:writeToConsole(debug.traceback()) return "." end
local cards = self.player:getCards("h")
cards = sgs.QList2Table(cards)
self:sortByUseValue(cards, true)
for _, card in ipairs(cards) do
if not self.player:isCardLimited(card, method) and card:getSuit() == sgs.Card_Heart and not card:isKindOf("Peach") then
card_id = card:getId()
break
end
end
if not card_id then return "." end
self:sort(self.enemies, "hp")
for _, enemy in ipairs(self.enemies) do
if (enemy:getHp() <= dmg.damage and enemy:isAlive() and enemy:getLostHp() + dmg.damage < 3) then
if (enemy:getHandcardNum() <= 2 or enemy:hasSkills("guose|leiji|ganglie|enyuan|qingguo|wuyan|kongcheng") or enemy:containsTrick("indulgence"))
and self:canAttack(enemy, dmg.from or self.room:getCurrent(), dmg.nature)
and not (dmg.card and dmg.card:getTypeId() == sgs.Card_TypeTrick and enemy:hasSkill("wuyan")) then
return "@TianxiangCard=" .. card_id .. "->" .. enemy:objectName()
end
end
end
for _, friend in ipairs(self.friends_noself) do
if (friend:getLostHp() + dmg.damage > 1 and friend:isAlive()) then
if friend:isChained() and dmg.nature ~= sgs.DamageStruct_Normal and not self:isGoodChainTarget(friend, dmg.from, dmg.nature, dmg.damage, dmg.card) then
elseif friend:getHp() >= 2 and dmg.damage < 2
and (friend:hasSkills("yiji|buqu|nosbuqu|shuangxiong|zaiqi|yinghun|jianxiong|fangzhu")
or self:getDamagedEffects(friend, dmg.from or self.room:getCurrent())
or self:needToLoseHp(friend)
or (friend:getHandcardNum() < 3 and (friend:hasSkill("nosrende") or (friend:hasSkill("rende") and not friend:hasUsed("RendeCard"))))) then
return "@TianxiangCard=" .. card_id .. "->" .. friend:objectName()
elseif dmg.card and dmg.card:getTypeId() == sgs.Card_TypeTrick and friend:hasSkill("wuyan") and friend:getLostHp() > 1 then
return "@TianxiangCard=" .. card_id .. "->" .. friend:objectName()
elseif hasBuquEffect(friend) then return "@TianxiangCard=" .. card_id .. "->" .. friend:objectName() end
end
end
for _, enemy in ipairs(self.enemies) do
if (enemy:getLostHp() <= 1 or dmg.damage > 1) and enemy:isAlive() and enemy:getLostHp() + dmg.damage < 4 then
if (enemy:getHandcardNum() <= 2)
or enemy:containsTrick("indulgence") or enemy:hasSkills("guose|leiji|vsganglie|ganglie|enyuan|qingguo|wuyan|kongcheng")
and self:canAttack(enemy, (dmg.from or self.room:getCurrent()), dmg.nature)
and not (dmg.card and dmg.card:getTypeId() == sgs.Card_TypeTrick and enemy:hasSkill("wuyan")) then
return "@TianxiangCard=" .. card_id .. "->" .. enemy:objectName() end
end
end
for i = #self.enemies, 1, -1 do
local enemy = self.enemies[i]
if not enemy:isWounded() and not self:hasSkills(sgs.masochism_skill, enemy) and enemy:isAlive()
and self:canAttack(enemy, dmg.from or self.room:getCurrent(), dmg.nature)
and (not (dmg.card and dmg.card:getTypeId() == sgs.Card_TypeTrick and enemy:hasSkill("wuyan") and enemy:getLostHp() > 0) or self:isWeak()) then
return "@TianxiangCard=" .. card_id .. "->" .. enemy:objectName()
end
end
return "."
end
sgs.ai_card_intention.TianxiangCard = function(self, card, from, tos)
local to = tos[1]
if self:getDamagedEffects(to) or self:needToLoseHp(to) then return end
local intention = 10
if hasBuquEffect(to) then intention = 0
elseif (to:getHp() >= 2 and to:hasSkills("yiji|shuangxiong|zaiqi|yinghun|jianxiong|fangzhu"))
or (to:getHandcardNum() < 3 and (to:hasSkill("nosrende") or (to:hasSkill("rende") and not to:hasUsed("RendeCard")))) then
intention = 0
end
sgs.updateIntention(from, to, intention)
end
function sgs.ai_slash_prohibit.tianxiang(self, from, to)
if from:hasSkill("jueqing") or (from:hasSkill("nosqianxi") and from:distanceTo(to) == 1) then return false end
if from:hasFlag("NosJiefanUsed") then return false end
if self:isFriend(to, from) then return false end
return self:cantbeHurt(to, from)
end
sgs.tianxiang_suit_value = {
heart = 4.9
}
function sgs.ai_cardneed.tianxiang(to, card, self)
return (card:getSuit() == sgs.Card_Heart or (to:hasSkill("hongyan") and card:getSuit() == sgs.Card_Spade))
and (getKnownCard(to, self.player, "heart", false) + getKnownCard(to, self.player, "spade", false)) < 2
end
table.insert(sgs.ai_global_flags, "questioner")
sgs.ai_skill_choice.guhuo = function(self, choices)
local yuji = self.room:findPlayerBySkillName("guhuo")
if not self:isEnemy(yuji) then return "noquestion" end
local guhuoname = self.room:getTag("GuhuoType"):toString()
if guhuoname == "peach+analeptic" then guhuoname = "peach" end
if guhuoname == "normal_slash" then guhuoname = "slash" end
local guhuocard = sgs.Sanguosha:cloneCard(guhuoname)
local guhuotype = guhuocard:getClassName()
if guhuotype and self:getRestCardsNum(guhuotype, yuji) == 0 and self.player:getHp() > 0 then return "question" end
if guhuotype and guhuotype == "AmazingGrace" then return "noquestion" end
if self.player:hasSkill("hunzi") and self.player:getMark("hunzi") == 0 and math.random(1, 15) ~= 1 then return "noquestion" end
if guhuotype:match("Slash") then
if yuji:getState() ~= "robot" and math.random(1, 8) == 1 then return "question" end
if not self:hasCrossbowEffect(yuji) then return "noquestion" end
end
local x = 5
if guhuoname == "peach" or guhuoname == "ex_nihilo" then
x = 2
if getKnownCard(yuji, self.player, guhuotype, false) > 0 then x = x * 3 end
end
return math.random(1, x) == 1 and "question" or "noquestion"
end
local guhuo_skill = {}
guhuo_skill.name = "guhuo"
table.insert(sgs.ai_skills, guhuo_skill)
guhuo_skill.getTurnUseCard = function(self)
if self.player:isKongcheng() or self.player:hasFlag("GuhuoUsed") then return end
local current = self.room:getCurrent()
if not current or current:isDead() or current:getPhase() == sgs.Player_NotActive then return end
local cards = sgs.QList2Table(self.player:getHandcards())
local GuhuoCard_str = {}
for _, card in ipairs(cards) do
if card:isNDTrick() then
local dummyuse = { isDummy = true }
self:useTrickCard(card, dummyuse)
if dummyuse.card then table.insert(GuhuoCard_str, "@GuhuoCard=" .. card:getId() .. ":" .. card:objectName()) end
end
end
local peach_str = self:getGuhuoCard("Peach", true, 1)
if peach_str then table.insert(GuhuoCard_str, peach_str) end
local fakeCards = {}
for _, card in sgs.qlist(self.player:getHandcards()) do
if (card:isKindOf("Slash") and self:getCardsNum("Slash", "h") >= 2 and not self:hasCrossbowEffect())
or (card:isKindOf("Jink") and self:getCardsNum("Jink", "h") >= 3)
or (card:isKindOf("EquipCard") and self:getSameEquip(card))
or card:isKindOf("Disaster") then
table.insert(fakeCards, card)
end
end
self:sortByUseValue(fakeCards, true)
local function fake_guhuo(objectName)
if #fakeCards == 0 then return end
local fakeCard
local guhuo = "peach|ex_nihilo|snatch|dismantlement|amazing_grace|archery_attack|savage_assault"
local ban = table.concat(sgs.Sanguosha:getBanPackages(), "|")
if not ban:match("maneuvering") then guhuo = guhuo .. "|fire_attack" end
local guhuos = guhuo:split("|")
for i = 1, #guhuos do
local forbidden = guhuos[i]
local forbid = sgs.Sanguosha:cloneCard(forbidden)
if self.player:isLocked(forbid) then
table.remove(guhuos, i)
i = i - 1
end
end
for i=1, 10 do
local card = fakeCards[math.random(1, #fakeCards)]
local newguhuo = objectName or guhuos[math.random(1, #guhuos)]
local guhuocard = sgs.Sanguosha:cloneCard(newguhuo, card:getSuit(), card:getNumber())
if self:getRestCardsNum(guhuocard:getClassName()) > 0 then
local dummyuse = {isDummy = true}
if newguhuo == "peach" then self:useBasicCard(guhuocard, dummyuse) else self:useTrickCard(guhuocard, dummyuse) end
if dummyuse.card then
fakeCard = sgs.Card_Parse("@GuhuoCard=" .. card:getId() .. ":" .. newguhuo)
break
end
end
end
return fakeCard
end
local enemy_num = #self.enemies
local can_question = enemy_num
for _, enemy in ipairs(self.enemies) do
if enemy:hasSkill("chanyuan") or (enemy:hasSkill("hunzi") and enemy:getMark("hunzi") == 0) then can_question = can_question - 1 end
end
local ratio = (can_question == 0) and 100 or (enemy_num / can_question)
if #GuhuoCard_str > 0 then
local guhuo_str = GuhuoCard_str[math.random(1, #GuhuoCard_str)]
local str = guhuo_str:split("=")
str = str[2]:split(":")
local cardid, cardname = str[1], str[2]
if sgs.Sanguosha:getCard(cardid):objectName() == cardname and cardname == "ex_nihilo" then
if math.random(1, 3) <= ratio then
local fake_exnihilo = fake_guhuo(cardname)
if fake_exnihilo then return fake_exnihilo end
end
return sgs.Card_Parse(guhuo_str)
elseif math.random(1, 5) <= ratio then
local fake_GuhuoCard = fake_guhuo()
if fake_GuhuoCard then return fake_GuhuoCard end
else
return sgs.Card_Parse(guhuo_str)
end
elseif math.random(1, 5) <= 3 * ratio then
local fake_GuhuoCard = fake_guhuo()
if fake_GuhuoCard then return fake_GuhuoCard end
end
if self:isWeak() then
local peach_str = self:getGuhuoCard("Peach", true, 1)
if peach_str then
local card = sgs.Card_Parse(peach_str)
local peach = sgs.Sanguosha:cloneCard("peach", card:getSuit(), card:getNumber())
local dummyuse = { isDummy = true }
self:useBasicCard(peach, dummyuse)
if dummyuse.card then return card end
end
end
local slash_str = self:getGuhuoCard("Slash", true, 1)
if slash_str and self:slashIsAvailable() then
local card = sgs.Card_Parse(slash_str)
local slash = sgs.Sanguosha:cloneCard("slash", card:getSuit(), card:getNumber())
local dummyuse = { isDummy = true }
self:useBasicCard(slash, dummyuse)
if dummyuse.card then return card end
end
end
sgs.ai_skill_use_func.GuhuoCard=function(card,use,self)
local userstring=card:toString()
userstring=(userstring:split(":"))[3]
local guhuocard=sgs.Sanguosha:cloneCard(userstring, card:getSuit(), card:getNumber())
guhuocard:setSkillName("guhuo")
if guhuocard:getTypeId() == sgs.Card_TypeBasic then
if not use.isDummy and use.card and guhuocard:isKindOf("Slash") and (not use.to or use.to:isEmpty()) then return end
self:useBasicCard(guhuocard, use)
else
assert(guhuocard)
self:useTrickCard(guhuocard, use)
end
if not use.card then return end
use.card=card
end
sgs.ai_use_priority.GuhuoCard = 10
function SmartAI:getGuhuoViewCard(class_name, latest_version)
local card_use, fakeCards = {}, {}
local all_cards = (self.room:getMode() == "_mini_48")
local can_question = #self.enemies
if latest_version == 1 then
for _, enemy in ipairs(self.enemies) do
if enemy:hasSkill("chanyuan") or (enemy:hasSkill("hunzi") and enemy:getMark("hunzi") == 0) then can_question = can_question - 1 end
end
if can_question == 0 then all_cards = true end
end
local ratio = (can_question == 0) and 100 or (#self.enemies / can_question)
if all_cards then
card_use = sgs.QList2Table(self.player:getHandcards())
self:sortByKeepValue(card_use)
else
if latest_version == -1 then
for _, card in sgs.qlist(self.player:getHandcards()) do
if card:isKindOf(class_name) and card:getSuit() == sgs.Card_Heart then
table.insert(card_use, card)
end
end
for _, card in sgs.qlist(self.player:getHandcards()) do
if card:isKindOf(class_name) and not table.contains(card_use, card) then
table.insert(card_use, card)
end
end
else
for _, card in sgs.qlist(self.player:getHandcards()) do
if card:isKindOf(class_name) then
table.insert(card_use, card)
end
end
end
for _, card in sgs.qlist(self.player:getHandcards()) do
if not card:isKindOf(class_name) then
if (card:isKindOf("Slash") and self:getCardsNum("Slash", "h") >= 2 and not self:hasCrossbowEffect())
or (card:isKindOf("Jink") and self:getCardsNum("Jink", "h") >= 3)
or (card:isKindOf("EquipCard") and self:getSameEquip(card))
or card:isKindOf("Disaster") then
table.insert(fakeCards, card)
end
end
end
self:sortByKeepValue(fakeCards)
end
local classname2objectname = {
["Slash"] = "slash", ["Jink"] = "jink",
["Peach"] = "peach", ["Analeptic"] = "analeptic",
["Nullification"] = "nullification",
["FireSlash"] = "fire_slash", ["ThunderSlash"] = "thunder_slash"
}
if classname2objectname[class_name] then
local card = sgs.Sanguosha:cloneCard(classname2objectname[class_name])
if not card or self.player:isCardLimited(card, sgs.Card_MethodUse, true) then return end
if #card_use > 1 or (#card_use > 0 and (latest_version == 1 or card_use[1]:getSuit() == sgs.Card_Heart or all_cards)) then
local index = 1
local ban = table.concat(sgs.Sanguosha:getBanPackages(), "|")
if not all_cards and (class_name == "Peach" or (class_name == "Analeptic" and not ban:match("maneuvering")) or class_name == "Jink") then
index = #card_use
end
local card_class = latest_version == 1 and "@GuhuoCard=" or "@NosGuhuoCard="
return card_class .. card_use[index]:getEffectiveId() .. ":" .. classname2objectname[class_name]
end
if #fakeCards > 0 and math.random(1, 5) <= ratio then
local card_class = latest_version == 1 and "@GuhuoCard=" or "@NosGuhuoCard="
return card_class .. fakeCards[1]:getEffectiveId() .. ":" .. classname2objectname[class_name]
end
end
end
function SmartAI:getGuhuoCard(class_name, at_play, latest_version)
if not latest_version then return self:getGuhuoCard(class_name, at_play, 1) or self:getGuhuoCard(class_name, at_play, -1) end
local player = self.player
local current = self.room:getCurrent()
if not (latest_version == 1 and player:hasSkill("guhuo") and not player:hasFlag("GuhuoUsed")
and current and current:isAlive() and current:getPhase() ~= sgs.Player_NotActive)
and not (latest_version == -1 and player:hasSkill("nosguhuo")) then return end
if at_play then
if class_name == "Peach" and not player:isWounded() then return
elseif class_name == "Analeptic" and player:hasUsed("Analeptic") then return
elseif (class_name == "Slash" or class_name == "ThunderSlash" or class_name == "FireSlash") and not self:slashIsAvailable(player) then return
elseif class_name == "Jink" or class_name == "Nullification" then return
end
else
if class_name == "Peach" and self.player:getMark("Global_PreventPeach") > 0 then return end
end
return self:getGuhuoViewCard(class_name, latest_version)
end
sgs.guhuo_suit_value = {
heart = 5,
}
sgs.ai_skill_choice.guhuo_saveself = function(self, choices)
if self:getCard("Peach") or not self:getCard("Analeptic") then return "peach" else return "analeptic" end
end
sgs.ai_suit_priority.guidao= "diamond|heart|club|spade"
sgs.ai_suit_priority.hongyan= "club|diamond|spade|heart"
sgs.ai_suit_priority.guhuo= "club|spade|diamond|heart"
sgs.ai_skill_choice.guhuo_slash = function(self, choices)
return "slash"
end
function sgs.ai_cardneed.kuanggu(to, card, self)
return card:isKindOf("OffensiveHorse") and not (to:getOffensiveHorse() or getKnownCard(to, self.player, "OffensiveHorse", false) > 0)
end | gpl-3.0 |
rlcevg/Zero-K | LuaUI/Widgets/tipdispenser.lua | 6 | 15941 | local widgetName = "Automatic Tip Dispenser"
local playerID = Spring.GetMyPlayerID()
local rank = playerID and select(9, Spring.GetPlayerInfo(playerID))
function widget:GetInfo()
return {
name = widgetName,
desc = "v0.4 Teach you to play the game, one tip at a time",
author = "KingRaptor; original by zwzsg",
date = "July 30th, 2009",
license = "Public Domain",
layer = 8,
enabled = false, -- (rank and rank == 1) or true,
handler = true,
}
end
------------------------
-- speedups
local spGetGameSeconds = Spring.GetGameSeconds
local spGetMyTeamID = Spring.GetMyTeamID
local spGetTeamUnitsByDefs = Spring.GetTeamUnitsByDefs
local spGetTeamResources = Spring.GetTeamResources
------------------------
-- CONFIG
------------------------
VFS.Include("LuaUI/Configs/tipconfig.lua",nil)
local tipsList = {}
local unitTipsAvailable = {}
local alreadyDisplayedTips = {}
local tipPeriod = 8 -- How long each tip is displayed, in seconds
local FontSize = nil
local SoundTable = {}
local SoundToggle = true
local MouseButton = nil
local generalTipsIndex = math.random(1, #generalTips)
local airSpotted = false
local nukeSpotted = false
local updateFrequency = tipPeriod
local myTeam = spGetMyTeamID()
-----------------------
-- minimum complexity of tips to display
-- 1 = new to RTS
-- 2 = a bit of experience with ZK
-- 3 = up to intermediate
local helpLevel = rank and math.min(rank, 3) or 1
-- Chili classes
local Chili
local Button
local Label
local Window
local Panel
local TextBox
local Image
local Control
-- Chili instances
local screen0
local window
local image
local textBox
local close
local closeImage
local nextTip
local function SortCompareTables(t1,t2)
table.sort(t1)
table.sort(t2)
if #t1~=#t2 then
return false
else
for k=1,#t1 do
if t1[k]~=t2[k] then
return false
end
end
return true
end
end
-- The round2 function from http://lua-users.org/wiki/SimpleRound fails on 0.11
local function FormatNbr(x,digits)
local _,fractional = math.modf(x)
if fractional==0 then
return x
elseif fractional<0.01 then
return math.floor(x)
elseif fractional>0.99 then
return math.ceil(x)
else
local ret=string.format("%."..(digits or 0).."f",x)
if digits and digits>0 then
while true do
local last = string.sub(ret,string.len(ret))
if last=="0" or last=="." then
ret = string.sub(ret,1,string.len(ret)-1)
end
if last~="0" then
break
end
end
end
return ret
end
end
local function MakePlural(str)
local ending=string.sub(str,string.len(str),string.len(str))
if ending=="y" then
return string.sub(str,1,string.len(str)-1).."ies"
elseif ending==">" or ending=="s" then
return str
else
return str.."s"
end
end
local function WriteString(str, unitDef, plural)
local name = (type(unitDef) == "number") and UnitDefs[unitDef].humanName or UnitDefNames[unitDef].humanName
if plural then name = MakePlural(name) end
return string.gsub(str, "<name>", name, 1)
end
local function AddTip(str, level, weight, sound, prereq)
if prereq and (not alreadyDisplayedTips[prereq]) then return end
level = level or 1
if level < helpLevel then return end
weight = weight or 1
local text, sound = str or "", sound or nil
tipsList[#tipsList + 1] = {weight = weight, text = text, sound = sound}
end
local function AddTipOnce(str, level, weight, sound, prereq)
if alreadyDisplayedTips[str] then return end
AddTip(str, level, weight, sound, prereq)
end
local function CountMy(unitKind)
local defs = {}
for i in pairs(unitKind) do
defs[#defs+1] = i
end
local got=spGetTeamUnitsByDefs(myTeam, defs)
if got==nil then
return 0
else
return #got
end
end
local function CountTheirs(unitKind)
local nGot=0
local defs = {}
for i in pairs(unitKind) do
defs[#defs+1] = i
end
local teams = Spring.GetTeamList()
for i=1,#teams do
local team = teams[i]
if not Spring.AreTeamsAllied(team,myTeam) then
nGot=nGot+#(spGetTeamUnitsByDefs(team,defs) or {})
end
end
return nGot
end
local function Prevalence(unitKind)
local Total=Spring.GetTeamUnitCount(myTeam)
if Total==0 then
return 0
else
return CountMy(unitKind)/Total
end
end
local function IsSelected(unitKind)
local units = spGetTeamUnitsByDefs(myTeam,unitKind)
for i=1,#units do
if Spring.IsUnitSelected(units[i]) then
return true
end
end
return false
end
-- used to get weighted sum of units in existence and selected
local function PSC(unitKind,PrevalenceWeight,isSelectedWeight)
PrevalenceWeight=PrevalenceWeight or 1
isSelectedWeight=isSelectedWeight or 1
return PrevalenceWeight*Prevalence(unitKind)+isSelectedWeight*(IsSelected(unitKind) and 1 or 0)
end
local function GetDamage(predator,prey)
return WeaponDefs[UnitDefs[UnitDefNames[predator].id].weapons[1].weaponDef].damages[UnitDefs[UnitDefNames[prey].id].armorType]
end
local function GetTipsList()
local t=myTeam
tipsList={}
-- add unit tips from available list
for name, _ in pairs(unitTipsAvailable) do
AddTipOnce(unpack(unitTips[name]))
end
-- Always shown tips
-- General interface tips
AddTipOnce("Use Ctrl+F11 to to move screen elements around.", 1)
AddTipOnce("Press Esc to toggle the game menu, where you can alter settings.", 1)
AddTipOnce("Use Mouse Wheel to zoom in and out. Hold down the mousewheel and drag to pan.", 1)
-- Beginning: Getting the commander to build the starting base
--[[
if CountMy(energy) + CountMy(mex) <= 3 and spGetGameSeconds() < 30 then
if Spring.GetTeamUnitCount(t)==0 then
if Game.startPosType==2 and Spring.GetGameFrame()==0 then
AddTip("Pick a starting position, then click ready.\nLook for areas with metal spots (press F4 to toggle the metal map). Do not spawn in a cliff!", 1, 5)
--else
--AddTip("Game is loading.", 3, 10000)
end
elseif CountMy(commander)==1 then
if Spring.GetSelectedUnitsCount()==0 then
AddTip("Select your commander and start building your base. You can select something to build by pressing right click and drawing a gesture, or using the buttons in the menu (bottom right)", 1)
end
local econStr1 = "Metal is the principal game resource. Build some Metal Extractors (mexes) on the metal spots."
local econStr2 = "Energy is also essential for your economy to function. Build some Solar Collectors or Wind Generators."
local econStr3 = "Buildpower, often described as the third resource, is the measure of how much you can spend at once. We'll discuss that later."
AddTip(econStr1, 1, 3)
AddTip(econStr2, 1, 3, nil, econStr1)
AddTip(econStr3, 1, 3, nil, econStr2)
end
-- Beginning: Getting commander) to build the first fac
elseif CountMy(energy) >= 3 and CountMy(mex)>= 1 and CountMy(factory) == 0 and spGetGameSeconds() < 60 then
AddTip("Use your commander to make a factory. The Shield Bot Factory is a good choice for beginners.\nYour first factory is \255\255\64\0FREE\008.", 1, 5)
-- Once the player has started getting stuff done
else
]]--
--[[if CountMy(factory)>=1 then
AddTipOnce("Build some units with that factory. You'll want to start with a couple of constructors for expansion and a few raiders for early combat.", 1, 10)
end --]]
if CountMy(energy)>= 5 then
AddTipOnce("Connect energy to your mexes to allow them to \255\255\64\0overdrive\008, which uses excess energy to produce more metal.", 1)
end
if CountMy(energy)>= 5 and (IsSelected(mex) or IsSelected(energy)) then
local odStr1 = "The circles around your mexes and energy (when selected) indicate their pylon radius.\nTwo econ buildings are connected if their circles overlap."
local odStr2 = "The color of a pylon grid denotes its efficiency. Blue is good, red is bad. Pink is unlinked."
AddTipOnce(odStr1, 2, 1)
AddTipOnce(odStr2, 2, 1, nil, odStr1)
end
if CountMy(raider) >= 1 then
local raiderStr1 = "Fast but fragile, raiders are suitable for harassing the enemy's economy, as well as jumping skirmishers and the like."
local raiderStr2 = "Raiders should avoid charging enemy defenses or riot units head-on."
AddTipOnce(raiderStr1, 1, 3)
AddTipOnce(raiderStr2,1, 2, nil, raiderStr1)
end
if CountMy(assault) >= 1 then
AddTipOnce("Assault units are generally good all-rounders, but they particularly excel at punching through defensive lines.", 1, 3)
end
if CountMy(skirm) >= 1 then
AddTipOnce("Skirmishers are medium-ranged units, ideal for picking off riot units and some defenses from afar. They are vulnerable to raider charges.", 1, 3)
end
if CountMy(riot) >= 1 then
AddTipOnce("Riot units are slow, short-ranged, and extremely deadly. Use them to counter raiders, but do not attack defenses head-on with them.", 1, 3)
end
if CountMy(arty) >= 1 then
AddTipOnce("Artillery excels at shelling enemy defenses from a safe distance. It is usually (though not always) relatively ineffective against mobile units.", 1, 3)
end
if CountMy(bomber) >= 1 then
AddTipOnce("Bombers require air repair pads to reload after each run. The Aircraft Plant comes with one free pad, but you should build more to avoid long waiting lines.", 2, 5)
end
local mlevel, mstore = spGetTeamResources(myTeam, "metal")
if mlevel/mstore >= 0.95 then
AddTip("Your metal storage is overflowing. You should get more buildpower and spend it.", 2, 5)
end
local elevel, estore = spGetTeamResources(myTeam, "energy")
if elevel < 80 and mlevel > elevel then
AddTip("Your energy reserves are running dangerously low. You should build more energy structures.", 3, 10)
end
--always tips
AddTipOnce("Left click to select a unit.\nKeep button down to drag a selection box.",1)
AddTipOnce("Left click in empty area to deselect units.",1)
AddTipOnce("Right click to issue default order.\nKeep the button down to draw a formation line.",1)
AddTipOnce("Left click an action on the menu in the bottom-left, then left click in the terrain to give specific orders.",1)
AddTipOnce("Use the SHIFT key to enqueue orders.",1)
AddTipOnce("Multiple constructors can build a structure together, or assist a factory.",2)
AddTipOnce("Keep making constructors and nanotowers as needed to spend your resources.", 2)
AddTipOnce("Avoid having large amounts of metal sitting in your storage. Spend it on combat units.", 2)
--end
end
local function GetGeneralTip(index)
local index = index or generalTipsIndex
if index > #generalTips then index = 1 end
local str = generalTips[index]
generalTipsIndex = index + 1
return str, nil
end
-- Pick a contextual tip
local function GetRandomTip()
GetTipsList()-- Create tipsList according to what's going on
if #tipsList >=2 then
local w=0
for t=1, #tipsList do
w=w+tipsList[t].weight
end
local d = w*math.random()
w=0
for t=1, #tipsList do
w=w+tipsList[t].weight
if w>=d then
local text, sound = tipsList[t].text,tipsList[t].sound
--table.remove(tipsList, t)
return text, sound
end
end
return "Could not fetch tip",nil
elseif #tipsList==1 then
local text, sound = tipsList[1].text,tipsList[1].sound
--tipsList[1] = nil
return text, sound
else
return GetGeneralTip()
end
end
-- need to regenerate textBox each time because TextBox:SetText() doesn't always do so
local function GenerateTextBox(str)
if textBox then window:RemoveChild(textBox) end
textBox = TextBox:New{
parent = window;
text = str or '',
x = image.width + image.x + 5,
y = 16;
width = window.width - 90 - 30,
valign = "ascender";
align = "left";
font = {
size = 12;
shadow = true;
},
}
end
local timer = 0
local function SetTip(str)
local str = str or GetRandomTip()
alreadyDisplayedTips[str] = true
--Spring.Echo("Writing tip: "..str)
GenerateTextBox(str)
timer = 0 -- resets update timer if called by something other than Update()
end
function widget:Update(dt)
timer = timer + dt
if timer > updateFrequency then
myTeam = spGetMyTeamID() -- just refresh for fun
SetTip()
timer = 0
end
end
--tells people not to build the expensive stuff early
function widget:UnitCommand(unitID, unitDefID, unitTeam, cmdID, cmdOpts, cmdParams)
if unitTeam ~= myTeam then return end
local t = Spring.GetGameSeconds()
local str
if superweapon[-cmdID] and t < TIMER_SUPERWEAPON then
str = WriteString(stringSuperweapon, -cmdID)
elseif adv_factory[-cmdID] and t < TIMER_ADV_FACTORY then
str = WriteString(stringAdvFactory, -cmdID)
elseif expensive_unit[-cmdID] and t < TIMER_EXPENSIVE_UNITS then
str = WriteString(stringExpensiveUnits, -cmdID)
end
if str then SetTip(str) end -- bring up the tip NOW
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if unitTeam ~= myTeam then return end
local name = UnitDefs[unitDefID].name
if unitTips[name] then unitTipsAvailable[name] = true end
end
function widget:UnitEnteredLos(unitID, unitTeam)
if not Spring.AreTeamsAllied(unitTeam, myTeam) then
local unitDef = UnitDefs[Spring.GetUnitDefID(unitID)]
if unitDef.canFly and not airSpotted then
SetTip(stringAirSpotted)
airSpotted = true
elseif unitDef.name == "corsilo" and not nukeSpotted then
SetTip(stringNukeSpotted)
nukeSpotted = true
end
end
end
function widget:Initialize()
if VFS.FileExists("LuaRules/Gadgets/mission.lua") then
widgetHandler:RemoveWidget() -- no need for tips in mission
end
-- setup Chili
Chili = WG.Chili
Button = Chili.Button
Label = Chili.Label
Window = Chili.Window
Panel = Chili.Panel
TextBox = Chili.TextBox
Image = Chili.Image
Control = Chili.Control
screen0 = Chili.Screen0
window = Window:New{
parent = screen0,
name = 'tipwindow';
width = 320,
height = 100,
right = 0;
bottom = 350;
dockable = true;
draggable = false,
resizable = false,
tweakDraggable = true,
tweakResizable = false,
minWidth = MIN_WIDTH,
minHeight = MIN_HEIGHT,
padding = {5, 0, 5, 0},
--itemMargin = {0, 0, 0, 0},
}
image = Image:New {
width = 80,
height = 80,
bottom = 10,
y= 10;
x= 5;
keepAspect = true,
file = "LuaUI/Images/advisor2.jpg";
parent = window;
}
GenerateTextBox()
close = Button:New {
width = 20,
height = 20,
y = 4,
right = 3,
parent=window;
padding = {0, 0, 0,0},
margin = {0, 0, 0, 0},
backgroundColor = {1, 1, 1, 0.4},
caption="";
tooltip = "Close Tip Dispenser";
OnClick = {function() Spring.SendCommands("luaui disablewidget ".. widgetName) end}
}
closeImage = Image:New {
width = 16,
height = 16,
x = 2,
y = 2,
keepAspect = false,
file = "LuaUI/Images/closex_16.png";
parent = close;
}
--sound code
--[[
local TipSoundFileList=VFS.DirList("sounds/tips")
for _,FileName in ipairs(TipSoundFileList) do
local ext=string.lower(string.sub(FileName,-4))
if ext==".ogg" or ext==".wav" then
local pref=string.match(FileName,".*%/(%d+)%.%a+")
if pref and (ext==".ogg" or SoundTable[tonumber(pref) or pref]==nil) then
SoundTable[tonumber(pref) or pref]=FileName
end
end
end
-- List the tips that do not contain side specific words:
for _,t in ipairs({87,88,711,712,713,11,12,21,22,23,24,25,26,27,71,72,73,81,82,83,84,85,86}) do
for s=1000,5000,1000 do
if not SoundTable[s+t] then-- If they have no side specific voice file
if not SoundTable[3000+t] then
Spring.Echo("No sound for tip #"..s+t..", default #"..(3000+t).." not available either!")
else
SoundTable[s+t]=SoundTable[3000+t]-- Make them use the Network voice
--Spring.Echo("No sound for tip #"..s+t..", defaulting to "..(3000+t))
end
end
end
end
local function QS(a)
if type(a)=="number" then
return tostring(a)
elseif type(a)=="string" then
return "\""..a.."\""
else
return "("..tostring(type(a))..")"..a
end
end
if Spring.IsDevLuaEnabled() then
Spring.Echo("<SoundTable>")
for key,value in pairs(SoundTable) do
Spring.Echo("Soundtable["..QS(key).."]="..QS(value))
end
Spring.Echo("</SoundTable>")
end
--]]
SetTip()
end
| gpl-2.0 |
rlcevg/Zero-K | gamedata/modularcomms/weapons/disintegrator.lua | 1 | 1066 | local name = "commweapon_disintegrator"
local weaponDef = {
name = [[Disintegrator]],
areaOfEffect = 48,
avoidFeature = false,
avoidFriendly = false,
avoidNeutral = false,
commandfire = true,
craterBoost = 1,
craterMult = 6,
customParams = {
muzzleEffectShot = [[custom:ataalaser]],
slot = [[3]],
manualfire = 1,
},
damage = {
default = 1400,
},
explosionGenerator = [[custom:DGUNTRACE]],
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 0,
noExplode = true,
noSelfDamage = true,
range = 200,
reloadtime = 20,
size = 6,
soundHit = [[explosion/ex_med6]],
soundStart = [[weapon/laser/heavy_laser4]],
soundTrigger = true,
turret = true,
weaponType = [[DGun]],
weaponVelocity = 300,
}
return name, weaponDef
| gpl-2.0 |
ViolyS/RayUI_VS | Interface/AddOns/RayUI_Options/libs/AceGUI-3.0-SharedMediaWidgets/Libs/AceGUI-3.0/widgets/AceGUIWidget-Button.lua | 1 | 2459 | --[[-----------------------------------------------------------------------------
Button Widget
Graphical Button.
-------------------------------------------------------------------------------]]
local Type, Version = "Button", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs = pairs
-- WoW APIs
local _G = _G
local PlaySound, CreateFrame, UIParent = PlaySound, CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Button_OnClick(frame, ...)
AceGUI:ClearFocus()
PlaySound("igMainMenuOption")
frame.obj:Fire("OnClick", ...)
end
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
-- restore default values
self:SetHeight(24)
self:SetWidth(200)
self:SetDisabled(false)
self:SetText()
end,
-- ["OnRelease"] = nil,
["SetText"] = function(self, text)
self.text:SetText(text)
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.frame:Disable()
else
self.frame:Enable()
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local name = "AceGUI30Button" .. AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Button", name, UIParent, "UIPanelButtonTemplate")
frame:Hide()
frame:EnableMouse(true)
frame:SetScript("OnClick", Button_OnClick)
frame:SetScript("OnEnter", Control_OnEnter)
frame:SetScript("OnLeave", Control_OnLeave)
local text = frame:GetFontString()
text:ClearAllPoints()
text:SetPoint("TOPLEFT", 15, -1)
text:SetPoint("BOTTOMRIGHT", -15, 1)
text:SetJustifyV("MIDDLE")
local widget = {
text = text,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
weirdouncle/QSanguosha-For-Hegemony-personal | lang/zh_CN/Audio/StandardWeiLines.lua | 7 | 3764 | --[[********************************************************************
Copyright (c) 2013-2015 Mogara
This file is part of QSanguosha-Hegemony.
This game is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3.0
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
See the LICENSE file for more details.
Mogara
*********************************************************************]]
return {
-- 曹操
["$jianxiong1"] = "宁教我负天下人,休教天下人负我!",
["$jianxiong2"] = "吾好梦中杀人!",
["$hujia1"] = "魏将何在?",
["$hujia2"] = "来人,护驾!",
["~caocao"] = "霸业未成,未成啊……",
-- 司马懿
["$guicai1"] = "天命?哈哈哈哈……",
["$guicai2"] = "吾乃天命之子!",
["$fankui1"] = "下次注意点。",
["$fankui2"] = "出来混,早晚要还的。",
["~simayi"] = "难道真是天命难违?",
-- 夏侯惇
["$ganglie1"] = "鼠辈,竟敢伤我!",
["$ganglie2"] = "以彼之道,还施彼身!",
["~xiahoudun"] = "两边都看不见了……",
-- 张辽
["$tuxi1"] = "哼,没想到吧!",
["$tuxi2"] = "拿来吧!",
["~zhangliao"] = "真的没想到……",
-- 许褚
["$luoyi1"] = "破!",
["$luoyi2"] = "谁来与我大战三百回合?",
["~xuchu"] = "冷,好冷啊……",
-- 郭嘉
["$tiandu1"] = "就这样吧。",
["$tiandu2"] = "哦?",
["$yiji1"] = "也好。",
["$yiji2"] = "罢了。",
["~guojia"] = "咳,咳……",
-- 甄姬
["$luoshen1"] = "仿佛兮若轻云之蔽月。",
["$luoshen2"] = "飘摇兮若流风之回雪。",
["$qingguo1"] = "凌波微步,罗袜生尘。",
["$qingguo2"] = "体迅飞凫,飘忽若神。",
["~zhenji"] = "悼良会之永绝兮,哀一逝而异乡。",
-- 曹仁
["$jushou1"] = "我先休息一会儿!",
["$jushou2"] = "尽管来吧!",
["~caoren"] = "实在是守不住了……",
-- 夏侯渊
["$shensu1"] = "吾善于千里袭人!",
["$shensu2"] = "取汝首级犹如探囊取物!",
["~xiahouyuan"] = "竟然比我还…快……",
["$jieming2"] = "我,永不背弃。",
["$jieming1"] = "秉忠贞之志,守谦退之节。",
["$quhu1"] = "此乃驱虎吞狼之计。",
["$quhu2"] = "借你之手,与他一搏吧。",
["~xunyu"] = "主公要臣死,臣不得不死。",
["$qiangxi1"] = "吃我一戟!",
["$qiangxi2"] = "看我三步之内,取你小命!",
["~dianwei"] = "主公,快走!",
["$xingshang1"] = "来,管杀还管埋!",
["$xingshang2"] = "我的是我的,你的,还是我的!",
["$fangzhu1"] = "给我翻过来!",
["$fangzhu2"] = "死罪可免,活罪难赦!",
["$songwei1"] = "仙福永享,寿与天齐!",
["$songwei2"] = "千秋万载,一统江山!",
["~caopi"] = "子建,子建……",
["$duanliang1"] = "截其源,断其粮,贼可擒也。",
["$duanliang2"] = "人是铁,饭是钢。",
["~xuhuang"] = "一顿不吃饿得慌。",
["$qiaobian1"] = "兵无常势,水无常形。", -- judge
["$qiaobian2"] = "用兵之道,变化万千。", -- draw
["~zhanghe"] = "呃,膝盖中箭了……",
-- 乐进
["cv:yuejin"] = "裤衩",
["$xiaoguo1"] = "骁勇果敢,每战必先!", -- 发动弃牌
["$xiaoguo2"] = "奋强突固,无坚不陷!", -- 弃置装备
["$xiaoguo3"] = "贼有防备,只伤皮毛,来日再战!", -- 受到伤害
["~yuejin"] = "戎马一生,何惧死乎!",
} | gpl-3.0 |
juefeix/lbcnn.torch | RandomBinaryConvolution.lua | 1 | 1187 | -- RandomBinaryConvolution.lua
local THNN = require 'nn.THNN'
local RandomBinaryConvolution, parent = torch.class('cudnn.RandomBinaryConvolution', 'cudnn.SpatialConvolution')
function RandomBinaryConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH)
parent.__init(self, nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH)
self:reset()
end
function RandomBinaryConvolution:reset()
local numElements = self.nInputPlane*self.nOutputPlane*self.kW*self.kH
self.weight = torch.CudaTensor(self.nOutputPlane,self.nInputPlane,self.kW,self.kH):fill(0)
self.weight = torch.reshape(self.weight,numElements)
local index = torch.Tensor(torch.floor(kSparsity*numElements)):random(numElements)
for i = 1,index:numel() do
self.weight[index[i]] = torch.bernoulli(0.5)*2-1
end
self.weight = torch.reshape(self.weight,self.nOutputPlane,self.nInputPlane,self.kW,self.kH)
self.bias = nil
self.gradBias = nil
self.gradWeight = torch.CudaTensor(self.nOutputPlane, self.nInputPlane, self.kH, self.kW):fill(0)
end
function RandomBinaryConvolution:accGradParameters(input, gradOutput, scale)
end
function RandomBinaryConvolution:updateParameters(learningRate)
end
| mit |
rlcevg/Zero-K | units/factorygunship.lua | 5 | 4568 | unitDef = {
unitname = [[factorygunship]],
name = [[Gunship Plant]],
description = [[Produces Gunships, Builds at 10 m/s]],
acceleration = 0,
brakeRate = 0,
buildCostEnergy = 600,
buildCostMetal = 600,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 9,
buildingGroundDecalSizeY = 7,
buildingGroundDecalType = [[factorygunship_aoplane.dds]],
buildoptions = {
[[armca]],
[[blastwing]],
[[bladew]],
[[armkam]],
[[gunshipsupport]],
[[armbrawl]],
[[blackdawn]],
[[corcrw]],
[[gunshipaa]],
[[corvalk]],
[[corbtrans]],
},
buildPic = [[factorygunship.png]],
buildTime = 600,
canMove = true,
canPatrol = true,
canstop = [[1]],
category = [[FLOAT UNARMED]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[86 86 86]],
collisionVolumeTest = 1,
collisionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
customParams = {
landflystate = [[0]],
description_de = [[Produziert Kampfhubschrauber, Baut mit 10 M/s]],
description_pl = [[Buduje statki powietrzne, moc 10 m/s]],
helptext = [[The Gunship Plant is designed for close air support. It includes a selection of transports for hauling land units around, and combat gunships which can perform a variety of offensive or defensive roles.]],
helptext_de = [[Kampfhubschrauber bieten aufgrund ihrer Beweglichkeit eine enorme Bandbreite an Einsetzbarkeit.]],
helptext_pl = [[Statki powietrzne zapewniaja miejscowe wsparcie lotnicze; wsrod jednostek oprocz statkow bojowych mozna takze znalezc transporty dla jednostek ladowych.]],
sortName = [[3]],
modelradius = [[43]],
},
energyMake = 0.3,
energyUse = 0,
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 7,
footprintZ = 7,
iconType = [[facgunship]],
idleAutoHeal = 5,
idleTime = 1800,
mass = 324,
maxDamage = 4000,
maxSlope = 15,
maxVelocity = 0,
metalMake = 0.3,
minCloakDistance = 150,
noAutoFire = false,
objectName = [[CORPLAS.s3o]],
seismicSignature = 4,
selfDestructAs = [[LARGE_BUILDINGEX]],
showNanoSpray = false,
side = [[CORE]],
sightDistance = 273,
smoothAnim = true,
TEDClass = [[PLANT]],
turnRate = 0,
useBuildingGroundDecal = true,
waterline = 0,
workerTime = 10,
yardMap = [[yyoooyy yoooooy ooooooo ooooooo ooooooo yoooooy yyoooyy]],
featureDefs = {
DEAD = {
description = [[Wreckage - Gunship Plant]],
blocking = true,
category = [[corpses]],
damage = 4000,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 7,
footprintZ = 6,
height = [[20]],
hitdensity = [[100]],
metal = 240,
object = [[corplas_dead.s3o]],
reclaimable = true,
reclaimTime = 240,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Gunship Plant]],
blocking = false,
category = [[heaps]],
damage = 4000,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 6,
footprintZ = 6,
height = [[4]],
hitdensity = [[100]],
metal = 120,
object = [[debris4x4c.s3o]],
reclaimable = true,
reclaimTime = 120,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ factorygunship = unitDef })
| gpl-2.0 |
yangboz/bugfree-bugfixes | CocosJSGame/frameworks/js-bindings/cocos2d-x/external/lua/luasocket/ltn12.lua | 71 | 8331 | -----------------------------------------------------------------------------
-- LTN12 - Filters, sources, sinks and pumps.
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local table = require("table")
local base = _G
local _M = {}
if module then -- heuristic for exporting a global package table
ltn12 = _M
end
local filter,source,sink,pump = {},{},{},{}
_M.filter = filter
_M.source = source
_M.sink = sink
_M.pump = pump
-- 2048 seems to be better in windows...
_M.BLOCKSIZE = 2048
_M._VERSION = "LTN12 1.0.3"
-----------------------------------------------------------------------------
-- Filter stuff
-----------------------------------------------------------------------------
-- returns a high level filter that cycles a low-level filter
function filter.cycle(low, ctx, extra)
base.assert(low)
return function(chunk)
local ret
ret, ctx = low(ctx, chunk, extra)
return ret
end
end
-- chains a bunch of filters together
-- (thanks to Wim Couwenberg)
function filter.chain(...)
local arg = {...}
local n = select('#',...)
local top, index = 1, 1
local retry = ""
return function(chunk)
retry = chunk and retry
while true do
if index == top then
chunk = arg[index](chunk)
if chunk == "" or top == n then return chunk
elseif chunk then index = index + 1
else
top = top+1
index = top
end
else
chunk = arg[index](chunk or "")
if chunk == "" then
index = index - 1
chunk = retry
elseif chunk then
if index == n then return chunk
else index = index + 1 end
else base.error("filter returned inappropriate nil") end
end
end
end
end
-----------------------------------------------------------------------------
-- Source stuff
-----------------------------------------------------------------------------
-- create an empty source
local function empty()
return nil
end
function source.empty()
return empty
end
-- returns a source that just outputs an error
function source.error(err)
return function()
return nil, err
end
end
-- creates a file source
function source.file(handle, io_err)
if handle then
return function()
local chunk = handle:read(_M.BLOCKSIZE)
if not chunk then handle:close() end
return chunk
end
else return source.error(io_err or "unable to open file") end
end
-- turns a fancy source into a simple source
function source.simplify(src)
base.assert(src)
return function()
local chunk, err_or_new = src()
src = err_or_new or src
if not chunk then return nil, err_or_new
else return chunk end
end
end
-- creates string source
function source.string(s)
if s then
local i = 1
return function()
local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1)
i = i + _M.BLOCKSIZE
if chunk ~= "" then return chunk
else return nil end
end
else return source.empty() end
end
-- creates rewindable source
function source.rewind(src)
base.assert(src)
local t = {}
return function(chunk)
if not chunk then
chunk = table.remove(t)
if not chunk then return src()
else return chunk end
else
table.insert(t, chunk)
end
end
end
function source.chain(src, f)
base.assert(src and f)
local last_in, last_out = "", ""
local state = "feeding"
local err
return function()
if not last_out then
base.error('source is empty!', 2)
end
while true do
if state == "feeding" then
last_in, err = src()
if err then return nil, err end
last_out = f(last_in)
if not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
elseif last_out ~= "" then
state = "eating"
if last_in then last_in = "" end
return last_out
end
else
last_out = f(last_in)
if last_out == "" then
if last_in == "" then
state = "feeding"
else
base.error('filter returned ""')
end
elseif not last_out then
if last_in then
base.error('filter returned inappropriate nil')
else
return nil
end
else
return last_out
end
end
end
end
end
-- creates a source that produces contents of several sources, one after the
-- other, as if they were concatenated
-- (thanks to Wim Couwenberg)
function source.cat(...)
local arg = {...}
local src = table.remove(arg, 1)
return function()
while src do
local chunk, err = src()
if chunk then return chunk end
if err then return nil, err end
src = table.remove(arg, 1)
end
end
end
-----------------------------------------------------------------------------
-- Sink stuff
-----------------------------------------------------------------------------
-- creates a sink that stores into a table
function sink.table(t)
t = t or {}
local f = function(chunk, err)
if chunk then table.insert(t, chunk) end
return 1
end
return f, t
end
-- turns a fancy sink into a simple sink
function sink.simplify(snk)
base.assert(snk)
return function(chunk, err)
local ret, err_or_new = snk(chunk, err)
if not ret then return nil, err_or_new end
snk = err_or_new or snk
return 1
end
end
-- creates a file sink
function sink.file(handle, io_err)
if handle then
return function(chunk, err)
if not chunk then
handle:close()
return 1
else return handle:write(chunk) end
end
else return sink.error(io_err or "unable to open file") end
end
-- creates a sink that discards data
local function null()
return 1
end
function sink.null()
return null
end
-- creates a sink that just returns an error
function sink.error(err)
return function()
return nil, err
end
end
-- chains a sink with a filter
function sink.chain(f, snk)
base.assert(f and snk)
return function(chunk, err)
if chunk ~= "" then
local filtered = f(chunk)
local done = chunk and ""
while true do
local ret, snkerr = snk(filtered, err)
if not ret then return nil, snkerr end
if filtered == done then return 1 end
filtered = f(done)
end
else return 1 end
end
end
-----------------------------------------------------------------------------
-- Pump stuff
-----------------------------------------------------------------------------
-- pumps one chunk from the source to the sink
function pump.step(src, snk)
local chunk, src_err = src()
local ret, snk_err = snk(chunk, src_err)
if chunk and ret then return 1
else return nil, src_err or snk_err end
end
-- pumps all data from a source to a sink, using a step function
function pump.all(src, snk, step)
base.assert(src and snk)
step = step or pump.step
while true do
local ret, err = step(src, snk)
if not ret then
if err then return nil, err
else return 1 end
end
end
end
return _M
| mit |
Amadiro/obtuse-tanuki | libs/material-love/init.lua | 2 | 2257 | local material = {
_VERSION = 'material-love v1.0.0',
_DESCRIPTION = 'Implementation of parts of the Material-Design spec, for LOVE',
_URL = 'https://www.github.com/Positive07/material-love',
_LICENSE = [[
The Material Design Icon font is Licensed under SIL Open Font License 1.1
https://github.com/Templarian/MaterialDesign/blob/master/license.txt
Some of the icons are designed by Google and are under Copyright CC-BY
https://github.com/google/material-design-icons/blob/master/LICENSE
The Material-Love Library is Licensed under MIT License (MIT)
Copyright (c) 2015 Pablo Mayobre
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]
}
local a = (...)..".libs."
local b = "libs/"..(...):gsub("%.","%/").."/assets"
local libs = {"patchy", "icons", "ripple", "colors", "roundrect", "image", "spinner", "shadow"}
for _,v in ipairs(libs) do
material[v] = require(a..v)
end
material.fab = require (a.."fab")(b)
material.roboto = require (a.."roboto")(b)
material.noto = require (a.."noto")(b)
material.shadow.load(b.."/shadow", material.patchy)
local drawicons = require (a.."drawicons")(b,material.icons,material.colors)
material.icons.draw = drawicons.draw
material.icons.font = drawicons.font
return material
| mit |
EliHar/Pattern_recognition | torch1/install/share/lua/5.1/pl/dir.lua | 5 | 15858 | --
-- Dependencies: `pl.utils`, `pl.path`, `pl.tablex`
--
-- Soft Dependencies: `alien`, `ffi` (either are used on Windows for copying/moving files)
-- @module pl.dir
local utils = require 'pl.utils'
local path = require 'pl.path'
local is_windows = path.is_windows
local tablex = require 'pl.tablex'
local ldir = path.dir
local chdir = path.chdir
local mkdir = path.mkdir
local rmdir = path.rmdir
local sub = string.sub
local os,pcall,ipairs,pairs,require,setmetatable,_G = os,pcall,ipairs,pairs,require,setmetatable,_G
local remove = os.remove
local append = table.insert
local wrap = coroutine.wrap
local yield = coroutine.yield
local assert_arg,assert_string,raise = utils.assert_arg,utils.assert_string,utils.raise
local List = utils.stdmt.List
local dir = {}
local function assert_dir (n,val)
assert_arg(n,val,'string',path.isdir,'not a directory',4)
end
local function assert_file (n,val)
assert_arg(n,val,'string',path.isfile,'not a file',4)
end
local function filemask(mask)
mask = utils.escape(mask)
return mask:gsub('%%%*','.+'):gsub('%%%?','.')..'$'
end
--- does the filename match the shell pattern?.
-- (cf. fnmatch.fnmatch in Python, 11.8)
-- @string file A file name
-- @string pattern A shell pattern
-- @treturn bool
-- @raise file and pattern must be strings
function dir.fnmatch(file,pattern)
assert_string(1,file)
assert_string(2,pattern)
return path.normcase(file):find(filemask(pattern)) ~= nil
end
--- return a list of all files which match the pattern.
-- (cf. fnmatch.filter in Python, 11.8)
-- @string files A table containing file names
-- @string pattern A shell pattern.
-- @treturn List(string) list of files
-- @raise file and pattern must be strings
function dir.filter(files,pattern)
assert_arg(1,files,'table')
assert_string(2,pattern)
local res = {}
local mask = filemask(pattern)
for i,f in ipairs(files) do
if f:find(mask) then append(res,f) end
end
return setmetatable(res,List)
end
local function _listfiles(dir,filemode,match)
local res = {}
local check = utils.choose(filemode,path.isfile,path.isdir)
if not dir then dir = '.' end
for f in ldir(dir) do
if f ~= '.' and f ~= '..' then
local p = path.join(dir,f)
if check(p) and (not match or match(p)) then
append(res,p)
end
end
end
return setmetatable(res,List)
end
--- return a list of all files in a directory which match the a shell pattern.
-- @string dir A directory. If not given, all files in current directory are returned.
-- @string mask A shell pattern. If not given, all files are returned.
-- @treturn {string} list of files
-- @raise dir and mask must be strings
function dir.getfiles(dir,mask)
assert_dir(1,dir)
if mask then assert_string(2,mask) end
local match
if mask then
mask = filemask(mask)
match = function(f)
return f:find(mask)
end
end
return _listfiles(dir,true,match)
end
--- return a list of all subdirectories of the directory.
-- @string dir A directory
-- @treturn {string} a list of directories
-- @raise dir must be a a valid directory
function dir.getdirectories(dir)
assert_dir(1,dir)
return _listfiles(dir,false)
end
local function quote_argument (f)
f = path.normcase(f)
if f:find '%s' then
return '"'..f..'"'
else
return f
end
end
local alien,ffi,ffi_checked,CopyFile,MoveFile,GetLastError,win32_errors,cmd_tmpfile
local function execute_command(cmd,parms)
if not cmd_tmpfile then cmd_tmpfile = path.tmpname () end
local err = path.is_windows and ' > ' or ' 2> '
cmd = cmd..' '..parms..err..cmd_tmpfile
local ret = utils.execute(cmd)
if not ret then
local err = (utils.readfile(cmd_tmpfile):gsub('\n(.*)',''))
remove(cmd_tmpfile)
return false,err
else
remove(cmd_tmpfile)
return true
end
end
local function find_ffi_copyfile ()
if not ffi_checked then
ffi_checked = true
local res
res,alien = pcall(require,'alien')
if not res then
alien = nil
res, ffi = pcall(require,'ffi')
end
if not res then
ffi = nil
return
end
else
return
end
if alien then
-- register the Win32 CopyFile and MoveFile functions
local kernel = alien.load('kernel32.dll')
CopyFile = kernel.CopyFileA
CopyFile:types{'string','string','int',ret='int',abi='stdcall'}
MoveFile = kernel.MoveFileA
MoveFile:types{'string','string',ret='int',abi='stdcall'}
GetLastError = kernel.GetLastError
GetLastError:types{ret ='int', abi='stdcall'}
elseif ffi then
ffi.cdef [[
int CopyFileA(const char *src, const char *dest, int iovr);
int MoveFileA(const char *src, const char *dest);
int GetLastError();
]]
CopyFile = ffi.C.CopyFileA
MoveFile = ffi.C.MoveFileA
GetLastError = ffi.C.GetLastError
end
win32_errors = {
ERROR_FILE_NOT_FOUND = 2,
ERROR_PATH_NOT_FOUND = 3,
ERROR_ACCESS_DENIED = 5,
ERROR_WRITE_PROTECT = 19,
ERROR_BAD_UNIT = 20,
ERROR_NOT_READY = 21,
ERROR_WRITE_FAULT = 29,
ERROR_READ_FAULT = 30,
ERROR_SHARING_VIOLATION = 32,
ERROR_LOCK_VIOLATION = 33,
ERROR_HANDLE_DISK_FULL = 39,
ERROR_BAD_NETPATH = 53,
ERROR_NETWORK_BUSY = 54,
ERROR_DEV_NOT_EXIST = 55,
ERROR_FILE_EXISTS = 80,
ERROR_OPEN_FAILED = 110,
ERROR_INVALID_NAME = 123,
ERROR_BAD_PATHNAME = 161,
ERROR_ALREADY_EXISTS = 183,
}
end
local function two_arguments (f1,f2)
return quote_argument(f1)..' '..quote_argument(f2)
end
local function file_op (is_copy,src,dest,flag)
if flag == 1 and path.exists(dest) then
return false,"cannot overwrite destination"
end
if is_windows then
-- if we haven't tried to load Alien/LuaJIT FFI before, then do so
find_ffi_copyfile()
-- fallback if there's no Alien, just use DOS commands *shudder*
-- 'rename' involves a copy and then deleting the source.
if not CopyFile then
src = path.normcase(src)
dest = path.normcase(dest)
local cmd = is_copy and 'copy' or 'rename'
local res, err = execute_command('copy',two_arguments(src,dest))
if not res then return false,err end
if not is_copy then
return execute_command('del',quote_argument(src))
end
return true
else
if path.isdir(dest) then
dest = path.join(dest,path.basename(src))
end
local ret
if is_copy then ret = CopyFile(src,dest,flag)
else ret = MoveFile(src,dest) end
if ret == 0 then
local err = GetLastError()
for name,value in pairs(win32_errors) do
if value == err then return false,name end
end
return false,"Error #"..err
else return true
end
end
else -- for Unix, just use cp for now
return execute_command(is_copy and 'cp' or 'mv',
two_arguments(src,dest))
end
end
--- copy a file.
-- @string src source file
-- @string dest destination file or directory
-- @bool flag true if you want to force the copy (default)
-- @treturn bool operation succeeded
-- @raise src and dest must be strings
function dir.copyfile (src,dest,flag)
assert_string(1,src)
assert_string(2,dest)
flag = flag==nil or flag
return file_op(true,src,dest,flag and 0 or 1)
end
--- move a file.
-- @string src source file
-- @string dest destination file or directory
-- @treturn bool operation succeeded
-- @raise src and dest must be strings
function dir.movefile (src,dest)
assert_string(1,src)
assert_string(2,dest)
return file_op(false,src,dest,0)
end
local function _dirfiles(dir,attrib)
local dirs = {}
local files = {}
for f in ldir(dir) do
if f ~= '.' and f ~= '..' then
local p = path.join(dir,f)
local mode = attrib(p,'mode')
if mode=='directory' then
append(dirs,f)
else
append(files,f)
end
end
end
return setmetatable(dirs,List),setmetatable(files,List)
end
local function _walker(root,bottom_up,attrib)
local dirs,files = _dirfiles(root,attrib)
if not bottom_up then yield(root,dirs,files) end
for i,d in ipairs(dirs) do
_walker(root..path.sep..d,bottom_up,attrib)
end
if bottom_up then yield(root,dirs,files) end
end
--- return an iterator which walks through a directory tree starting at root.
-- The iterator returns (root,dirs,files)
-- Note that dirs and files are lists of names (i.e. you must say path.join(root,d)
-- to get the actual full path)
-- If bottom_up is false (or not present), then the entries at the current level are returned
-- before we go deeper. This means that you can modify the returned list of directories before
-- continuing.
-- This is a clone of os.walk from the Python libraries.
-- @string root A starting directory
-- @bool bottom_up False if we start listing entries immediately.
-- @bool follow_links follow symbolic links
-- @return an iterator returning root,dirs,files
-- @raise root must be a directory
function dir.walk(root,bottom_up,follow_links)
assert_dir(1,root)
local attrib
if path.is_windows or not follow_links then
attrib = path.attrib
else
attrib = path.link_attrib
end
return wrap(function () _walker(root,bottom_up,attrib) end)
end
--- remove a whole directory tree.
-- @string fullpath A directory path
-- @return true or nil
-- @return error if failed
-- @raise fullpath must be a string
function dir.rmtree(fullpath)
assert_dir(1,fullpath)
if path.islink(fullpath) then return false,'will not follow symlink' end
for root,dirs,files in dir.walk(fullpath,true) do
for i,f in ipairs(files) do
local res, err = remove(path.join(root,f))
if not res then return nil,err end
end
local res, err = rmdir(root)
if not res then return nil,err end
end
return true
end
local dirpat
if path.is_windows then
dirpat = '(.+)\\[^\\]+$'
else
dirpat = '(.+)/[^/]+$'
end
local _makepath
function _makepath(p)
-- windows root drive case
if p:find '^%a:[\\]*$' then
return true
end
if not path.isdir(p) then
local subp = p:match(dirpat)
local ok, err = _makepath(subp)
if not ok then return nil, err end
return mkdir(p)
else
return true
end
end
--- create a directory path.
-- This will create subdirectories as necessary!
-- @string p A directory path
-- @return true on success, nil + errormsg on failure
-- @raise failure to create
function dir.makepath (p)
assert_string(1,p)
return _makepath(path.normcase(path.abspath(p)))
end
--- clone a directory tree. Will always try to create a new directory structure
-- if necessary.
-- @string path1 the base path of the source tree
-- @string path2 the new base path for the destination
-- @func file_fun an optional function to apply on all files
-- @bool verbose an optional boolean to control the verbosity of the output.
-- It can also be a logging function that behaves like print()
-- @return true, or nil
-- @return error message, or list of failed directory creations
-- @return list of failed file operations
-- @raise path1 and path2 must be strings
-- @usage clonetree('.','../backup',copyfile)
function dir.clonetree (path1,path2,file_fun,verbose)
assert_string(1,path1)
assert_string(2,path2)
if verbose == true then verbose = print end
local abspath,normcase,isdir,join = path.abspath,path.normcase,path.isdir,path.join
local faildirs,failfiles = {},{}
if not isdir(path1) then return raise 'source is not a valid directory' end
path1 = abspath(normcase(path1))
path2 = abspath(normcase(path2))
if verbose then verbose('normalized:',path1,path2) end
-- particularly NB that the new path isn't fully contained in the old path
if path1 == path2 then return raise "paths are the same" end
local i1,i2 = path2:find(path1,1,true)
if i2 == #path1 and path2:sub(i2+1,i2+1) == path.sep then
return raise 'destination is a subdirectory of the source'
end
local cp = path.common_prefix (path1,path2)
local idx = #cp
if idx == 0 then -- no common path, but watch out for Windows paths!
if path1:sub(2,2) == ':' then idx = 3 end
end
for root,dirs,files in dir.walk(path1) do
local opath = path2..root:sub(idx)
if verbose then verbose('paths:',opath,root) end
if not isdir(opath) then
local ret = dir.makepath(opath)
if not ret then append(faildirs,opath) end
if verbose then verbose('creating:',opath,ret) end
end
if file_fun then
for i,f in ipairs(files) do
local p1 = join(root,f)
local p2 = join(opath,f)
local ret = file_fun(p1,p2)
if not ret then append(failfiles,p2) end
if verbose then
verbose('files:',p1,p2,ret)
end
end
end
end
return true,faildirs,failfiles
end
--- return an iterator over all entries in a directory tree
-- @string d a directory
-- @return an iterator giving pathname and mode (true for dir, false otherwise)
-- @raise d must be a non-empty string
function dir.dirtree( d )
assert( d and d ~= "", "directory parameter is missing or empty" )
local exists, isdir = path.exists, path.isdir
local sep = path.sep
local last = sub ( d, -1 )
if last == sep or last == '/' then
d = sub( d, 1, -2 )
end
local function yieldtree( dir )
for entry in ldir( dir ) do
if entry ~= "." and entry ~= ".." then
entry = dir .. sep .. entry
if exists(entry) then -- Just in case a symlink is broken.
local is_dir = isdir(entry)
yield( entry, is_dir )
if is_dir then
yieldtree( entry )
end
end
end
end
end
return wrap( function() yieldtree( d ) end )
end
--- Recursively returns all the file starting at _path_. It can optionally take a shell pattern and
-- only returns files that match _pattern_. If a pattern is given it will do a case insensitive search.
-- @string start_path A directory. If not given, all files in current directory are returned.
-- @string pattern A shell pattern. If not given, all files are returned.
-- @treturn List(string) containing all the files found recursively starting at _path_ and filtered by _pattern_.
-- @raise start_path must be a directory
function dir.getallfiles( start_path, pattern )
assert_dir(1,start_path)
pattern = pattern or ""
local files = {}
local normcase = path.normcase
for filename, mode in dir.dirtree( start_path ) do
if not mode then
local mask = filemask( pattern )
if normcase(filename):find( mask ) then
files[#files + 1] = filename
end
end
end
return setmetatable(files,List)
end
return dir
| mit |
medialab-prado/Interactivos-15-Ego | minetest-ego/games/adventuretest/mods/mobs/monsters/yeti.lua | 1 | 1152 | mobs:register_mob("mobs:snow_monster", {
type = "monster",
hp_min = 10,
hp_max = 35,
exp_min = 3,
exp_max = 35,
collisionbox = {-0.35,-1.0,-0.35, 0.35,0.8,0.35},
visual = "mesh",
mesh = "character.x",
textures = {"mobs_snow_monster.png"},
visual_size = {x=1, y=1},
makes_footstep_sound = true,
view_range = 15,
walk_velocity = 1,
run_velocity = 3,
damage = 2,
drops = { },
armor = 100,
drawtype = "front",
water_damage = 1,
lava_damage = 5,
light_damage = 2,
on_rightclick = nil,
attack_type = "dogfight",
animation = {
speed_normal = 30,
speed_run = 30,
stand_start = 0,
stand_end = 79,
walk_start = 168,
walk_end = 187,
run_start = 168,
run_end = 187,
punch_start = 200,
punch_end = 219,
},
jump = true,
sounds = {
death = "mobs_yeti_death",
random = "mobs_howl",
attack = "mobs_slash_attack",
},
step = 0.5,
avoid_nodes = {"default:water_source","default:water_flowing","campfire:campfire_burning","fire:basic_flame","fire:permanent_flame"},
avoid_range = 15,
})
mobs:register_spawn("mobs:snow_monster", {"default:snow","default:snow_with_grass","default:snowblock"}, 10, -1, 7000, 2, 31000)
| mit |
anholt/ValyriaTear | dat/effects/particles/shield_big_sprites.lua | 3 | 2438 | --defensive stance particle effect, big sprites version
-- Author: Bertram
systems = {}
systems[0] =
{
enabled = true,
emitter =
{
x = 0,
y = -128,
x2 = 0, --useless when using a circle shape
y2 = 0, --useless when using a circle shape
center_x = 0, --useless when using a circle shape
center_y = 0, --useless when using a circle shape
x_variation = 0,
y_variation = 0,
radius = 80,
shape = 'point',
omnidirectional = false,
orientation = -1.6, --up
outer_cone = 0.0,
inner_cone = 0,
initial_speed = 60,
initial_speed_variation = 0,
emission_rate = 1,
start_time = 0,
emitter_mode = 'burst',
spin = 'counter clockwise'
},
keyframes =
{
{ -- keyframe 1
size_x = 4.5,
size_y = 4.5,
color={0.2, 0.2, 1.0, 0.6},
rotation_speed = 0.0,
size_variation_x = 0.2,
size_variation_y = 0.2,
rotation_speed_variation = 0.0,
color_variation = {0.0, 0.0, 0.0, 0.0},
time = 0.0
},
{ -- keyframe 2
size_x = 0.3,
size_y = 0.3,
color = {0.5, 0.5, 1.0, 0.4},
rotation_speed = 0.0,
size_variation_x = 0.2,
size_variation_y = 0.2,
rotation_speed_variation = 0.0,
color_variation = {0.0, 0.0, 0.0, 0.0},
time = 1.0
}
},
animation_frames =
{
'img/effects/shield.png'
},
animation_frame_times =
{
16
},
blend_mode = 13,
system_lifetime = 0.3,
particle_lifetime = 0.5,
particle_lifetime_variation = 0.0,
max_particles = 5,
damping = 1,
damping_variation = 0,
acceleration_x = 0,
acceleration_y = 400,
acceleration_variation_x = 0,
acceleration_variation_y = 0,
wind_velocity_x = 0,
wind_velocity_y = 0,
wind_velocity_variation_x = 0,
wind_velocity_variation_y = 0,
tangential_acceleration = 0,
tangential_acceleration_variation = 0,
radial_acceleration = 0,
radial_acceleration_variation = 0,
user_defined_attractor = false,
attractor_falloff = 0.0,
smooth_animation = true,
modify_stencil = false,
stencil_op = 'INCR',
use_stencil = false,
random_initial_angle = true
}
| gpl-2.0 |
Jigoku/boxclip | src/entities/enemies/spike_timer.lua | 1 | 2999 | --[[
* Copyright (C) 2015 - 2022 Ricky K. Thomson
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* u should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
spike_timer = {}
table.insert(enemies.list, "spike_timer")
table.insert(editor.entities, {"spike_timer", "enemy"})
enemies.textures["spike_timer"] = {love.graphics.newImage( "data/images/enemies/spike.png"),}
function spike_timer:worldInsert(x,y,movespeed,movedist,dir,name)
if dir == 0 or dir == 2 then
width = enemies.textures[name][1]:getWidth()
height = enemies.textures[name][1]:getHeight()
end
if dir == 3 or dir == 1 then
width = enemies.textures[name][1]:getHeight()
height = enemies.textures[name][1]:getWidth()
end
table.insert(world.entities.enemy, {
x = x or 0,
y = y or 0,
xorigin = x,
yorigin = y,
w = width,
h = height,
group = "enemy",
type = name,
alive = true,
timer = 1.25,
timer_cycle = love.math.random(0,125)/100,
movedist = 0,
dir = dir,
movespeed = 0,
movedist = 0,
editor_canrotate = false
})
end
function spike_timer:checkCollision(enemy, dt)
enemy.timer_cycle = math.max(0, enemy.timer_cycle - dt)
if enemy.timer_cycle <= 0 then
if world:inview(enemy) then
sound:play(sound.effects["slice"])
end
enemy.switch = not enemy.switch
enemy.timer_cycle = enemy.timer
end
if enemy.switch then
enemy.y = math.max(enemy.yorigin,enemy.y - 400 *dt)
else
enemy.y = math.min(enemy.yorigin+enemy.h,enemy.y + 400 *dt)
end
-- NOT ACTIVE WHILST EDITING
if mode == "game" and player.alive and collision:check(player.newX,player.newY,player.w,player.h,
enemy.x+5,enemy.y+5,enemy.w-10,enemy.h-10) then
if enemy.y ~= enemy.yorigin+enemy.h then
-- only die when entity is active
player.yvel = -player.yvel
player:die(enemy.type)
end
end
end
function spike_timer:draw(enemy)
local texture = enemies.textures[enemy.type][1]
love.graphics.setColor(1,1,1,1)
local x,y = camera:toCameraCoords(enemy.xorigin, enemy.yorigin)
love.graphics.setScissor( x,y,enemy.w*camera.scale,enemy.h*camera.scale)
love.graphics.draw(texture, enemy.x, enemy.y, 0,1,1)
love.graphics.setScissor()
end
function spike_timer:drawdebug(enemy, i)
--bounds
love.graphics.setColor(1,0,0,1)
love.graphics.rectangle("line", enemy.x+5, enemy.y+5, enemy.w-10, enemy.h-10)
--hitbox
love.graphics.setColor(1,0.78,0.39,1)
love.graphics.rectangle("line", enemy.xorigin, enemy.yorigin, enemy.w, enemy.h*2)
end
| gpl-3.0 |
drmingdrmer/mysql-proxy-xp | lib/ro-balance.lua | 40 | 6646 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
-- slave aware load-balancer
--
-- * take slaves which are too far behind out of the rotation
-- * when we bring back the slave make sure it doesn't get
-- behind again too early (slow start)
-- * fallback to the master of all slaves are too far behind
-- * check if the backends are really configures as slave
-- * check if the io-thread is running at all
--
-- it is unclear how to
-- - handle requests sent to a backend with a io-thread off
-- - should we just close the connection to the client
-- and let it retry ?
-- - how to activate the backend again ?
-- - if a slave is lagging, we don't send queries to it
-- how do we figure out it is back again ?
require("proxy.auto-config")
local commands = require("proxy.commands")
if not proxy.global.config.ro_balance then
proxy.global.config.ro_balance = {
max_seconds_lag = 10, -- 10 seconds
max_bytes_lag = 10 * 1024, -- 10k
check_timeout = 2,
is_debug = true
}
end
if not proxy.global.lag then
proxy.global.lag = { }
end
local config = proxy.global.config.ro_balance
local backend_lag = proxy.global.lag
---
-- pick a backend server
--
-- we take the lag into account
-- * ignore backends which aren't configured
-- * ignore backends which don't have a io-thread running
-- * ignore backends that are too far behind
function connect_server()
local fallback_ndx
local slave_ndx
local unknown_slave_ndx
local slave_bytes_lag
for b_ndx = 1, #proxy.global.backends do
local backend = proxy.global.backends[b_ndx]
if backend.state ~= proxy.BACKEND_STATE_DOWN then
if backend.type == proxy.BACKEND_TYPE_RW then
-- the fallback
fallback_ndx = b_ndx
else
---
-- connect to the backends first we don't know yet
if not backend_lag[backend.dst.name] then
unknown_slave_ndx = b_ndx
elseif backend_lag[backend.dst.name].state == "running" then
if not slave_bytes_lag then
slave_ndx = b_ndx
slave_bytes_lag = backend_lag[backend.dst.name].slave_bytes_lag
elseif backend_lag[backend.dst.name].slave_bytes_lag < slave_bytes_lag then
slave_ndx = b_ndx
slave_bytes_lag = backend_lag[backend.dst.name].slave_bytes_lag
end
end
end
end
end
proxy.connection.backend_ndx = unknown_slave_ndx or slave_ndx or fallback_ndx
if config.is_debug then
print("(connect-server) using backend: " .. proxy.global.backends[proxy.connection.backend_ndx].dst.name)
end
end
function read_query(packet)
local cmd = commands.parse(packet)
local ret = proxy.global.config:handle(cmd)
if ret then return ret end
--
-- check the backend periodicly for its lag
--
-- translate the backend_ndx into its address
local backend_addr = proxy.global.backends[proxy.connection.backend_ndx].dst.name
backend_lag[backend_addr] = backend_lag[backend_addr] or {
state = "unchecked"
}
local now = os.time()
if config.is_debug then
print("(read_query) we are on backend: ".. backend_addr ..
" in state: " .. backend_lag[backend_addr].state)
end
if backend_lag[backend_addr].state == "unchecked" or
(backend_lag[backend_addr].state == "running" and
now - backend_lag[backend_addr].check_ts > config.check_timeout) then
if config.is_debug then
print("(read-query) unchecked, injecting a SHOW SLAVE STATUS")
end
proxy.queries:append(2, string.char(proxy.COM_QUERY) .. "SHOW SLAVE STATUS")
proxy.queries:append(1, packet)
return proxy.PROXY_SEND_QUERY
elseif proxy.global.backends[proxy.connection.backend_ndx].type == proxy.BACKEND_TYPE_RW or -- master
backend_lag[backend_addr].state == "running" then -- good slave
-- pass through
return
else
-- looks like this is a bad backend
-- let's get the client to connect to another backend
--
-- ... by closing the connection
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "slave-state is " .. backend_lag[backend_addr].state,
sqlstate = "08S01"
}
proxy.queries:reset()
-- and now we have to tell the proxy to close the connection
--
proxy.connection.connection_close = true
return proxy.PROXY_SEND_RESULT
end
end
function read_query_result(inj)
-- pass through the client query
if inj.id == 1 then
return
end
---
-- parse the SHOW SLAVE STATUS
--
-- what can happen ?
-- * no permissions (ERR)
-- * if not slave, result is empty
local res = inj.resultset
local fields = res.fields
local show_slave_status = {}
-- turn the resultset into local hash
for row in res.rows do
for field_id, field in pairs(row) do
show_slave_status[fields[field_id].name] = tostring(field)
if config.is_debug then
print(("[%d] '%s' = '%s'"):format(field_id, fields[field_id].name, tostring(field)))
end
end
end
local backend_addr = proxy.global.backends[proxy.connection.backend_ndx].dst.name
backend_lag[backend_addr].check_ts = os.time()
backend_lag[backend_addr].state = nil
if not show_slave_status["Master_Host"] then
-- this backend is not a slave
backend_lag[backend_addr].state = "noslave"
return proxy.PROXY_IGNORE_RESULT
end
if show_slave_status["Master_Log_File"] == show_slave_status["Relay_Master_Log_File"] then
-- ok, we use the same relay-log for reading and writing
backend_lag[backend_addr].slave_bytes_lag = tonumber(show_slave_status["Exec_Master_Log_Pos"]) - tonumber(show_slave_status["Read_Master_Log_Pos"])
else
backend_lag[backend_addr].slave_bytes_lag = nil
end
if show_slave_status["Seconds_Behind_Master"] then
backend_lag[backend_addr].seconds_lag = tonumber(show_slave_status["Seconds_Behind_Master"])
else
backend_lag[backend_addr].seconds_lag = nil
end
if show_slave_status["Slave_IO_Running"] == "No" then
backend_lag[backend_addr].state = "noiothread"
end
backend_lag[backend_addr].state = backend_lag[backend_addr].state or "running"
return proxy.PROXY_IGNORE_RESULT
end
| gpl-2.0 |
cailyoung/CommandPost | src/plugins/finalcutpro/watchers/version.lua | 1 | 3621 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- F I N A L C U T P R O V E R S I O N --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.watchers.version ===
---
--- This plugin will compare the current version of Final Cut Pro to the last one run.
--- If it has changed, watchers' `change` function is called.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local config = require("cp.config")
local fcp = require("cp.apple.finalcutpro")
local prop = require("cp.prop")
local watcher = require("cp.watcher")
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
-- plugins.finalcutpro.watchers.version._watchers -> table
-- Variable
-- Watchers.
mod._watchers = watcher.new("change")
--- plugins.finalcutpro.watchers.version.watch(events) -> watcher
--- Function
--- Watch Events.
---
--- Parameters:
--- * events - Events to watch
---
--- Returns:
--- * The Watcher
function mod.watch(events)
return mod._watchers:watch(events)
end
--- plugins.finalcutpro.watchers.version.unwatch(id) -> none
--- Function
--- Unwatch a watcher.
---
--- Parameters:
--- * id - The ID of the watcher to unwatch
---
--- Returns:
--- * None
function mod.unwatch(id)
return mod._watchers:unwatch(id)
end
--- plugins.finalcutpro.watchers.version.lastVersion <cp.prop: string>
--- Variable
--- The last Final Cut Pro version.
mod.lastVersion = config.prop("lastVersion")
--- plugins.finalcutpro.watchers.version.currentVersion <cp.prop: string>
--- Variable
--- The current Final Cut Pro version.
mod.currentVersion = prop(function()
return fcp:getVersion()
end)
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.watchers.version",
group = "finalcutpro",
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init()
return mod
end
--------------------------------------------------------------------------------
-- POST INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.postInit()
--------------------------------------------------------------------------------
-- Check for Final Cut Pro Updates:
--------------------------------------------------------------------------------
local lastVersion = mod.lastVersion()
local currentVersion = mod.currentVersion()
if lastVersion ~= nil and lastVersion ~= currentVersion then
mod._watchers:notify("change", lastVersion, currentVersion)
end
mod.lastVersion(currentVersion)
end
return plugin | mit |
notcake/glib | lua/glib/garrysmod/net/layer1/pinnednetinbuffer.lua | 2 | 1148 | local self = {}
GLib.Net.Layer1.PinnedNetInBuffer = GLib.MakeConstructor (self, GLib.Net.InBuffer)
function self:ctor (netInBuffer, position, data)
self.PositionOffset = position - 1
self.InBuffer = GLib.StringInBuffer (data)
end
function self:GetBytesRemaining ()
return self.InBuffer:GetBytesRemaining ()
end
function self:GetPosition ()
return self.InBuffer:GetPosition () + self.PositionOffset
end
function self:GetSize ()
return self.InBuffer:GetSize () + self.PositionOffset
end
function self:IsEndOfStream ()
return self.InBuffer:IsEndOfStream ()
end
function self:Pin ()
return self
end
function self:UInt8 ()
return self.InBuffer:UInt8 ()
end
function self:UInt16 ()
return self.InBuffer:UInt16 ()
end
function self:UInt32 ()
return self.InBuffer:UInt32 ()
end
function self:Int8 ()
return self.InBuffer:Int8 ()
end
function self:Int16 ()
return self.InBuffer:Int16 ()
end
function self:Int32 ()
return self.InBuffer:Int32 ()
end
function self:Bytes (length)
return self.InBuffer:Bytes (length)
end
function self:String ()
return self:StringN16 ()
end
function self:LongString ()
return self:StringN32 ()
end | gpl-3.0 |
rlcevg/Zero-K | LuaUI/Widgets/unit_auto_set_retreat60.lua | 6 | 5109 | local versionNumber = "1.3"
function widget:GetInfo()
return {
name = "Auto Set Retreat @60",
desc = "[v" .. string.format("%s", versionNumber ) .. "] Automatically set units when built to 'Retreat at 60% health', support /luaui reload (re-set retreat for every unit). Based on 'Auto Retreat' by CarRepairer",
author = "versus666",
date = "Oct 17, 2010",
license = "GNU GPL, v2 or later",
layer = 1,
enabled = false -- loaded by default?
}
end
--[[
Features:
_ Set every units exiting from factories to retreat @60% automatically. Don't trigger auto retreat for units being built.
_ Should set Commander to same value @ game start.
_ Is disabled when player go spec/use replay. NEED TESTING TO KNOW IF WIDGET STOPS (and need to be reactivated) WHEN RE-JOINING GAME AFTER CRASH !!
-- to do : probably fusion with unit_news.lua.
Changelog:
-- versus666, v1.3b (01mar2011) : fixed logic.
-- versus666, v1.3 (07jan2011) : changed detection logic to avoid to triger auto retreat for units being built.
-- versus666, v1.2 (01nov2010) : some changes.
-- versus666, v1.1 (18oct2010) : added debug mode and optimised.
-- versus666, v1.0 (17oct2010) : creation.
--]]
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--CMD_RETREAT = 10000-- taken from CarRepairer widget, see no use, maybe a workaround
local Echo = Spring.Echo
local spGetMyTeamID = Spring.GetMyTeamID
local spGetTeamUnits = Spring.GetTeamUnits
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitTeam = Spring.GetUnitTeam
local spGetUnitHealth = Spring.GetUnitHealth
local debug = false --generates debug message
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function IsSpec()
if (Spring.GetSpectatingState() or Spring.IsReplay()) and (not Spring.IsCheatingEnabled()) then
widgetHandler:RemoveWidget()
return true
end
end
function widget:Initialize()
MyTeam = spGetMyTeamID()
if (IsSpec()) then return false end
-- init already present units, probably superfluous if CREATED is checked too
--[[ for _,unitID in ipairs(spGetTeamUnits(spGetMyTeamID())) do
local unitDefID = spGetUnitDefID(unitID)
--local ud = UnitDefs[unitDefID]
--printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID " .. unitID .. " presence detected !")
checkUnits(unitID,unitDefID)
end
--]]
end
function checkUnits(unitID,unitDefID,unitTeam)
local ud = UnitDefs[unitDefID]
--printDebug("<unit_auto_retreat60>: checking " .. " with ID " .. unitID .. " in team " .. unitTeam)
if ((unitTeam == MyTeam) and ((ud ~= nil) and not (ud.isBuilding or not ud.canMove))) then -- test if exist and (is mobile and not a building) [I know buildings can't move but you never know]
WG['retreat'].addRetreatCommand(unitID, unitDefID, 2)
--printDebug("<unit_auto_retreat60>: set autorepair level 2 for " .. ud.humanName .. " with ID " .. unitID)
--else printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID ".. unitID .. " & team " .. unitTeam .." NOT suitable -> rejected !")
end
end
--[[ function widget:UnitFromFactory(unitID,unitDefID,unitTeam) -- every 'from factory' is created BUT autoretreat makes them retreat if retreat is set while they are built.
printDebug("<unit_auto_retreat60> : unit " .. unitID .. " from factory detected !")
checkUnits(unitID,unitDefID,unitTeam)
end ]]--
function widget:UnitCreated(unitID,unitDefID,unitTeam)-- needed for resurrected units/spawned units. check health to know if they are being built.
--local ud = UnitDefs[unitDefID]
--printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID " .. unitID .. " and team " .. unitTeam .. " created detected !")
local health = spGetUnitHealth(unitID)
--printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID " .. unitID .. " just created have a health of " .. health)
if health >= 0.3 then
checkUnits(unitID,unitDefID,unitTeam)
else
--printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID " .. unitID .. " is being built : do not touch yet.")
return end
end
function widget:UnitFinished(unitID,unitDefID,unitTeam)-- every 'from factory' is also finished after being created BUT autoretreat makes them retreat if retreat is set while they are built.
--local ud = UnitDefs[unitDefID]
--printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID ".. unitID .. " finished detected !")
checkUnits(unitID,unitDefID,unitTeam)
end
function widget:UnitTaken(unitID,unitDefID,unitTeam)-- needed for taken units
--local ud = UnitDefs[unitDefID]
--printDebug("<unit_auto_retreat60>: " .. ud.humanName .. " with ID ".. unitID .. " taken detected !")
checkUnits(unitID,unitDefID,unitTeam)
end
function printDebug( value )
if ( debug ) then Echo( value )
end
end
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------- | gpl-2.0 |
pielover88888/denice | lua/greeting.lua | 2 | 1117 | -- callback for user joining a channel
function greeting_join_callback(event, origin, params)
local nick = sql_escape(origin)
local t = sql_query_fetch("SELECT `Greeting` FROM `greeting` WHERE `Nick` = '" .. nick .. "'")
if #t > 0 and t[1].Greeting ~= nil and t[1].Greeting:len() > 0 then
irc_msg(params[1], t[1].Greeting)
end
end
register_callback("JOIN", "greeting_join_callback")
function greeting_set(event, origin, params)
local nick = sql_escape(origin)
local g = sql_escape(params[2])
local t = sql_query_fetch("SELECT `ID` FROM `greeting` WHERE `Nick` = '"..nick.."'")
if #t > 0 and event == "!setgreeting" then
sql_query_fetch("UPDATE `greeting` SET `Greeting`='"..g.."' WHERE `Nick`='"..nick.."'")
elseif event == "!setgreeting" then
sql_query_fetch("INSERT INTO `greeting` SET `Greeting`='"..g.."', `Nick`='"..nick.."'")
elseif event == "!unsetgreeting" then
sql_query_fetch("DELETE FROM `greeting` WHERE `Nick`='"..nick.."'")
end
irc_msg(params[1], "Greeting updated for "..origin)
end
register_command("setgreeting", "greeting_set")
register_command("unsetgreeting", "greeting_set")
| mit |
naserteam/hextor | plugins/invite.lua | 2 | 1202 | do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'این کاربر بن است')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'این کاربر بن گلوبال است')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'گروه خصوصی است'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_sudo(msg) then
return 'فقط سازنده ربات اجازه دعوت داارد'
end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^[!/]invite (.*)$"
},
run = run
}
end
| gpl-2.0 |
ViolyS/RayUI_VS | Interface/AddOns/WorldQuestTab/libs/LibStub/LibStub.lua | 184 | 1367 | -- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info
-- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
function LibStub:IterateLibraries() return pairs(self.libs) end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
| mit |
cailyoung/CommandPost | src/extensions/cp/strings/init.lua | 1 | 4388 | --- === cp.strings ===
---
--- Provides strings from (potentially) multiple sources, with support for loading from multiple languages.
---
--- ```lua
--- local strs = require("cp.strings").new():fromPlist("/Path/To/Resources/${language}.lproj/MYLocalization.strings")
--- local value = strs:find("en", "AKey")
--- ```
---
--- This will load the file for the specified language (replacing `${language}` with `"en"` in the path) and return the value.
--- Note: This will load the file on each request. To have values cached, use the `cp.strings` module and specify a `plist` as a source.
local log = require("hs.logger").new("strings")
local plistSrc = require("cp.strings.source.plist")
local _ = require("moses")
local mod = {}
mod.mt = {}
local UNFOUND = {}
--- cp.strings:from(source) -> cp.strings
--- Method
--- Adds the source to the strings sources.
---
--- Parameters:
--- * `source` - The source to add.
---
--- Returns:
--- * The current `cp.strings` instance.
function mod.mt:from(source)
table.insert(self._sources, source)
self._cache = {}
return self
end
--- cp.strings:fromPlist(pathPattern) -> cp.strings
--- Method
--- Convenience method for addedn a `plist` source to the strings instance.
---
--- Parameters:
--- * `pathPattern` - The path to load from. May contain a special `${language}` marker which will be replace with the provided langauge when searching.
---
--- Returns:
--- * The current `cp.strings` instance.
function mod.mt:fromPlist(pathPattern)
return self:from(plistSrc.new(pathPattern))
end
--- cp.strings:findInSources(language, key) -> string | nil
--- Method
--- Searches directly in the sources for the specified language/key combination.
---
--- Parameters:
--- * `language` - The language code to look for (e.g. `"en"`, or `"fr"`).
--- * `key` - The key to retrieve from the file.
---
--- Returns:
--- * The value of the key, or `nil` if not found.
function mod.mt:findInSources(language, key)
for _,source in ipairs(self._sources) do
local value = source:find(language, key)
if value then return value end
end
return nil
end
--- cp.strings:findKeysInSources(language, value) -> string | nil
--- Method
--- Searches directly in the sources for the specified language/value combination.
---
--- Parameters:
--- * `language` - The language code to look for (e.g. `"en"`, or `"fr"`).
--- * `value` - The value to search for.
---
--- Returns:
--- * The array of keys, or `{}` if not found.
function mod.mt:findKeysInSources(language, value)
local keys = {}
for i,source in ipairs(self._sources) do
keys = _.append(keys, source:findKeys(language, value))
end
return keys
end
--- cp.strings:find(language, key) -> string | nil
--- Method
--- Searches for the specified key in the specified language, caching the result when found.
---
--- Parameters:
--- * `language` - The language code to look for (e.g. `"en"`, or `"fr"`).
--- * `key` - The key to retrieve from the file.
---
--- Returns:
--- * The value of the key, or `nil` if not found.
function mod.mt:find(language, key)
-- ensure we have a cache for the specific language
self._cache[language] = self._cache[language] or {}
local cache = self._cache[language]
local value = cache[key]
if value == nil then
value = self:findInSources(language, key) or UNFOUND
cache[key] = value
end
if value == UNFOUND then
log.wf("Unable to find '%s' in '%s'", key, language)
return nil
else
return value
end
end
--- cp.strings:findKeysIn(language, value) -> string | nil
--- Method
--- Searches for the list of keys with a matching value, in the specified language.
---
--- Parameters:
--- * `language` - The language code to look for (e.g. `"en"`, or `"fr"`).
--- * `value` - The value to search for.
---
--- Returns:
--- * The array of keys, or `{}` if not found.
function mod.mt:findKeys(language, value)
-- NOTE: Not bothering to cache results currently, since it should not be a frequent operation.
return self:findKeysInSources(language, value)
end
--- cp.strings.new() -> cp.strings
--- Constructor
--- Creates a new `strings` instance. You should add sources with the [from](#from) or [fromPlist](#fromPlist) methods.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The new `cp.strings`
function mod.new()
local o = {
_sources = {},
_cache = {},
}
return setmetatable(o, {__index = mod.mt})
end
return mod | mit |
rlcevg/Zero-K | scripts/cruisemissile.lua | 7 | 1222 | include "constants.lua"
local base = piece 'base'
function script.AimWeapon1(heading, pitch) return true end
local function RemoveMissile()
Spring.SetUnitNoSelect(unitID, true)
Spring.SetUnitNoDraw(unitID, true)
Spring.SetUnitNoMinimap(unitID, true)
Spring.SetUnitHealth(unitID, {paralyze=99999999})
Spring.SetUnitCloak(unitID, 4)
Spring.SetUnitStealth(unitID, true)
Spring.SetUnitBlocking(unitID,false,false,false)
Sleep(2000)
-- keep alive for stats
Spring.SetUnitPosition(unitID,-9001, -9001)
-- Note that missiles intentionally remove their command 2s after firing
-- instead of immediately. This is to give some command feedback (that the
-- command actually was placed) and to show allies where the launch occurred.
Spring.GiveOrderToUnit(unitID, CMD.STOP, {}, 0)
GG.DestroyMissile(unitID, unitDefID)
Sleep(15000)
Spring.DestroyUnit(unitID, false, true)
end
function script.Shot()
StartThread(RemoveMissile)
end
function script.AimFromWeapon()
return base
end
function script.QueryWeapon()
return base
end
function script.Create()
Turn(base, x_axis, math.rad(-90))
Move(base, y_axis, 40)
end
function script.Killed(recentDamage, maxHealth)
Explode(base, sfxNone)
return 1
end
| gpl-2.0 |
ViolyS/RayUI_VS | Interface/AddOns/GnomishVendorShrinker/GnomishVendorShrinker.lua | 1 | 14155 |
local myname, ns = ...
local ItemSearch = LibStub('LibItemSearch-1.0')
local NUMROWS, ICONSIZE, GAP, SCROLLSTEP = 14, 17, 4, 5
for _,f in pairs{MerchantNextPageButton, MerchantPrevPageButton, MerchantPageText} do
f:Hide()
f.Show = f.Hide
end
local GVS = CreateFrame("frame", nil, MerchantFrame)
GVS:SetWidth(315)
GVS:SetHeight(294)
GVS:SetPoint("TOPLEFT", 8, -67)
GVS:SetScript("OnEvent", function(self, event, ...) if self[event] then return self[event](self, event, ...) end end)
GVS:Hide()
local function OnClick(self, button)
if IsAltKeyDown() and not self.altcurrency then self:BuyItem(true)
elseif IsModifiedClick() then HandleModifiedItemClick(GetMerchantItemLink(self:GetID()))
elseif self.altcurrency then
local id = self:GetID()
local link = GetMerchantItemLink(id)
self.link, self.texture = GetMerchantItemLink(id), self.icon:GetTexture()
MerchantFrame_ConfirmExtendedItemCost(self)
else self:BuyItem() end
end
local function PopoutOnClick(self, button)
local id = self:GetParent():GetID()
local link = GetMerchantItemLink(id)
if not link then return end
local _, _, _, vendorStackSize, numAvailable = GetMerchantItemInfo(id)
local maxPurchase = GetMerchantItemMaxStack(id)
local _, _, _, _, _, _, _, itemStackSize = GetItemInfo(link)
local size = numAvailable > 0 and numAvailable or itemStackSize
-- OpenStackSplitFrame(size, self, "LEFT", "RIGHT")
OpenStackSplitFrame(250, self, "LEFT", "RIGHT")
end
local function Purchase(id, quantity)
local _, _, _, vendorStackSize, numAvailable = GetMerchantItemInfo(id)
local maxPurchase = GetMerchantItemMaxStack(id)
if numAvailable > 0 and numAvailable < quantity then quantity = numAvailable end
local purchased = 0
while purchased < quantity do
local buyamount = math.min(maxPurchase, quantity - purchased)
purchased = purchased + buyamount
BuyMerchantItem(id, buyamount)
end
end
local function BuyItem(self, fullstack)
local id = self:GetID()
local link = GetMerchantItemLink(id)
if not link then return end
local _, _, _, vendorStackSize = GetMerchantItemInfo(id)
local _, _, _, _, _, _, _, itemStackSize = GetItemInfo(link)
Purchase(id, fullstack and itemStackSize or vendorStackSize or 1)
end
local function PopoutSplitStack(self, qty)
Purchase(self:GetParent():GetID(), qty)
end
local function OnEnter(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
if self.link then GameTooltip:SetHyperlink(self.link) else GameTooltip:SetMerchantCostItem(self.index, self.itemIndex) end
end
local function OnLeave()
GameTooltip:Hide()
ResetCursor()
end
local function GetCurencyCount(item)
for i=1,GetCurrencyListSize() do
local name, _, _, _, _, count = GetCurrencyListInfo(i)
if item == name then return count end
end
end
local function SetValue(self, text, icon, link)
local color = ""
local id = link and link:match("item:(%d+)")
self.link, self.index, self.itemIndex = nil
if id then self.link = link end
if id and (GetItemCount(id, true) or 0) < text or link and not id and (GetCurencyCount(link) or 0) < text then
color = "|cffff9999"
end
self.text:SetText(color..text)
self.icon:SetTexture(icon)
self:Show()
end
local function GetAltCurrencyFrame(frame)
for i,v in ipairs(frame.altframes) do if not v:IsShown() then return v end end
local anchor = #frame.altframes > 0 and frame.altframes[#frame.altframes].text
local f = CreateFrame('Frame', nil, frame)
f:SetWidth(ICONSIZE) f:SetHeight(ICONSIZE)
f:SetPoint("RIGHT", anchor or frame.ItemPrice, "LEFT")
f.icon = f:CreateTexture()
f.icon:SetWidth(ICONSIZE) f.icon:SetHeight(ICONSIZE)
f.icon:SetPoint("RIGHT")
f.text = f:CreateFontString(nil, nil, "NumberFontNormalSmall")
f.text:SetPoint("RIGHT", f.icon, "LEFT", -GAP/2, 0)
f.SetValue = SetValue
f:EnableMouse(true)
f:SetScript("OnEnter", OnEnter)
f:SetScript("OnLeave", OnLeave)
table.insert(frame.altframes, f)
return f
end
local function AddAltCurrency(frame, i)
local lastframe = frame.ItemPrice
for j=GetMerchantItemCostInfo(i),1,-1 do
local f = frame:GetAltCurrencyFrame()
local texture, price, link, name = GetMerchantItemCostItem(i, j)
f:SetValue(price, texture, link or name)
f.index, f.itemIndex, f.link = i, j
lastframe = f.text
end
frame.ItemName:SetPoint("RIGHT", lastframe, "LEFT", -GAP, 0)
end
local ROWHEIGHT = 21
local rows = {}
for i=1,NUMROWS do
local row = CreateFrame('Button', nil, GVS) -- base frame
row:SetHeight(ROWHEIGHT)
row:SetPoint("TOP", i == 1 and GVS or rows[i-1], i == 1 and "TOP" or "BOTTOM")
row:SetPoint("LEFT")
row:SetPoint("RIGHT", -19, 0)
row.BuyItem = BuyItem
row:SetHighlightTexture("Interface\\HelpFrame\\HelpFrameButton-Highlight")
row:GetHighlightTexture():SetTexCoord(0, 1, 0, 0.578125)
row:RegisterForClicks("AnyUp")
row:SetScript('OnClick', OnClick)
row:RegisterForDrag("LeftButton")
row:SetScript('OnDragStart', function(self, button)
MerchantFrame.extendedCost = nil
PickupMerchantItem(self:GetID())
if self.extendedCost then MerchantFrame.extendedCost = self end
end)
local backdrop = row:CreateTexture(nil, "BACKGROUND")
backdrop:SetAllPoints()
backdrop:SetTexture("Interface\\Tooltips\\UI-Tooltip-Background")
row.backdrop = backdrop
local icon = CreateFrame('Frame', nil, row)
icon:SetHeight(ICONSIZE)
icon:SetWidth(ICONSIZE)
icon:SetPoint('LEFT', 2, 0)
row.icon = icon:CreateTexture(nil, "BORDER")
row.icon:SetAllPoints()
local ItemName = row:CreateFontString(nil, nil, "GameFontNormalSmall")
ItemName:SetPoint('LEFT', icon, "RIGHT", GAP, 0)
ItemName:SetJustifyH('LEFT')
row.ItemName = ItemName
local popout = CreateFrame("Button", nil, row)
popout:SetPoint("RIGHT")
popout:SetWidth(ROWHEIGHT/2) popout:SetHeight(ROWHEIGHT)
popout:SetNormalTexture("Interface\\PaperDollInfoFrame\\UI-GearManager-FlyoutButton")
popout:SetHighlightTexture("Interface\\PaperDollInfoFrame\\UI-GearManager-FlyoutButton")
popout:GetNormalTexture():SetTexCoord(0.15625, 0.5, 0.84375, 0.5, 0.15625, 0, 0.84375, 0)
popout:GetHighlightTexture():SetTexCoord(0.15625, 1, 0.84375, 1, 0.15625, 0.5, 0.84375, 0.5)
popout:SetScript("OnClick", PopoutOnClick)
popout.SplitStack = PopoutSplitStack
row.popout = popout
local ItemPrice = row:CreateFontString(nil, nil, "NumberFontNormal")
ItemPrice:SetPoint('RIGHT', popout, "LEFT", -2, 0)
row.ItemPrice = ItemPrice
row.altframes = {}
row.AddAltCurrency, row.GetAltCurrencyFrame = AddAltCurrency, GetAltCurrencyFrame
row:SetScript('OnEnter', function(self)
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:SetMerchantItem(self:GetID())
GameTooltip_ShowCompareItem()
MerchantFrame.itemHover = self:GetID()
if IsModifiedClick("DRESSUP") then ShowInspectCursor() else ResetCursor() end
end)
row:SetScript('OnLeave', function()
GameTooltip:Hide()
ResetCursor()
MerchantFrame.itemHover = nil
end)
rows[i] = row
end
local default_grad = {0,1,0,0.75, 0,1,0,0} -- green
local grads = setmetatable({
red = {1,0,0,0.75, 1,0,0,0},
[1] = {1,1,1,0.75, 1,1,1,0}, -- white
[2] = default_grad, -- green
[3] = {0.5,0.5,1,1, 0,0,1,0}, -- blue
[4] = {1,0,1,0.75, 1,0,1,0}, -- purple
[7] = {1,.75,.5,0.75, 1,.75,.5,0}, -- heirloom
}, {__index = function(t,i) t[i] = default_grad return default_grad end})
local RECIPE = GetItemClassInfo(LE_ITEM_CLASS_RECIPE)
local GARRISON_ICON = {[1001489] = true, [1001490] = true, [1001491] = true}
local quality_colors = setmetatable({}, {__index = function() return "|cffffffff" end})
for i=0,7 do quality_colors[i] = "|c".. select(4, GetItemQualityColor(i)) end
local function ShowMerchantItem(row, i)
local name, itemTexture, itemPrice, itemStackCount, numAvailable, isUsable, extendedCost = GetMerchantItemInfo(i)
local link = GetMerchantItemLink(i)
local color = quality_colors.default
row.backdrop:Hide()
if not isUsable then
row.backdrop:SetGradientAlpha("HORIZONTAL", unpack(grads.red))
row.backdrop:Show()
end
if link then
local name, link2, quality, iLevel, reqLevel, class, subclass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo(link)
local id = ns.ids[link]
local is_heirloom = ns.is_six_one and C_Heirloom.IsItemHeirloom(id)
color = quality_colors[quality]
if is_heirloom or class == RECIPE or GARRISON_ICON[texture] then
if ns.knowns[link] then
color = quality_colors[0]
row.backdrop:Hide()
else
row.backdrop:SetGradientAlpha("HORIZONTAL", unpack(grads[quality]))
row.backdrop:Show()
end
end
end
row.icon:SetTexture(itemTexture)
row.ItemName:SetText((numAvailable > -1 and ("["..numAvailable.."] ") or "").. color.. (name or "<Loading item data>").. (itemStackCount > 1 and ("|r x"..itemStackCount) or ""))
for i,v in pairs(row.altframes) do v:Hide() end
row.altcurrency = extendedCost
if extendedCost then
row:AddAltCurrency(i)
row.link, row.texture, row.extendedCost = link, itemTexture, true
end
if itemPrice > 0 then
row.ItemPrice:SetText(ns.GSC(itemPrice))
row.Price = itemPrice
end
if extendedCost and (itemPrice <= 0) then
row.ItemPrice:SetText()
row.Price = 0
elseif extendedCost and (itemPrice > 0) then
row.ItemPrice:SetText(ns.GSC(itemPrice))
else
row.ItemName:SetPoint("RIGHT", row.ItemPrice, "LEFT", -GAP, 0)
row.extendedCost = nil
end
if isUsable then row.icon:SetVertexColor(1, 1, 1) else row.icon:SetVertexColor(.9, 0, 0) end
row:SetID(i)
row:Show()
end
local scrollbar = LibStub("tekKonfig-Scroll").new(GVS, 0, SCROLLSTEP)
local offset = 0
local searchstring
local function Refresh()
local n = GetMerchantNumItems()
local row, n_searchmatch = 1, 0
for i=1,n do
local link = GetMerchantItemLink(i)
if ItemSearch:Find(link, searchstring) then
if n_searchmatch >= offset and n_searchmatch < offset + NUMROWS then
ShowMerchantItem(rows[row], i)
row = row + 1
end
n_searchmatch = n_searchmatch + 1
end
end
scrollbar:SetMinMaxValues(0, math.max(0, n_searchmatch - NUMROWS))
for i=row,NUMROWS do
rows[i]:Hide()
end
end
GVS.CURRENCY_DISPLAY_UPDATE = Refresh
GVS.BAG_UPDATE = Refresh
GVS.MERCHANT_UPDATE = Refresh
local editbox = CreateFrame('EditBox', nil, GVS)
editbox:SetAutoFocus(false)
editbox:SetPoint("BOTTOMLEFT", GVS, "TOPLEFT", 55, 9)
editbox:SetWidth(105)
editbox:SetHeight(32)
editbox:SetFontObject('GameFontHighlightSmall')
local left = editbox:CreateTexture(nil, "BACKGROUND")
left:SetWidth(8) left:SetHeight(20)
left:SetPoint("LEFT", -5, 0)
left:SetTexture("Interface\\Common\\Common-Input-Border")
left:SetTexCoord(0, 0.0625, 0, 0.625)
local right = editbox:CreateTexture(nil, "BACKGROUND")
right:SetWidth(8) right:SetHeight(20)
right:SetPoint("RIGHT", 0, 0)
right:SetTexture("Interface\\Common\\Common-Input-Border")
right:SetTexCoord(0.9375, 1, 0, 0.625)
local center = editbox:CreateTexture(nil, "BACKGROUND")
center:SetHeight(20)
center:SetPoint("RIGHT", right, "LEFT", 0, 0)
center:SetPoint("LEFT", left, "RIGHT", 0, 0)
center:SetTexture("Interface\\Common\\Common-Input-Border")
center:SetTexCoord(0.0625, 0.9375, 0, 0.625)
editbox:SetScript("OnEscapePressed", editbox.ClearFocus)
editbox:SetScript("OnEnterPressed", editbox.ClearFocus)
editbox:SetScript("OnEditFocusGained", function(self)
if not searchstring then
self:SetText("")
self:SetTextColor(1,1,1,1)
end
end)
editbox:SetScript("OnEditFocusLost", function(self)
if self:GetText() == "" then
self:SetText("Search...")
self:SetTextColor(0.75, 0.75, 0.75, 1)
end
end)
editbox:SetScript("OnTextChanged", function(self)
local t = self:GetText()
searchstring = t ~= "" and t ~= "Search..." and t:lower() or nil
Refresh()
end)
editbox:SetScript("OnShow", function(self)
self:SetText("Search...")
self:SetTextColor(0.75, 0.75, 0.75, 1)
end)
editbox:SetScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_BOTTOMRIGHT")
GameTooltip:AddLine("Enter an item name to search")
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine("Type search:", "bop boe bou", nil,nil,nil, 255,255,255)
GameTooltip:AddDoubleLine(" ", "boa quest", 255,255,255, 255,255,255)
GameTooltip:AddDoubleLine(" ", "ilvl>=378 ilvl=359", 255,255,255, 255,255,255)
GameTooltip:AddDoubleLine(" ", "q=rare q<4", 255,255,255, 255,255,255)
GameTooltip:AddDoubleLine(" ", "t:leather t:shield", 255,255,255, 255,255,255)
GameTooltip:AddDoubleLine("Modifiers:", "& Match both", nil,nil,nil, 255,255,255)
GameTooltip:AddDoubleLine(" ", "| Match either", 255,255,255, 255,255,255)
GameTooltip:AddDoubleLine(" ", "! Do not match", 255,255,255, 255,255,255)
GameTooltip:Show()
end)
editbox:SetScript("OnLeave", function(self)
GameTooltip:Hide()
end)
local f = scrollbar:GetScript("OnValueChanged")
scrollbar:SetScript("OnValueChanged", function(self, value, ...)
offset = math.floor(value)
Refresh()
return f(self, value, ...)
end)
local offset = 0
GVS:EnableMouseWheel(true)
GVS:SetScript("OnMouseWheel", function(self, value) scrollbar:SetValue(scrollbar:GetValue() - value * SCROLLSTEP) end)
GVS:SetScript("OnShow", function(self, noreset)
local max = math.max(0, GetMerchantNumItems() - NUMROWS)
scrollbar:SetMinMaxValues(0, max)
scrollbar:SetValue(noreset and math.min(scrollbar:GetValue(), max) or 0)
Refresh()
GVS:RegisterEvent("BAG_UPDATE")
GVS:RegisterEvent("MERCHANT_UPDATE")
GVS:RegisterEvent("CURRENCY_DISPLAY_UPDATE")
end)
GVS:SetScript("OnHide", function()
GVS:UnregisterEvent("BAG_UPDATE")
GVS:UnregisterEvent("MERCHANT_UPDATE")
GVS:UnregisterEvent("CURRENCY_DISPLAY_UPDATE")
if StackSplitFrame:IsVisible() then StackSplitFrame:Hide() end
end)
-- Reanchor the buyback button, it acts weird when switching tabs otherwise...
MerchantBuyBackItem:ClearAllPoints()
MerchantBuyBackItem:SetPoint("BOTTOMRIGHT", -7, 33)
local function Show()
for i=1,12 do _G["MerchantItem"..i]:Hide() end
if GVS:IsShown() then GVS:GetScript("OnShow")(GVS, true) else GVS:Show() end
end
hooksecurefunc("MerchantFrame_UpdateMerchantInfo", Show)
hooksecurefunc("MerchantFrame_UpdateBuybackInfo", function()
GVS:Hide()
for i=1,12 do _G["MerchantItem"..i]:Show() end
end)
if MerchantFrame:IsVisible() and MerchantFrame.selectedTab == 1 then Show() end
LibStub("tekKonfig-AboutPanel").new(nil, "GnomishVendorShrinker")
| mit |
ViolyS/RayUI_VS | Interface/AddOns/RayUI/mini/BonusRollPreview/encounters/Legion.lua | 1 | 6176 | local _, ns = ...
ns.encounterInfo = ns.encounterInfo or {}
ns.itemBlacklist = ns.itemBlacklist or {}
-- http://www.wowhead.com/spells/uncategorized/name:Bonus?filter=84:109:16;1:6:7;::
for spellID, encounterInfo in next, {
--- World
[227128] = {1790, 822, 14}, -- Ana-Mouz
[227129] = {1774, 822, 14}, -- Calamir
[227130] = {1789, 822, 14}, -- Drugon the Frostblood
[227131] = {1795, 822, 14}, -- Flotsam
[227132] = {1770, 822, 14}, -- Humongris
[227133] = {1769, 822, 14}, -- Levantus
[227134] = {1783, 822, 14}, -- Na'zak the Fiend
[227135] = {1749, 822, 14}, -- Nithogg
[227136] = {1763, 822, 14}, -- Shar'thos
[227137] = {1756, 822, 14}, -- The Soultakers
[227138] = {1796, 822, 14}, -- Withered J'im
[242969] = {1956, 822, 14}, -- Apocron
[242970] = {1883, 822, 14}, -- Brutallus
[242971] = {1884, 822, 14}, -- Malificus
[242972] = {1885, 822, 14}, -- Si'vash
--- Raids
-- The Emerald Nightmare
[221046] = {1703, 768, nil, 14}, -- Nythendra
[221047] = {1738, 768, nil, 14}, -- Il'gynoth, Heart of Corruption
[221048] = {1744, 768, nil, 14}, -- Elerethe Renferal
[221049] = {1667, 768, nil, 14}, -- Ursoc
[221050] = {1704, 768, nil, 14}, -- Dragons of Nightmare
[221052] = {1750, 768, nil, 14}, -- Cenarius
[221053] = {1726, 768, nil, 14}, -- Xavius
-- Trial of Valor
[232466] = {1819, 861, nil, 14}, -- Odyn
[232467] = {1830, 861, nil, 14}, -- Guarm
[232468] = {1829, 861, nil, 14}, -- Helya
-- The Nighthold
[232436] = {1706, 786, nil, 14}, -- Skorpyron
[232437] = {1725, 786, nil, 14}, -- Chronomatic Anomaly
[232438] = {1731, 786, nil, 14}, -- Trilliax
[232439] = {1751, 786, nil, 14}, -- Spellblade Aluriel
[232440] = {1762, 786, nil, 14}, -- Tichondrius
[232441] = {1713, 786, nil, 14}, -- Krosus
[232442] = {1761, 786, nil, 14}, -- High Botanist Tel'arn
[232443] = {1732, 786, nil, 14}, -- Star Augur Etraeus
-- Grand Magistrix Elisande needs special handling
[232445] = {1737, 786, nil, 14}, -- Gul'dan
-- Tomb of Sargeras
[240655] = {1862, 875, nil, 14}, -- Goroth
[240656] = {1867, 875, nil, 14}, -- Demonic Inquisition
[240657] = {1856, 875, nil, 14}, -- Harjatan
[240658] = {1861, 875, nil, 14}, -- Mistress Sassz'ine
[240659] = {1903, 875, nil, 14}, -- Sisters of the Moon
[240660] = {1896, 875, nil, 14}, -- The Desolate Host
[240661] = {1897, 875, nil, 14}, -- Maiden of Vigilance
[240662] = {1873, 875, nil, 14}, -- Fallen Avatar
[240663] = {1898, 875, nil, 14}, -- Kil'jaeden
--- Dungeons
-- Return to Karazhan (Mythic)
[232102] = {1820, 860, 23}, -- Opera Hall: Wikket
[232103] = {1826, 860, 23}, -- Opera Hall: Westfall Story
[232104] = {1827, 860, 23}, -- Opera Hall: Beautiful Beast
[232101] = {1825, 860, 23}, -- Maiden of Virtue
[232099] = {1835, 860, 23}, -- Attumen the Huntsman
[232100] = {1837, 860, 23}, -- Moroes
[232105] = {1836, 860, 23}, -- The Curator
[232106] = {1817, 860, 23}, -- Shade of Medivh
[232107] = {1818, 860, 23}, -- Mana Devourer
[232108] = {1838, 860, 23}, -- Viz'aduum the Watcher
-- Assault on Violet Hold (Mythic)
[226656] = {1693, 777, 23}, -- Festerface
[226657] = {1694, 777, 23}, -- Shivermaw
[226658] = {1702, 777, 23}, -- Blood-Princess Thal'ena
[226659] = {1686, 777, 23}, -- Mindflayer Kaahrj
[226660] = {1688, 777, 23}, -- Millificent Manastorm
[226661] = {1696, 777, 23}, -- Anub'esset
[226662] = {1711, 777, 23}, -- Sael'orn
[226663] = {1697, 777, 23}, -- Fel Lord Betrug
-- Black Rook Hold (Mythic)
[226595] = {1518, 740, 23}, -- The Amalgam of Souls
[226599] = {1653, 740, 23}, -- Illysanna Ravencrest
[226600] = {1664, 740, 23}, -- Smashspite the Hateful
[226603] = {1672, 740, 23}, -- Lord Kur'talos Ravencrest
-- Court of Stars (Mythic)
[226605] = {1718, 800, 23}, -- Patrol Captain Gerdo
[226607] = {1719, 800, 23}, -- Talixae Flamewreath
[226608] = {1720, 800, 23}, -- Advisor Melandrus
-- Darkheart Thicket (Mythic)
[226610] = {1654, 762, 23}, -- Archdruid Glaidalis
[226611] = {1655, 762, 23}, -- Oakheart
[226613] = {1656, 762, 23}, -- Dresaron
[226615] = {1657, 762, 23}, -- Shade of Xavius
-- Eye of Azshara (Mythic)
[226618] = {1480, 716, 23}, -- Warlord Parjesh
[226619] = {1490, 716, 23}, -- Lady Hatecoil
[226621] = {1491, 716, 23}, -- King Deepbeard
[226622] = {1479, 716, 23}, -- Serpentrix
[226624] = {1492, 716, 23}, -- Wrath of Azshara
-- Halls of Valor (Mythic)
[226636] = {1485, 721, 23}, -- Hymdall
[226626] = {1486, 721, 23}, -- Hyrja
[226627] = {1487, 721, 23}, -- Fenryr
[226629] = {1488, 721, 23}, -- God-King Skovald
[226625] = {1489, 721, 23}, -- Odyn
-- Maw of Souls (Mythic)
[226637] = {1502, 727, 23}, -- Ymiron, the Fallen King
[226638] = {1512, 727, 23}, -- Harbaron
[226639] = {1663, 727, 23}, -- Helya
-- Neltharion's Lair (Mythic)
[226640] = {1662, 767, 23}, -- Rokmora
[226641] = {1665, 767, 23}, -- Ularogg Cragshaper
[226642] = {1673, 767, 23}, -- Naraxas
[226643] = {1687, 767, 23}, -- Dargul the Underking
-- The Arcway (Mythic)
[226644] = {1497, 726, 23}, -- Ivanyr
[226645] = {1498, 726, 23}, -- Corstilax
[226646] = {1499, 726, 23}, -- General Xakal
[226647] = {1500, 726, 23}, -- Nal'tira
[226648] = {1501, 726, 23}, -- Advisor Vandros
-- Vault of the Wardens (Mythic)
[226649] = {1467, 707, 23}, -- Tirathon Saltheril
[226652] = {1695, 707, 23}, -- Inquisitor Tormentorum
[226653] = {1468, 707, 23}, -- Ash'golm
[226654] = {1469, 707, 23}, -- Glazer
[226655] = {1470, 707, 23}, -- Cordana Felsong
-- Cathedral of Eternal Night (Mythic)
[244782] = {1905, 900, 23}, -- Agronox
[244783] = {1906, 900, 23}, -- Thrashbite the Scornful
[244784] = {1904, 900, 23}, -- Domatrax
[244786] = {1878, 900, 23}, -- Mephistroth
} do
ns.encounterInfo[spellID] = encounterInfo
end
for _, itemID in next, {
-- Mounts
} do
ns.itemBlacklist[itemID] = true
end
| mit |
avatani83/teleseed | plugins/invite.lua | 1 | 1192 | do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'User is banned.')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'User is globaly banned.')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'Group is private.'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_momod(msg) then
return
end
--if not is_admin(msg) then -- For admins only !
--return 'Only admins can invite.'
--end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^/invite (.*)$"
},
run = run
}
end
| gpl-2.0 |
cxiao/chdkptp-old | lua/extras/msgtest.lua | 5 | 4789 | --[[
Copyright (C) 2010-2014 <reyalp (at) gmail dot com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
]]
--[[
a script for stressing the usb layer and message system
usage:
!m=require'extras/msgtest'
!m.test(options)
opions:{
size=number -- initial message size
sizemax=number -- end message size
sizestep=number -- increment size by N
count=number -- number of messages
verbose=number -- level of verbosity, 2 = print a line for each message
checkmem=bool -- check free memory and lua allocated memory for each message
memverbose=bool -- print memory stats for each message
gc=string|nil -- garbage collection mode, 'step', 'collect' or nil
}
example
!m.test{size=100,sizeinc=10,sizemax=200,verbose=0,memverbose=true,checkmem=true,gc='step'}
]]
local m={}
local default_opts = {
verbose = 2,
checkmem = false,
memverbose = false,
gc = nil,
}
m.opts = {}
m.detailmsg = util.make_msgf( function() return m.opts.verbose end, 2)
function m.init_test()
m.fail_count = 0
m.run_count = 0
if m.opts.checkmem then
m.memstats = {
free={},
count={}
}
end
m.load()
m.set_gc(m.opts.gc)
m.t0=ustime.new()
return true
end
function m.fmt_memstats(stats)
local min=1000000000
local max=0
local total = 0
if #stats == 0 then
return "no stats"
end
for i,v in ipairs(stats) do
if v > max then
max = v
end
if v < min then
min = v
end
total = total + v
end
return string.format("min %d max %d avg %d",min, max, total/#stats)
end
function m.finish_test()
m.quit()
printf("ran %d fail %d time %.4f\n",m.run_count,m.fail_count,ustime.diff(m.t0)/1000000)
if m.opts.checkmem then
printf("free (bytes): %s\n",m.fmt_memstats(m.memstats.free))
printf("lua alloc (kb): %s\n",m.fmt_memstats(m.memstats.count))
end
return (m.fail_count == 0)
end
function m.load()
con:exec('msg_shell:run()',{libs={'msg_shell','serialize'}})
con:write_msg([[exec
msg_shell.read_msg_timeout = nil
msg_shell.default_cmd=function(msg)
if msgtest_gc then
collectgarbage(msgtest_gc)
end
write_usb_msg(msg)
end
msg_shell.cmds.memstats=function()
write_usb_msg(serialize({mem=get_meminfo().free_size,lmem=collectgarbage('count')}))
end
]])
end
function m.quit()
con:write_msg('quit')
end
function m.test_msg(len)
m.run_count = m.run_count + 1
local s=string.rep('x',len)
con:write_msg(s)
local r = con:wait_msg({mtype='user'})
if s == r.value then
m.detailmsg('ok\n')
else
m.fail_count = m.fail_count + 1
printf('failed\nmsg %d len %d not equal\n',m.run_count,len)
end
if m.opts.checkmem then
con:write_msg('memstats')
r = con:wait_msg({mtype='user',munserialize=true})
table.insert(m.memstats.free,r.mem)
table.insert(m.memstats.count,r.lmem)
if m.opts.memverbose then
printf('free:%d lua alloc:%d kb\n',r.mem,r.lmem)
end
end
end
function m.test(opts)
opts = util.extend_table(util.extend_table({},default_opts),opts)
m.opts = opts
if not opts.size then
error("missing size")
end
if not opts.count then
if opts.sizeinc and opts.sizemax then
opts.count = math.floor((opts.sizemax - opts.size )/opts.sizeinc)
else
error("missing count")
end
end
if opts.sizeinc == 0 then
opts.sizeinc = nil
end
if opts.sizeinc and not opts.sizemax then
opts.sizemax = opts.size + opts.count * opts.sizeinc
end
local size = opts.size
printf("testing %d messages size %d",opts.count,size)
if opts.sizeinc and opts.sizeinc > 0 then
printf("-%d, inc %d",opts.sizemax,opts.sizeinc)
end
printf("\n")
m.init_test()
for i=1,opts.count do
m.detailmsg("send %d...",i)
local status,err=pcall(m.test_msg,size)
if not status then
printf("%s\n",tostring(err))
printf("aborted, communication error\n")
m.finish_test()
return false
end
if opts.sizeinc and size < opts.sizemax then
size = size + opts.sizeinc
end
end
return m.finish_test()
end
function m.set_gc(mode)
if not mode then
mode='nil'
else
mode = '"'..mode..'"'
end
con:write_msg('exec msgtest_gc='..mode)
end
return m
| gpl-2.0 |
cailyoung/CommandPost | src/plugins/finalcutpro/notifications/pushover.lua | 1 | 14601 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- P U S H O V E R N O T I F I C A T I O N S --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.notifications.pushover ===
---
--- Pushover Notifications Plugin.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local log = require("hs.logger").new("pushover")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local http = require("hs.http")
local json = require("hs.json")
local dialog = require("hs.dialog")
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local config = require("cp.config")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
-- PRIORITY -> number
-- Constant
-- The menubar position priority.
local PRIORITY = 100
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.finalcutpro.notifications.pushover.userAPIKey <cp.prop: string>
--- Field
--- User API Key
mod.userAPIKey = config.prop("pushoverUserAPIKey", nil)
--- plugins.finalcutpro.notifications.pushover.appAPIKey <cp.prop: string>
--- Field
--- Application API Key
mod.appAPIKey = config.prop("pushoverAppAPIKey", nil)
--- plugins.finalcutpro.notifications.pushover.apiValidated <cp.prop: boolean>
--- Field
--- Whether or not the API keys have been validated.
mod.apiValidated = config.prop("pushoverAPIValidated", false)
--- plugins.finalcutpro.notifications.pushover.enabled <cp.prop: boolean>
--- Field
--- Whether or not the plugin has been enabled.
mod.enabled = config.prop("pushoverNotificationsEnabled", false):watch(function() mod.update() end)
--- plugins.finalcutpro.notifications.pushover.validateAPIKeys(userKey, appKey) -> success, errorMessage
--- Function
--- Validates a Pushover User & Application API Key
---
--- Parameters:
--- * userKey - The User API Key as a string
--- * appKey - The Application API Key as a string
---
--- Returns:
--- * success - `true` if successful otherwise `false`
--- * errorMessage - a string containing any error messages
function mod.validateAPIKeys(userKey, appKey)
if not userKey or not appKey then
log.ef("Invalid User and/or Application API Key. This shouldn't happen.")
return false
end
local url = "https://api.pushover.net/1/users/validate.json"
local request = "token=" .. http.encodeForQuery(appKey) .. "&user=" .. http.encodeForQuery(userKey)
local status, body = http.doRequest(url, "post", request)
if status == 200 and string.match(body, [["status":1]]) then
return true
else
if pcall(function() json.decode(body) end) and json.decode(body)["errors"] then
local errors = json.decode(body)["errors"]
local errorMessage = ""
for i, v in ipairs(errors) do
errorMessage = " - " .. errorMessage .. v
if i ~= #errors then
errorMessage = errorMessage .. "\n"
end
end
return false, errorMessage
else
if status == 0 then
return false, " - " .. i18n("pushoverServerFailed") .. "\n - " .. i18n("areYouConnectedToTheInternet")
else
return false, " - " .. i18n("unknownError") .. " (" .. tostring(status) .. ")"
end
end
end
end
--- plugins.finalcutpro.notifications.pushover.update() -> none
--- Function
--- Enables or disables Pushover Notifications depending on the user's preferences.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.update()
if mod.enabled() then
if mod.watcherId == nil then
mod.watcherId = mod.notifications.watch({
success = mod.sendNotification,
failure = mod.sendNotification,
})
end
else
if mod.watcherId ~= nil then
mod.notifications.unwatch(mod.watcherId)
mod.watcherId = nil
end
end
end
--- plugins.finalcutpro.notifications.pushover.init() -> none
--- Function
--- Initialises the plugin.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.init(notifications)
mod.notifications = notifications
mod.update()
end
--- plugins.finalcutpro.notifications.pushover.sendNotification(message, [title]) -> none
--- Function
--- Sends a notification.
---
--- Parameters:
--- * message - The message you want to send as a string.
--- * [title] - An optional Title for the message as a string.
---
--- Returns:
--- * success - `true` if successful otherwise `false`
--- * errorMessage - a string containing any error messages
function mod.sendNotification(message, optionalTitle)
if not mod.apiValidated() or not mod.userAPIKey() or not mod.appAPIKey then
return false
end
local url = "https://api.pushover.net/1/messages.json"
local title = optionalTitle or http.encodeForQuery(string.upper(i18n("finalCutPro")))
message = http.encodeForQuery(message)
local request = "token=" .. mod.appAPIKey() .. "&user=" .. mod.userAPIKey() .. "&title=" .. title .. "&message=" .. message
local status, body = http.doRequest(url, "post", request)
if status == 200 and string.match(body, [["status":1]]) then
return true
else
if pcall(function() json.decode(body) end) and json.decode(body)["errors"] then
local errors = json.decode(body)["errors"]
local errorMessage = ""
for i, v in ipairs(errors) do
errorMessage = " - " .. errorMessage .. v
if i ~= #errors then
errorMessage = errorMessage .. "\n"
end
end
return false, errorMessage
else
if status == 0 then
return false, " - " .. i18n("pushoverServerFailed") .. "\n - " .. i18n("areYouConnectedToTheInternet")
else
return false, " - " .. i18n("unknownError") .. " (" .. tostring(status) .. ")"
end
end
end
end
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.notifications.pushover",
group = "finalcutpro",
dependencies = {
["finalcutpro.notifications.manager"] = "manager",
["core.preferences.panels.notifications"] = "prefs",
["core.preferences.manager"] = "prefsManager",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
mod.init(deps.manager)
--------------------------------------------------------------------------------
-- Setup Preferences Panel:
--------------------------------------------------------------------------------
if deps.prefs then
deps.prefs
:addContent(PRIORITY, [[
<style>
.validatePushover {
float:left;
margin-bottom: 10px;
}
.sendTestNotification {
clear: both;
float:left;
margin-top: 5px;
margin-bottom: 10px;
}
.pushoverButtons {
float:left;
margin-left: -15px;
margin-top: 5px;
margin-bottom: 10px;
}
</style>
]], true)
:addHeading(PRIORITY+1, i18n("pushoverNotifications"))
:addCheckbox(PRIORITY+2,
{
label = i18n("enablePushoverNotifications"),
onchange = function(_, params)
if mod.apiValidated() then
mod.enabled(params.checked)
else
if params.checked then
mod.enabled(false)
dialog.webviewAlert(deps.prefsManager.getWebview(), function()
deps.prefsManager.injectScript([[
document.getElementById("pushoverEnable").checked = false;
]])
end, i18n("invalidAPIKeysSupplied"), i18n("pushoverValidateFailed"), i18n("ok"))
end
end
end,
checked = mod.enabled,
id = "pushoverEnable",
}
)
:addButton(PRIORITY+3,
{
label = i18n("sendTestNotification"),
onclick = function()
if mod.apiValidated() then
local success, errorMessage = mod.sendNotification(i18n("thisIsATest"), i18n("testTitle"))
errorMessage = errorMessage or " - Unknown Error"
if not success then
dialog.webviewAlert(deps.prefsManager.getWebview(), function() end, i18n("notificationTestFailed"), i18n("notificationTestFailedMessage") .. "\n\n" .. errorMessage, i18n("ok"))
end
else
dialog.webviewAlert(deps.prefsManager.getWebview(), function() end, i18n("invalidAPIKeysSupplied"), i18n("pushoverTestFailed"), i18n("ok"))
end
end,
class = "sendTestNotification",
}
)
:addButton(PRIORITY+4,
{
label = i18n("pushoverSignup"),
onclick = function()
os.execute('open "https://pushover.net/login"')
end,
class = "pushoverButtons",
}
)
:addButton(PRIORITY+5,
{
label = i18n("getCommandPostPushoverAPIKey"),
onclick = function()
os.execute('open "https://pushover.net/apps/clone/commandpost"')
end,
class = "pushoverButtons",
}
)
:addTextbox(PRIORITY+6,
{
label = i18n("userAPIKey") .. ":",
value = mod.userAPIKey(),
class = "api",
id = "pushoverUserAPIKey",
onchange = function(_, params)
mod.apiValidated(false)
deps.prefsManager.injectScript([[
document.getElementById("pushoverEnable").checked = false;
]])
mod.enabled(false)
mod.userAPIKey(params.value)
end,
}
)
:addTextbox(PRIORITY+7,
{
label = i18n("applicationAPIKey") .. ":",
value = mod.appAPIKey(),
class = "api",
id = "pushoverAppAPIKey",
onchange = function(_, params)
mod.apiValidated(false)
mod.appAPIKey(params.value)
deps.prefsManager.injectScript([[
document.getElementById("pushoverEnable").checked = false;
]])
mod.enabled(false)
end,
}
)
:addButton(PRIORITY+8,
{
label = i18n("validate"),
onclick = function()
if not mod.userAPIKey() or not mod.appAPIKey() then
dialog.webviewAlert(deps.prefsManager.getWebview(), function() end, i18n("needUserAndAppAPIKey"), i18n("pleaseTryAgain"), i18n("ok"))
else
local success, errorMessage = mod.validateAPIKeys(mod.userAPIKey(), mod.appAPIKey())
if success then
dialog.webviewAlert(deps.prefsManager.getWebview(), function() end, i18n("success") .. "!", i18n("apiKeysValidated"), i18n("ok"))
mod.apiValidated(true)
else
mod.enabled(false)
mod.apiValidated(false)
dialog.webviewAlert(deps.prefsManager.getWebview(), function() end, i18n("invalidAPIKeysSupplied"), i18n("notValidKeysAndError") .. errorMessage, i18n("ok"))
deps.prefsManager.injectScript([[
document.getElementById("pushoverEnable").checked = false;
]])
end
end
end,
class = "validatePushover"
}
)
end
return mod
end
return plugin
| mit |
VladimirTyrin/wireshark | test/lua/pcre_sets.lua | 35 | 6911 | -- See Copyright Notice in the file lrexlib.h
local luatest = require "luatest"
local N = luatest.NT
local function norm(a) return a==nil and N or a end
local function fill (n, m)
local t = {}
for i = n, m, -1 do table.insert (t, i) end
return t
end
local function set_named_subpatterns (lib, flg)
return {
Name = "Named Subpatterns",
Func = function (subj, methodname, patt, name1, name2)
local r = lib.new (patt)
local _,_,caps = r[methodname] (r, subj)
return norm(caps[name1]), norm(caps[name2])
end,
--{} N.B. subject is always first element
{ {"abcd", "tfind", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} },
{ {"abcd", "exec", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} },
}
end
local function set_f_find (lib, flg)
local cp1251 =
"ÀÁÂÃÄŨÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÜÛÚÝÞßàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ"
local loc = "Russian_Russia.1251"
return {
Name = "Function find",
Func = lib.find,
--{subj, patt, st,cf,ef,lo}, { results }
{ {"abcd", ".+", 5}, { N } }, -- failing st
{ {"abcd", ".*?"}, { 1,0 } }, -- non-greedy
{ {"abc", "aBC", N,flg.CASELESS}, { 1,3 } }, -- cf
{ {"abc", "aBC", N,"i" }, { 1,3 } }, -- cf
{ {"abc", "bc", N,flg.ANCHORED}, { N } }, -- cf
{ {"abc", "bc", N,N,flg.ANCHORED}, { N } }, -- ef
--{ {cp1251, "[[:upper:]]+", N,N,N, loc}, { 1,33} }, -- locale
--{ {cp1251, "[[:lower:]]+", N,N,N, loc}, {34,66} }, -- locale
}
end
local function set_f_match (lib, flg)
return {
Name = "Function match",
Func = lib.match,
--{subj, patt, st,cf,ef,lo}, { results }
{ {"abcd", ".+", 5}, { N }}, -- failing st
{ {"abcd", ".*?"}, { "" }}, -- non-greedy
{ {"abc", "aBC", N,flg.CASELESS}, {"abc" }}, -- cf
{ {"abc", "aBC", N,"i" }, {"abc" }}, -- cf
{ {"abc", "bc", N,flg.ANCHORED}, { N }}, -- cf
{ {"abc", "bc", N,N,flg.ANCHORED}, { N }}, -- ef
}
end
local function set_f_gmatch (lib, flg)
-- gmatch (s, p, [cf], [ef])
local pCSV = "(^[^,]*)|,([^,]*)"
local F = false
local function test_gmatch (subj, patt)
local out, guard = {}, 10
for a, b in lib.gmatch (subj, patt) do
table.insert (out, { norm(a), norm(b) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function gmatch",
Func = test_gmatch,
--{ subj patt results }
{ {"a\0c", "." }, {{"a",N},{"\0",N},{"c",N}} },--nuls in subj
{ {"", pCSV}, {{"",F}} },
{ {"12", pCSV}, {{"12",F}} },
{ {",", pCSV}, {{"", F},{F,""}} },
{ {"12,,45", pCSV}, {{"12",F},{F,""},{F,"45"}} },
{ {",,12,45,,ab,", pCSV}, {{"",F},{F,""},{F,"12"},{F,"45"},{F,""},{F,"ab"},{F,""}} },
}
end
local function set_f_split (lib, flg)
-- split (s, p, [cf], [ef])
local function test_split (subj, patt)
local out, guard = {}, 10
for a, b, c in lib.split (subj, patt) do
table.insert (out, { norm(a), norm(b), norm(c) })
guard = guard - 1
if guard == 0 then break end
end
return unpack (out)
end
return {
Name = "Function split",
Func = test_split,
--{ subj patt results }
{ {"a,\0,c", ","}, {{"a",",",N},{"\0",",",N},{"c",N,N}, } },--nuls in subj
{ {"ab", "$"}, {{"ab","",N}, {"",N,N}, } },
{ {"ab", "^|$"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } },
{ {"ab45ab","(?<=ab).*?"}, {{"ab","",N}, {"45ab","",N},{"",N,N}, } },
{ {"ab", "\\b"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } },
}
end
local function set_m_exec (lib, flg)
return {
Name = "Method exec",
Method = "exec",
--{patt,cf,lo}, {subj,st,ef} { results }
{ {".+"}, {"abcd",5}, { N } }, -- failing st
{ {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf
{ {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef
}
end
local function set_m_tfind (lib, flg)
return {
Name = "Method tfind",
Method = "tfind",
--{patt,cf,lo}, {subj,st,ef} { results }
{ {".+"}, {"abcd",5}, { N } }, -- failing st
{ {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf
{ {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef
}
end
local function set_m_dfa_exec (lib, flg)
return {
Name = "Method dfa_exec",
Method = "dfa_exec",
--{patt,cf,lo}, {subj,st,ef,os,ws} { results }
{ {".+"}, {"abcd"}, {1,{4,3,2,1},4} }, -- [none]
{ {".+"}, {"abcd",2}, {2,{4,3,2}, 3} }, -- positive st
{ {".+"}, {"abcd",-2}, {3,{4,3}, 2} }, -- negative st
{ {".+"}, {"abcd",5}, {N } }, -- failing st
{ {".*"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- [none]
{ {".*?"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- non-greedy
{ {"aBC",flg.CASELESS}, {"abc"}, {1,{3},1} }, -- cf
{ {"aBC","i" }, {"abc"}, {1,{3},1} }, -- cf
{ {"bc"}, {"abc"}, {2,{3},1} }, -- [none]
{ {"bc",flg.ANCHORED}, {"abc"}, {N } }, -- cf
{ {"bc"}, {"abc",N, flg.ANCHORED}, {N } }, -- ef
{ { "(.)b.(d)"}, {"abcd"}, {1,{4},1} }, --[captures]
{ {"abc"}, {"ab"}, {N } },
{ {"abc"}, {"ab",N,flg.PARTIAL}, {1,{2},flg.ERROR_PARTIAL} },
{ {".+"}, {string.rep("a",50),N,N,50,50}, {1, fill(50,26), 0}},-- small ovecsize
}
end
return function (libname, isglobal)
local lib = isglobal and _G[libname] or require (libname)
local flags = lib.flags ()
local sets = {
set_f_match (lib, flags),
set_f_find (lib, flags),
set_f_gmatch (lib, flags),
set_f_split (lib, flags),
set_m_exec (lib, flags),
set_m_tfind (lib, flags),
}
if flags.MAJOR >= 4 then
table.insert (sets, set_named_subpatterns (lib, flags))
end
if flags.MAJOR >= 6 then
table.insert (sets, set_m_dfa_exec (lib, flags))
end
return sets
end
| gpl-2.0 |
SneakyB/iceball | pkg/base/plug_pmfedit.lua | 4 | 5869 | --[[
This file is part of Ice Lua Components.
Ice Lua Components is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Ice Lua Components is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with Ice Lua Components. If not, see <http://www.gnu.org/licenses/>.
]]
print("pmfedit selected")
PMFEDIT_FNAME = "clsave/vol/editor.pmf"
BTSK_PMF_EDIT = SDLK_F2
BTSK_PMF_MOVEXN = SDLK_l
BTSK_PMF_MOVEXP = SDLK_j
BTSK_PMF_MOVEYN = SDLK_i
BTSK_PMF_MOVEYP = SDLK_k
BTSK_PMF_MOVEZN = SDLK_u
BTSK_PMF_MOVEZP = SDLK_o
BTSK_PMF_SIZEP = SDLK_EQUALS
BTSK_PMF_SIZEN = SDLK_MINUS
BTSK_PMF_ROTYN = SDLK_LEFTBRACKET
BTSK_PMF_ROTYP = SDLK_RIGHTBRACKET
BTSK_PMF_BLKSET = SDLK_g
BTSK_PMF_BLKCLEAR = SDLK_b
BTSK_PMF_QUICKLOAD = SDLK_F3
BTSK_PMF_QUICKSAVE = SDLK_F10
pmfedit_enabled = false
pmfedit_x = 0
pmfedit_y = 0
pmfedit_z = 0
pmfedit_size = 16
pmfedit_data = {}
pmfedit_model = common.model_new(1)
pmfedit_model, pmfedit_model_bone = common.model_bone_new(pmfedit_model)
pmfedit_data[#pmfedit_data+1] = {x=0,y=0,z=0,r=0,g=0,b=0,radius=1}
pmfedit_rx = 0
do
local old_tickhook = client.hook_tick
function pmfhook_tick(sec_current, sec_delta)
pmfedit_data[#pmfedit_data] = {
x=pmfedit_x,y=pmfedit_y,z=pmfedit_z-0.01,
r=math.sin(sec_current-2*math.pi/3)*127+128,
g=math.sin(sec_current)*127+128,
b=math.sin(sec_current+2*math.pi/3)*127+128,
radius=pmfedit_size}
common.model_bone_set(pmfedit_model, pmfedit_model_bone, "edit", pmfedit_data)
-- chain along
client.hook_tick = old_tickhook
local ret = old_tickhook(sec_current, sec_delta)
old_tickhook = client.hook_tick
client.hook_tick = pmfhook_tick
return ret
end
client.hook_tick = pmfhook_tick
local old_keyhook = client.hook_key
function client.hook_key(key, uni, state, modif)
if state then
if pmfedit_enabled then
if key == BTSK_PMF_MOVEXN then
pmfedit_x = pmfedit_x - pmfedit_size
elseif key == BTSK_PMF_MOVEXP then
pmfedit_x = pmfedit_x + pmfedit_size
elseif key == BTSK_PMF_MOVEYN then
pmfedit_y = pmfedit_y - pmfedit_size
elseif key == BTSK_PMF_MOVEYP then
pmfedit_y = pmfedit_y + pmfedit_size
elseif key == BTSK_PMF_MOVEZN then
pmfedit_z = pmfedit_z - pmfedit_size
elseif key == BTSK_PMF_MOVEZP then
pmfedit_z = pmfedit_z + pmfedit_size
elseif key == BTSK_PMF_SIZEN and pmfedit_size > 1 then
pmfedit_size = pmfedit_size - 1
elseif key == BTSK_PMF_SIZEP and pmfedit_size < 65535 then
pmfedit_size = pmfedit_size + 1
elseif key == SDLK_LEFTBRACKET then
pmfedit_rx = pmfedit_rx + math.pi/16
elseif key == SDLK_RIGHTBRACKET then
pmfedit_rx = pmfedit_rx - math.pi/16
elseif key == BTSK_PMF_BLKSET and #pmfedit_data < 4095 then
local plr = players[players.current]
pmfedit_data[#pmfedit_data].r = plr.blk_color[1]
pmfedit_data[#pmfedit_data].g = plr.blk_color[2]
pmfedit_data[#pmfedit_data].b = plr.blk_color[3]
pmfedit_data[#pmfedit_data+1] = pmfedit_data[#pmfedit_data]
elseif key == BTSK_PMF_BLKCLEAR then
if #pmfedit_data > 1 then
local i
local dx,dy,dz
local d
local mi,md
mi = 1
md = nil
-- find nearest piece
for i=1,#pmfedit_data-1 do
dx = pmfedit_data[i].x - pmfedit_x
dy = pmfedit_data[i].y - pmfedit_y
dz = pmfedit_data[i].z - pmfedit_z
d = dx*dx+dy*dy+dz*dz
if md == nil or d < md then
md = d
mi = i
end
end
-- delete it and move to it
pmfedit_x = pmfedit_data[mi].x
pmfedit_y = pmfedit_data[mi].y
pmfedit_z = pmfedit_data[mi].z
pmfedit_size = pmfedit_data[mi].radius
for i=mi,#pmfedit_data-1 do
pmfedit_data[i] = pmfedit_data[i+1]
end
pmfedit_data[#pmfedit_data] = nil
end
elseif key == BTSK_PMF_QUICKLOAD then
local xpmf = common.model_load_pmf(PMFEDIT_FNAME)
if xpmf then
common.model_free(pmfedit_model) -- YECCH! Forgot this line!
pmfedit_model = xpmf
pmfedit_model_bone = 0
local bname
bname, pmfedit_data = common.model_bone_get(pmfedit_model, pmfedit_model_bone)
pmfedit_data[#pmfedit_data+1] = {}
print("loaded!")
else
print("error during loading - NOT LOADED")
end
elseif key == BTSK_PMF_QUICKSAVE then
local xpt = pmfedit_data[#pmfedit_data]
pmfedit_data[#pmfedit_data] = nil
local bname, blah
bname, blah = common.model_bone_get(pmfedit_model, pmfedit_model_bone)
common.model_bone_set(pmfedit_model, pmfedit_model_bone, bname, pmfedit_data)
if common.model_save_pmf(pmfedit_model, PMFEDIT_FNAME) then
print("saved!")
else
print("error during saving - NOT SAVED")
end
pmfedit_data[#pmfedit_data+1] = xpt
end
end
if key == BTSK_PMF_EDIT then
pmfedit_enabled = not pmfedit_enabled
end
end
return old_keyhook(key, state, modif)
end
local old_renderhook = client.hook_render
-- I still believe the "Old Kenderhook" explanation for the meaning of O.K. is a load of crap. --GM
function client.hook_render()
if pmfedit_enabled then
font_mini.print(4,40,0x80FFFFFF,string.format(
"PMF - size: %-6i x: %-6i y: %6i z: %-6i - COUNT: %6i / rot: %3f"
,pmfedit_size
,pmfedit_x
,pmfedit_y
,pmfedit_z
,#pmfedit_data-1
,pmfedit_rx))
client.model_render_bone_local(pmfedit_model, pmfedit_model_bone,
0,0,1,
pmfedit_rx,0,0,
0.7)
end
return old_renderhook()
end
end
print("pmfedit loaded")
| gpl-3.0 |
cloudkick/ck-agent | src/lua/remote/test_util.lua | 1 | 4890 | -- -- Copyright 2012 Rackspace
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
module(..., package.seeall);
local lanes = require 'lanes'
local util = require 'util'
local buffer = alien.buffer(1024)
local getcwd = alien.default.getcwd
local error_msg = alien.buffer()
getcwd:types('string', 'string', 'int')
buffer = getcwd(error_msg, 1024)
local cwd = tostring(buffer)
local local_plugins_path_default = cwd .. '/tests/'
local munin_plugins_path_default = cwd .. '/tests/'
local function get_conf_object(local_plugins_path, munin_plugins_path)
local local_plugins_path = local_plugins_path or local_plugins_path_default
local munin_plugins_path = munin_plugins_path or munin_plugins_path_default
local conf = {}
conf.local_plugins_path = local_plugins_path
conf.munin_plugins_path = munin_plugins_path
return conf
end
function get_check_module(check_name, local_plugins_path, munin_plugins_path)
local rv, check = pcall(require, check_name)
if rv then
check.conf = get_conf_object(local_plugins_path, munin_plugins_path)
end
return rv, check
end
local function _run_test_tcp_server(ip, port, timeout, mode, mappings)
local ip = ip or '*'
local timeout = timeout or .01
local mode = mode or 'line'
local mappings = mappings or {}
local func = lanes.gen({ cancelstep = true}, function()
local client, line, err, command, response
socket = require 'socket'
local server = assert(socket.bind(ip, port))
local parse_line = function(line, client)
line = util.trim(line)
if util.table.contains(mappings, line, 'key') then
response = mappings[line]
client:send(response)
return true
end
return false
end
while true do
local client = server:accept()
local buffer = ''
local match = false
client:settimeout(timeout)
line, err = client:receive('*l')
while line do
if mode == 'line' then
if not err then
if parse_line(line, client) then
-- Match found, close the connection
client:close()
end
else
client:close()
end
end
buffer = buffer .. line .. '\n'
line, err = client:receive('*l')
end
if mode == 'line' then
client:close()
elseif mode == 'http' then
local buffer_lower = buffer:lower()
for key,value in pairs(mappings) do
local match_pattern = value['match_pattern']:lower()
if string.find(buffer_lower, match_pattern) ~= nil then
match = true
local response = value['response']
local response_len = string.len(response)
local header = 'HTTP/1.1 ' .. value['status_line'] .. '\n' ..
'Content-type: ' .. value['content_type'] .. '\n' ..
'Content-Length: ' .. response_len .. '\n\n'
client:send(header .. response)
break
end
end
end
if not match then
client:send('HTTP/1.1 404 Not found\n\n')
end
client:close()
end
end)
local lane = func()
-- Wait until the lane is running
while lane.status ~= 'running' do
end
return lane
end
function run_test_http_server(ip, port, timeout, routes)
local content
for key,value in pairs(routes) do
if value['file'] ~= nil then
local path = cwd .. '/tests/' .. value['file']
local file = assert(io.open(path, 'r'))
content = file:read('*a')
file:close()
else
content = value['response']
end
routes[key] = { ['match_pattern'] = value['method']:upper() .. ' ' .. key,
['status_line'] = value['status_line'],
['content_type'] = value['content_type'],
['response'] = content }
end
return _run_test_tcp_server(ip, port, timeout, 'http', routes)
end
function run_test_tcp_server(ip, port, timeout, command_mappings)
return _run_test_tcp_server(ip, port, timeout, 'line', command_mappings)
end
function kill_test_server(lane, timeout)
local timeout = timeout or 0
lane:cancel(timeout, true)
end
| apache-2.0 |
avdimdv/proxmark3 | client/scripts/dumptoemul.lua | 10 | 2939 | -- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bin = require('bin')
example = "script run dumptoemul -i dumpdata-foobar.bin"
author = "Martin Holst Swende"
usage = "script run dumptoemul [-i <file>] [-o <file>]"
desc =[[
This script takes a dumpfile from 'hf mf dump' and converts it to a format that can be used
by the emulator
Arguments:
-h This help
-i <file> Specifies the dump-file (input). If omitted, 'dumpdata.bin' is used
-o <filename> Specifies the output file. If omitted, <uid>.eml is used.
]]
-------------------------------
-- Some utilities
-------------------------------
---
-- A debug printout-function
function dbg(args)
if DEBUG then
print("###", args)
end
end
---
-- This is only meant to be used when errors occur
function oops(err)
print("ERROR: ",err)
end
---
-- Usage help
function help()
print(desc)
print("Example usage")
print(example)
end
local function convert_to_ascii(hexdata)
if string.len(hexdata) % 32 ~= 0 then
return oops(("Bad data, length should be a multiple of 32 (was %d)"):format(string.len(hexdata)))
end
local js,i = "[";
for i = 1, string.len(hexdata),32 do
js = js .."'" ..string.sub(hexdata,i,i+31).."',\n"
end
js = js .. "]"
return js
end
local function readdump(infile)
t = infile:read("*all")
--print(string.len(t))
len = string.len(t)
local len,hex = bin.unpack(("H%d"):format(len),t)
--print(len,hex)
return hex
end
local function convert_to_emulform(hexdata)
if string.len(hexdata) % 32 ~= 0 then
return oops(("Bad data, length should be a multiple of 32 (was %d)"):format(string.len(hexdata)))
end
local ascii,i = "";
for i = 1, string.len(hexdata),32 do
ascii = ascii ..string.sub(hexdata,i,i+31).."\n"
end
return string.sub(ascii,1,-1)
end
local function main(args)
local input = "dumpdata.bin"
local output
for o, a in getopt.getopt(args, 'i:o:h') do
if o == "h" then return help() end
if o == "i" then input = a end
if o == "o" then output = a end
end
-- Validate the parameters
local infile = io.open(input, "rb")
if infile == nil then
return oops("Could not read file ", input)
end
local dumpdata = readdump(infile)
-- The hex-data is now in ascii-format,
-- But first, check the uid
local uid = string.sub(dumpdata,1,8)
output = output or (uid .. ".eml")
-- Format some linebreaks
dumpdata = convert_to_emulform(dumpdata)
local outfile = io.open(output, "w")
if outfile == nil then
return oops("Could not write to file ", output)
end
outfile:write(dumpdata:lower())
io.close(outfile)
print(("Wrote an emulator-dump to the file %s"):format(output))
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)
| gpl-2.0 |
rlcevg/Zero-K | LuaRules/Gadgets/mod_stats.lua | 7 | 7701 | -- $Id: unit_noselfpwn.lua 3171 2008-11-06 09:06:29Z det $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Mod statistics",
desc = "Gathers mod statistics",
author = "Licho",
date = "29.3.2009",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if VFS.FileExists("mission.lua") then
-- stats are meaningless in missions
return
end
if (not gadgetHandler:IsSyncedCode()) then
return false -- silent removal
end
local damages = {} -- damages[attacker][victim] = { damage, emp}
local unitCounts = {} -- unitCounts[defID] = { created, destroyed}
local lastPara = {}
local plops = {}
local Echo = Spring.Echo
local spGameOver = Spring.IsGameOver
local spGetUnitHealth = Spring.GetUnitHealth
local spAreTeamsAllied = Spring.AreTeamsAllied
local gaiaTeamID = Spring.GetGaiaTeamID()
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- drones are counted as parent for damage done, ignored for damage received
-- key = drone, value = parent
local drones = {
carrydrone = "reef",
wolverine_mine = "corgarp",
}
-- fallback for when attacker is already dead at damage event - attackerDefID == nil
-- probably should be autogenerated but meh
local weaponIDToUnitDefIDRaw = {
logkoda_napalm_bomblet = "logkoda",
firewalker_napalm_mortar = "firewalker",
corhurc2_napalm = "corhurc2",
corpyro_napalm = "corpyro",
corpyro_flamethrower = "corpyro",
dante_napalm_rockets = "dante",
dante_napalm_rocket_salvo = "dante",
dante_dante_flamer = "dante",
armtick_death = "armtick",
tacnuke_weapon = "tacnuke",
napalmmissile_weapon = "napalmmissile",
seismic_seismic_weapon = "seismic",
empmissile_emp_weapon = "emp",
wolverine_mine_bomblet = "corgarp",
}
local weaponIDToUnitDefID = {}
for weapon,unit in pairs(weaponIDToUnitDefIDRaw) do
if WeaponDefNames[weapon] and UnitDefNames[unit] then
local weaponDefID = WeaponDefNames[weapon].id
weaponIDToUnitDefID[weaponDefID] = UnitDefNames[unit].id
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Factory Plop
local function AddFactoryPlop(teamID, plopUnitDefID)
plops[#plops + 1] = {
teamID = teamID,
plopUnitDefID = plopUnitDefID,
}
end
GG.mod_stats_AddFactoryPlop = AddFactoryPlop
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer,
weaponID, attackerID, attackerDefID, attackerTeam)
if unitTeam == gaiaTeamID then
return
end
if weaponID and (not attackerDefID) then
attackerDefID = weaponIDToUnitDefID[weaponID]
--Spring.Echo(UnitDefs[attackerDefID].humanName)
end
if (attackerDefID == nil or unitDefID == nil or damage == nil) or (not attackerTeam) or (attackerTeam == unitTeam) or (damage < 0) or spAreTeamsAllied(attackerTeam, unitTeam) then
if (paralyzer) then
local hp, maxHp, paraDam = spGetUnitHealth(unitID)
local paraHp = maxHp - paraDam
if paraHp < 0 then paraHp = 0 end
lastPara[unitID] = paraHp
end
return
end
-- treat as different unit as needed
if drones[UnitDefs[unitDefID].name] then
return
end
if drones[UnitDefs[attackerDefID].name] then
local name = drones[UnitDefs[attackerDefID].name]
attackerDefID = (UnitDefNames[name] and UnitDefNames[name].id) or attackerDefID
end
local attackerAlias = UnitDefs[attackerDefID].customParams.statsname
if attackerAlias and UnitDefNames[attackerAlias] then
attackerDefID = UnitDefNames[attackerAlias].id
end
local defenderAlias = UnitDefs[unitDefID].customParams.statsname
if defenderAlias and UnitDefNames[defenderAlias] then
unitDefID = UnitDefNames[defenderAlias].id
end
local hp, maxHp, paraDam, capture, build = spGetUnitHealth(unitID)
if build >= 1 then
local tab = damages[attackerDefID]
if (tab == nil) then
tab = {}
damages[attackerDefID] = tab
end
local dam = tab[unitDefID]
if (dam == nil) then
dam = {0,0}
tab[unitDefID] = dam
end
local h
if (paralyzer) then h = lastPara[unitID] or maxHp
else h = hp + damage end
if h < 0 then h = 0 end
if h > maxHp then h = maxHp end
if (damage > h) then damage = h end
if (paralyzer) then
dam[2] = dam[2] + damage
else
dam[1] = dam[1] + damage
end
end
local paraHp = maxHp - paraDam
if paraHp < 0 then paraHp = 0 end
lastPara[unitID] = paraHp
end
function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
lastPara[unitID] = nil
local unitAlias = UnitDefs[unitDefID].customParams.statsname
if unitAlias and UnitDefNames[unitAlias] then
unitDefID = UnitDefNames[unitAlias].id
end
if (builderID == nil) then
local tab = unitCounts[unitDefID]
if (tab == nil) then
tab = {0,0}
unitCounts[unitDefID] = tab
end
tab[1] = tab[1] + 1
end
end
function gadget:UnitFinished(unitID, unitDefID, unitTeam)
lastPara[unitID] = nil
local unitAlias = UnitDefs[unitDefID].customParams.statsname
if unitAlias and UnitDefNames[unitAlias] then
unitDefID = UnitDefNames[unitAlias].id
end
local tab = unitCounts[unitDefID]
if (tab == nil) then
tab = {0,0}
unitCounts[unitDefID] = tab
end
tab[1] = tab[1] + 1
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
lastPara[unitID] = nil
local unitAlias = UnitDefs[unitDefID].customParams.statsname
if unitAlias and UnitDefNames[unitAlias] then
unitDefID = UnitDefNames[unitAlias].id
end
local tab = unitCounts[unitDefID]
if (tab == nil) then
tab = {0,0}
unitCounts[unitDefID] = tab
end
tab[2] = tab[2] + 1
end
function SendData(statsData)
Spring.SendCommands("wbynum 255 SPRINGIE:stats,".. statsData)
end
function gadget:GameOver()
if GG.Chicken then
Spring.Log(gadget:GetInfo().name, LOG.INFO, "Chicken game; unit stats disabled")
return -- don't report stats in chicken
end
Spring.Echo("Submitting stats")
for atk, victims in pairs(damages) do
for victim, dam in pairs(victims) do
SendData("dmg,"..UnitDefs[atk].name .. ",".. UnitDefs[victim].name .. "," .. dam[1] .. "," .. dam[2])
end
end
for unit, counts in pairs(unitCounts) do
SendData("unit,"..UnitDefs[unit].name .. ",".. UnitDefs[unit].metalCost ..",".. counts[1] .. "," .. counts[2] .. "," .. UnitDefs[unit].health)
end
for _, data in ipairs(plops) do
-- Send Data here
end
local teams = Spring.GetTeamList()
local humanAlly = {}
local players = 0
gaiaTeam = Spring.GetGaiaTeamID()
for _, teamID in ipairs(teams) do
local teamLuaAI = Spring.GetTeamLuaAI(teamID)
if ((teamLuaAI == nil or teamLuaAI == "") and teamID ~= gaiaTeam) then
local _,_,_,ai,side,ally = Spring.GetTeamInfo(teamID)
if (not ai) then
humanAlly[ally] = 1
players = players + 1
end
end
end
local allycount = 0
for _,_ in pairs(humanAlly) do allycount = allycount + 1 end
SendData("teams,"..players .. ",".. allycount)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
stas2z/openwrt-witi | package/luci/protocols/luci-proto-vpnc/luasrc/model/cbi/admin_network/proto_vpnc.lua | 7 | 3343 | -- Copyright 2015 Daniel Dickinson <openwrt@daniel.thecshore.com>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local server, username, password, hexpassword
local authgroup, interface, passgroup, hexpassgroup
local domain, vendor, natt_mode, dh_group
local pfs, enable_single_des, enable_no_enc
local mtu, local_addr, local_port, dpd_idle
local auth_mode, target_network
local ifc = net:get_interface():name()
server = section:taboption("general", Value, "server", translate("VPN Server"))
server.datatype = "host(0)"
port = section:taboption("general", Value, "local_addr", translate("VPN Local address"))
port.placeholder = "0.0.0.0"
port.datatype = "ipaddr"
port = section:taboption("general", Value, "local_port", translate("VPN Local port"))
port.placeholder = "500"
port.datatype = "port"
ifname = section:taboption("general", Value, "interface", translate("Output Interface"))
ifname.template = "cbi/network_netlist"
mtu = section.taboption("general", Value, "mtu", translate("MTU"))
mtu.datatype = "uinteger"
section:taboption("general", Value, "authgroup", translate("AuthGroup"))
username = section:taboption("general", Value, "username", translate("Username"))
password = section:taboption("general", Value, "password", translate("Password"))
hexpassword = section:taboption("general", Value, "hexpassword", translate("Obfuscated Password"))
password.password = true
hexpassword.password = true
authroup = section:taboption("general", Value, "authgroup", translate("Auth Group"))
passgroup = section:taboption("general", Value, "passgroup", translate("Group Password"))
hexpassgroup = section:taboption("general", Value, "hexpassgroup", translate("Obfuscated Group Password"))
password.passgroup = true
hexpassword.passgroup= true
domain = section:taboption("general", Value, "domain", translate("NT Domain"))
vendor = section:taboption("general", Value, "vendor", translate("Vendor"))
dh_group = section:taboption("general", ListValue, "dh_group", translate("IKE DH Group"))
dh_group:value("dh2")
dh_group:value("dh1")
dh_group:value("dh5")
pfs = section:taboption("general", ListValue, "pfs", translate("Perfect Forward Secrecy"))
dh_group:value("server")
dh_group:value("nopfs")
dh_group:value("dh1")
dh_group:value("dh2")
dh_group:value("dh5")
natt_mode = section:taboption("general", ListValue, "natt_mode", translate("NAT-T Mode")
natt_mode:value("natt", translate("RFC3947 NAT-T mode"))
natt_mode:value("none", translate("No NAT-T"))
natt_mode:value("force-natt", translate("Force use of NAT-T")
natt_mode:value("cisco-udp", translate("Cisco UDP encapsulation")
enable_no_enc = section:taboption("general", Flag, "enable_no_enc",
translate("Disable Encryption"),
translate("If checked, encryption is disabled"))
enable_no_enc.default = enable_no_enc.disabled
enable_single_des = section:taboption("general", Flag, "enable_single_des",
translate("Enable Single DES"),
translate("If checked, 1DES is enaled"))
enable_no_enc.default = enable_single_des.disabled
dpd_idle = section.taboption("general", Value, "dpd_idle", translate("DPD Idle Timeout"))
dpd_idle.datatype = "uinteger"
dpd.placeholder = "600"
ifname = section:taboption("general", Value, "target_network", translate("Target network"))
port.placeholder = "0.0.0.0/0"
port.datatype = "network"
| gpl-2.0 |
doorxp/ccjson | cocos2d/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua | 146 | 1793 | --------------------------------
-- @module plugin
--------------------------------------------------------
-- the plugin PluginProtocol
-- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module
--------------------------------------------------------
-- the plugin PluginManager
-- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module
--------------------------------------------------------
-- the plugin ProtocolAnalytics
-- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module
--------------------------------------------------------
-- the plugin ProtocolIAP
-- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module
--------------------------------------------------------
-- the plugin ProtocolAds
-- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module
--------------------------------------------------------
-- the plugin ProtocolShare
-- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module
--------------------------------------------------------
-- the plugin ProtocolSocial
-- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module
--------------------------------------------------------
-- the plugin ProtocolUser
-- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module
--------------------------------------------------------
-- the plugin AgentManager
-- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module
--------------------------------------------------------
-- the plugin FacebookAgent
-- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module
return nil
| gpl-3.0 |
imashkan/ashifire | bot/seedbot.lua | 1 | 9427 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"fire",
"spam"
},
sudo_users = {81444630},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Telefire v3 - Open Source
An advance Administration bot based on yagop/telegram-bot
Admins
@ashi_admin1_kaboos [Founder]
Special thanks to
Ashi sudo
]],
help_text_realm = [[
Realm Commands:
creategroup [Name]
Create a group
createrealm [Name]
Create a realm
setname [Name]
Set realm name
setabout [GroupID] [Text]
Set a group's about text
setrules [GroupID] [Text]
Set a group's rules
lock [GroupID] [setting]
Lock a group's setting
unlock [GroupID] [setting]
Unock a group's setting
wholist
Get a list of members in group/realm
who
Get a file of members in group/realm
type
Get group type
kill chat [GroupID]
Kick all memebers and delete group
kill realm [RealmID]
Kick all members and delete realm
addadmin [id|username]
Promote an admin by id OR username *Sudo only
removeadmin [id|username]
Demote an admin by id OR username *Sudo only
list groups
Get a list of all groups
list realms
Get a list of all realms
log
Grt a logfile of current group or realm
broadcast [text]
broadcast Hello !
Send text to all groups
bc [group_id] [text]
bc 123456789 Hello !
This command will send text to [group_id]
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings
Admins: @ashi_admin1_kaboos
]],
help_text = [[
Commands list :
kick [username|id]
You can also do it by reply
ban [ username|id]
You can also do it by reply
unban [id]
You can also do it by reply
who
Members list
modlist
Moderators list
promote [username]
Promote someone
demote [username]
Demote someone
kickme
Will kick user
about
Group description
setphoto
Set and locks group photo
setname [name]
Set group name
rules
Group rules
id
return group id or user id
help
lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
set rules <text>
Set <text> as rules
set about <text>
Set <text> as about
settings
Returns group settings
newlink
create/revoke your group link
link
returns group link
owner
returns group owner id
setowner [id]
Will set id as owner
setflood [value]
Set [value] as flood sensitivity
stats
Simple message statistics
save [value] <text>
Save <text> as [value]
get [value]
Returns text of [value]
clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
res [username]
returns user id
"!res @username"
log
will return group logs
banlist
will return group ban list
feedback
pm to admin
echo (your text)
fire
ashi
Admins: @ashi_admin1_kaboos
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
Jennal/cocos2dx-3.2-qt | cocos/scripting/lua-bindings/auto/api/Animate.lua | 6 | 1297 |
--------------------------------
-- @module Animate
-- @extend ActionInterval
-- @parent_module cc
--------------------------------
-- @overload self
-- @overload self
-- @function [parent=#Animate] getAnimation
-- @param self
-- @return Animation#Animation ret (retunr value: cc.Animation)
--------------------------------
-- @function [parent=#Animate] setAnimation
-- @param self
-- @param #cc.Animation animation
--------------------------------
-- @function [parent=#Animate] create
-- @param self
-- @param #cc.Animation animation
-- @return Animate#Animate ret (return value: cc.Animate)
--------------------------------
-- @function [parent=#Animate] startWithTarget
-- @param self
-- @param #cc.Node node
--------------------------------
-- @function [parent=#Animate] clone
-- @param self
-- @return Animate#Animate ret (return value: cc.Animate)
--------------------------------
-- @function [parent=#Animate] stop
-- @param self
--------------------------------
-- @function [parent=#Animate] reverse
-- @param self
-- @return Animate#Animate ret (return value: cc.Animate)
--------------------------------
-- @function [parent=#Animate] update
-- @param self
-- @param #float float
return nil
| mit |
stas2z/openwrt-witi | package/luci/applications/luci-app-qos/luasrc/model/cbi/qos/qos.lua | 17 | 2481 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
m = Map("qos", translate("Quality of Service"),
translate("With <abbr title=\"Quality of Service\">QoS</abbr> you " ..
"can prioritize network traffic selected by addresses, " ..
"ports or services."))
s = m:section(TypedSection, "interface", translate("Interfaces"))
s.addremove = true
s.anonymous = false
e = s:option(Flag, "enabled", translate("Enable"))
e.rmempty = false
c = s:option(ListValue, "classgroup", translate("Classification group"))
c:value("Default", translate("default"))
c.default = "Default"
s:option(Flag, "overhead", translate("Calculate overhead"))
s:option(Flag, "halfduplex", translate("Half-duplex"))
dl = s:option(Value, "download", translate("Download speed (kbit/s)"))
dl.datatype = "and(uinteger,min(1))"
ul = s:option(Value, "upload", translate("Upload speed (kbit/s)"))
ul.datatype = "and(uinteger,min(1))"
s = m:section(TypedSection, "classify", translate("Classification Rules"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
s.sortable = true
t = s:option(ListValue, "target", translate("Target"))
t:value("Priority", translate("priority"))
t:value("Express", translate("express"))
t:value("Normal", translate("normal"))
t:value("Bulk", translate("low"))
t.default = "Normal"
srch = s:option(Value, "srchost", translate("Source host"))
srch.rmempty = true
srch:value("", translate("all"))
wa.cbi_add_knownips(srch)
dsth = s:option(Value, "dsthost", translate("Destination host"))
dsth.rmempty = true
dsth:value("", translate("all"))
wa.cbi_add_knownips(dsth)
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
local pats = io.popen("find /etc/l7-protocols/ -type f -name '*.pat'")
if pats then
local l
while true do
l = pats:read("*l")
if not l then break end
l = l:match("([^/]+)%.pat$")
if l then
l7:value(l)
end
end
pats:close()
end
p = s:option(Value, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p:value("icmp", "ICMP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("all"))
bytes = s:option(Value, "connbytes", translate("Number of bytes"))
comment = s:option(Value, "comment", translate("Comment"))
return m
| gpl-2.0 |
stas2z/openwrt-witi | package/luci/applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua | 141 | 1031 | --[[
smap_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.smap_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.smap_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug)
luci.controller.luci_diag.smap_common.action_links(m, true)
return m
| gpl-2.0 |
Amadiro/obtuse-tanuki | libs/winapi/wglext.lua | 2 | 23164 |
--proc/wglext: opengl WGL API from wglext.h
--Written by Cosmin Apreutesei. Public Domain.
setfenv(1, require'winapi')
require'winapi.winuser'
require'gl_types'
WGL_WGLEXT_VERSION = 24
-- WGL_ARB_buffer_region
WGL_FRONT_COLOR_BUFFER_BIT_ARB = 0x00000001
WGL_BACK_COLOR_BUFFER_BIT_ARB = 0x00000002
WGL_DEPTH_BUFFER_BIT_ARB = 0x00000004
WGL_STENCIL_BUFFER_BIT_ARB = 0x00000008
-- WGL_ARB_multisample
WGL_SAMPLE_BUFFERS_ARB = 0x2041
WGL_SAMPLES_ARB = 0x2042
-- WGL_ARB_extensions_string
-- WGL_ARB_pixel_format
WGL_NUMBER_PIXEL_FORMATS_ARB = 0x2000
WGL_DRAW_TO_WINDOW_ARB = 0x2001
WGL_DRAW_TO_BITMAP_ARB = 0x2002
WGL_ACCELERATION_ARB = 0x2003
WGL_NEED_PALETTE_ARB = 0x2004
WGL_NEED_SYSTEM_PALETTE_ARB = 0x2005
WGL_SWAP_LAYER_BUFFERS_ARB = 0x2006
WGL_SWAP_METHOD_ARB = 0x2007
WGL_NUMBER_OVERLAYS_ARB = 0x2008
WGL_NUMBER_UNDERLAYS_ARB = 0x2009
WGL_TRANSPARENT_ARB = 0x200A
WGL_TRANSPARENT_RED_VALUE_ARB = 0x2037
WGL_TRANSPARENT_GREEN_VALUE_ARB = 0x2038
WGL_TRANSPARENT_BLUE_VALUE_ARB = 0x2039
WGL_TRANSPARENT_ALPHA_VALUE_ARB = 0x203A
WGL_TRANSPARENT_INDEX_VALUE_ARB = 0x203B
WGL_SHARE_DEPTH_ARB = 0x200C
WGL_SHARE_STENCIL_ARB = 0x200D
WGL_SHARE_ACCUM_ARB = 0x200E
WGL_SUPPORT_GDI_ARB = 0x200F
WGL_SUPPORT_OPENGL_ARB = 0x2010
WGL_DOUBLE_BUFFER_ARB = 0x2011
WGL_STEREO_ARB = 0x2012
WGL_PIXEL_TYPE_ARB = 0x2013
WGL_COLOR_BITS_ARB = 0x2014
WGL_RED_BITS_ARB = 0x2015
WGL_RED_SHIFT_ARB = 0x2016
WGL_GREEN_BITS_ARB = 0x2017
WGL_GREEN_SHIFT_ARB = 0x2018
WGL_BLUE_BITS_ARB = 0x2019
WGL_BLUE_SHIFT_ARB = 0x201A
WGL_ALPHA_BITS_ARB = 0x201B
WGL_ALPHA_SHIFT_ARB = 0x201C
WGL_ACCUM_BITS_ARB = 0x201D
WGL_ACCUM_RED_BITS_ARB = 0x201E
WGL_ACCUM_GREEN_BITS_ARB = 0x201F
WGL_ACCUM_BLUE_BITS_ARB = 0x2020
WGL_ACCUM_ALPHA_BITS_ARB = 0x2021
WGL_DEPTH_BITS_ARB = 0x2022
WGL_STENCIL_BITS_ARB = 0x2023
WGL_AUX_BUFFERS_ARB = 0x2024
WGL_NO_ACCELERATION_ARB = 0x2025
WGL_GENERIC_ACCELERATION_ARB = 0x2026
WGL_FULL_ACCELERATION_ARB = 0x2027
WGL_SWAP_EXCHANGE_ARB = 0x2028
WGL_SWAP_COPY_ARB = 0x2029
WGL_SWAP_UNDEFINED_ARB = 0x202A
WGL_TYPE_RGBA_ARB = 0x202B
WGL_TYPE_COLORINDEX_ARB = 0x202C
-- WGL_ARB_make_current_read
ERROR_INVALID_PIXEL_TYPE_ARB = 0x2043
ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB = 0x2054
-- WGL_ARB_pbuffer
WGL_DRAW_TO_PBUFFER_ARB = 0x202D
WGL_MAX_PBUFFER_PIXELS_ARB = 0x202E
WGL_MAX_PBUFFER_WIDTH_ARB = 0x202F
WGL_MAX_PBUFFER_HEIGHT_ARB = 0x2030
WGL_PBUFFER_LARGEST_ARB = 0x2033
WGL_PBUFFER_WIDTH_ARB = 0x2034
WGL_PBUFFER_HEIGHT_ARB = 0x2035
WGL_PBUFFER_LOST_ARB = 0x2036
-- WGL_ARB_render_texture
WGL_BIND_TO_TEXTURE_RGB_ARB = 0x2070
WGL_BIND_TO_TEXTURE_RGBA_ARB = 0x2071
WGL_TEXTURE_FORMAT_ARB = 0x2072
WGL_TEXTURE_TARGET_ARB = 0x2073
WGL_MIPMAP_TEXTURE_ARB = 0x2074
WGL_TEXTURE_RGB_ARB = 0x2075
WGL_TEXTURE_RGBA_ARB = 0x2076
WGL_NO_TEXTURE_ARB = 0x2077
WGL_TEXTURE_CUBE_MAP_ARB = 0x2078
WGL_TEXTURE_1D_ARB = 0x2079
WGL_TEXTURE_2D_ARB = 0x207A
WGL_MIPMAP_LEVEL_ARB = 0x207B
WGL_CUBE_MAP_FACE_ARB = 0x207C
WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB = 0x207D
WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB = 0x207E
WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB = 0x207F
WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB = 0x2080
WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB = 0x2081
WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB = 0x2082
WGL_FRONT_LEFT_ARB = 0x2083
WGL_FRONT_RIGHT_ARB = 0x2084
WGL_BACK_LEFT_ARB = 0x2085
WGL_BACK_RIGHT_ARB = 0x2086
WGL_AUX0_ARB = 0x2087
WGL_AUX1_ARB = 0x2088
WGL_AUX2_ARB = 0x2089
WGL_AUX3_ARB = 0x208A
WGL_AUX4_ARB = 0x208B
WGL_AUX5_ARB = 0x208C
WGL_AUX6_ARB = 0x208D
WGL_AUX7_ARB = 0x208E
WGL_AUX8_ARB = 0x208F
WGL_AUX9_ARB = 0x2090
-- WGL_ARB_pixel_format_float
WGL_TYPE_RGBA_FLOAT_ARB = 0x21A0
-- WGL_ARB_framebuffer_sRGB
WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB = 0x20A9
-- WGL_ARB_create_context
WGL_CONTEXT_DEBUG_BIT_ARB = 0x00000001
WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB = 0x00000002
WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091
WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092
WGL_CONTEXT_LAYER_PLANE_ARB = 0x2093
WGL_CONTEXT_FLAGS_ARB = 0x2094
ERROR_INVALID_VERSION_ARB = 0x2095
-- WGL_ARB_create_context_profile
WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126
WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001
WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB = 0x00000002
ERROR_INVALID_PROFILE_ARB = 0x2096
-- WGL_ARB_create_context_robustness
WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB = 0x00000004
WGL_LOSE_CONTEXT_ON_RESET_ARB = 0x8252
WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB = 0x8256
WGL_NO_RESET_NOTIFICATION_ARB = 0x8261
-- WGL_EXT_make_current_read
ERROR_INVALID_PIXEL_TYPE_EXT = 0x2043
-- WGL_EXT_pixel_format
WGL_NUMBER_PIXEL_FORMATS_EXT = 0x2000
WGL_DRAW_TO_WINDOW_EXT = 0x2001
WGL_DRAW_TO_BITMAP_EXT = 0x2002
WGL_ACCELERATION_EXT = 0x2003
WGL_NEED_PALETTE_EXT = 0x2004
WGL_NEED_SYSTEM_PALETTE_EXT = 0x2005
WGL_SWAP_LAYER_BUFFERS_EXT = 0x2006
WGL_SWAP_METHOD_EXT = 0x2007
WGL_NUMBER_OVERLAYS_EXT = 0x2008
WGL_NUMBER_UNDERLAYS_EXT = 0x2009
WGL_TRANSPARENT_EXT = 0x200A
WGL_TRANSPARENT_VALUE_EXT = 0x200B
WGL_SHARE_DEPTH_EXT = 0x200C
WGL_SHARE_STENCIL_EXT = 0x200D
WGL_SHARE_ACCUM_EXT = 0x200E
WGL_SUPPORT_GDI_EXT = 0x200F
WGL_SUPPORT_OPENGL_EXT = 0x2010
WGL_DOUBLE_BUFFER_EXT = 0x2011
WGL_STEREO_EXT = 0x2012
WGL_PIXEL_TYPE_EXT = 0x2013
WGL_COLOR_BITS_EXT = 0x2014
WGL_RED_BITS_EXT = 0x2015
WGL_RED_SHIFT_EXT = 0x2016
WGL_GREEN_BITS_EXT = 0x2017
WGL_GREEN_SHIFT_EXT = 0x2018
WGL_BLUE_BITS_EXT = 0x2019
WGL_BLUE_SHIFT_EXT = 0x201A
WGL_ALPHA_BITS_EXT = 0x201B
WGL_ALPHA_SHIFT_EXT = 0x201C
WGL_ACCUM_BITS_EXT = 0x201D
WGL_ACCUM_RED_BITS_EXT = 0x201E
WGL_ACCUM_GREEN_BITS_EXT = 0x201F
WGL_ACCUM_BLUE_BITS_EXT = 0x2020
WGL_ACCUM_ALPHA_BITS_EXT = 0x2021
WGL_DEPTH_BITS_EXT = 0x2022
WGL_STENCIL_BITS_EXT = 0x2023
WGL_AUX_BUFFERS_EXT = 0x2024
WGL_NO_ACCELERATION_EXT = 0x2025
WGL_GENERIC_ACCELERATION_EXT = 0x2026
WGL_FULL_ACCELERATION_EXT = 0x2027
WGL_SWAP_EXCHANGE_EXT = 0x2028
WGL_SWAP_COPY_EXT = 0x2029
WGL_SWAP_UNDEFINED_EXT = 0x202A
WGL_TYPE_RGBA_EXT = 0x202B
WGL_TYPE_COLORINDEX_EXT = 0x202C
-- WGL_EXT_pbuffer
WGL_DRAW_TO_PBUFFER_EXT = 0x202D
WGL_MAX_PBUFFER_PIXELS_EXT = 0x202E
WGL_MAX_PBUFFER_WIDTH_EXT = 0x202F
WGL_MAX_PBUFFER_HEIGHT_EXT = 0x2030
WGL_OPTIMAL_PBUFFER_WIDTH_EXT = 0x2031
WGL_OPTIMAL_PBUFFER_HEIGHT_EXT = 0x2032
WGL_PBUFFER_LARGEST_EXT = 0x2033
WGL_PBUFFER_WIDTH_EXT = 0x2034
WGL_PBUFFER_HEIGHT_EXT = 0x2035
-- WGL_EXT_depth_float
WGL_DEPTH_FLOAT_EXT = 0x2040
-- WGL_3DFX_multisample
WGL_SAMPLE_BUFFERS_3DFX = 0x2060
WGL_SAMPLES_3DFX = 0x2061
-- WGL_EXT_multisample
WGL_SAMPLE_BUFFERS_EXT = 0x2041
WGL_SAMPLES_EXT = 0x2042
-- WGL_I3D_digital_video_control
WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D = 0x2050
WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D = 0x2051
WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D = 0x2052
WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D = 0x2053
-- WGL_I3D_gamma
WGL_GAMMA_TABLE_SIZE_I3D = 0x204E
WGL_GAMMA_EXCLUDE_DESKTOP_I3D = 0x204F
-- WGL_I3D_genlock
WGL_GENLOCK_SOURCE_MULTIVIEW_I3D = 0x2044
WGL_GENLOCK_SOURCE_EXTENAL_SYNC_I3D = 0x2045
WGL_GENLOCK_SOURCE_EXTENAL_FIELD_I3D = 0x2046
WGL_GENLOCK_SOURCE_EXTENAL_TTL_I3D = 0x2047
WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D = 0x2048
WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D = 0x2049
WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D = 0x204A
WGL_GENLOCK_SOURCE_EDGE_RISING_I3D = 0x204B
WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D = 0x204C
-- WGL_I3D_image_buffer
WGL_IMAGE_BUFFER_MIN_ACCESS_I3D = 0x00000001
WGL_IMAGE_BUFFER_LOCK_I3D = 0x00000002
-- WGL_I3D_swap_frame_lock
-- WGL_NV_render_depth_texture
WGL_BIND_TO_TEXTURE_DEPTH_NV = 0x20A3
WGL_BIND_TO_TEXTURE_RECTANGLE_DEPTH_NV = 0x20A4
WGL_DEPTH_TEXTURE_FORMAT_NV = 0x20A5
WGL_TEXTURE_DEPTH_COMPONENT_NV = 0x20A6
WGL_DEPTH_COMPONENT_NV = 0x20A7
-- WGL_NV_render_texture_rectangle
WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV = 0x20A0
WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV = 0x20A1
WGL_TEXTURE_RECTANGLE_NV = 0x20A2
-- WGL_ATI_pixel_format_float
WGL_TYPE_RGBA_FLOAT_ATI = 0x21A0
-- WGL_NV_float_buffer
WGL_FLOAT_COMPONENTS_NV = 0x20B0
WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV = 0x20B1
WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV = 0x20B2
WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV = 0x20B3
WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV = 0x20B4
WGL_TEXTURE_FLOAT_R_NV = 0x20B5
WGL_TEXTURE_FLOAT_RG_NV = 0x20B6
WGL_TEXTURE_FLOAT_RGB_NV = 0x20B7
WGL_TEXTURE_FLOAT_RGBA_NV = 0x20B8
-- WGL_3DL_stereo_control
WGL_STEREO_EMITTER_ENABLE_3DL = 0x2055
WGL_STEREO_EMITTER_DISABLE_3DL = 0x2056
WGL_STEREO_POLARITY_NORMAL_3DL = 0x2057
WGL_STEREO_POLARITY_INVERT_3DL = 0x2058
-- WGL_EXT_pixel_format_packed_float
WGL_TYPE_RGBA_UNSIGNED_FLOAT_EXT = 0x20A8
-- WGL_EXT_framebuffer_sRGB
WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT = 0x20A9
-- WGL_NV_present_video
WGL_NUM_VIDEO_SLOTS_NV = 0x20F0
-- WGL_NV_video_out
WGL_BIND_TO_VIDEO_RGB_NV = 0x20C0
WGL_BIND_TO_VIDEO_RGBA_NV = 0x20C1
WGL_BIND_TO_VIDEO_RGB_AND_DEPTH_NV = 0x20C2
WGL_VIDEO_OUT_COLOR_NV = 0x20C3
WGL_VIDEO_OUT_ALPHA_NV = 0x20C4
WGL_VIDEO_OUT_DEPTH_NV = 0x20C5
WGL_VIDEO_OUT_COLOR_AND_ALPHA_NV = 0x20C6
WGL_VIDEO_OUT_COLOR_AND_DEPTH_NV = 0x20C7
WGL_VIDEO_OUT_FRAME = 0x20C8
WGL_VIDEO_OUT_FIELD_1 = 0x20C9
WGL_VIDEO_OUT_FIELD_2 = 0x20CA
WGL_VIDEO_OUT_STACKED_FIELDS_1_2 = 0x20CB
WGL_VIDEO_OUT_STACKED_FIELDS_2_1 = 0x20CC
-- WGL_NV_swap_group
-- WGL_NV_gpu_affinity
WGL_ERROR_INCOMPATIBLE_AFFINITY_MASKS_NV = 0x20D0
WGL_ERROR_MISSING_AFFINITY_MASK_NV = 0x20D1
-- WGL_AMD_gpu_association
WGL_GPU_VENDOR_AMD = 0x1F00
WGL_GPU_RENDERER_STRING_AMD = 0x1F01
WGL_GPU_OPENGL_VERSION_STRING_AMD = 0x1F02
WGL_GPU_FASTEST_TARGET_GPUS_AMD = 0x21A2
WGL_GPU_RAM_AMD = 0x21A3
WGL_GPU_CLOCK_AMD = 0x21A4
WGL_GPU_NUM_PIPES_AMD = 0x21A5
WGL_GPU_NUM_SIMD_AMD = 0x21A6
WGL_GPU_NUM_RB_AMD = 0x21A7
WGL_GPU_NUM_SPI_AMD = 0x21A8
-- WGL_NV_video_capture
WGL_UNIQUE_ID_NV = 0x20CE
WGL_NUM_VIDEO_CAPTURE_SLOTS_NV = 0x20CF
-- WGL_NV_copy_image
-- WGL_NV_multisample_coverage
WGL_COVERAGE_SAMPLES_NV = 0x2042
WGL_COLOR_SAMPLES_NV = 0x20B9
-- WGL_EXT_create_context_es2_profile
WGL_CONTEXT_ES2_PROFILE_BIT_EXT = 0x00000004
-- WGL_NV_DX_interop
WGL_ACCESS_READ_ONLY_NV = 0x00000000
WGL_ACCESS_READ_WRITE_NV = 0x00000001
WGL_ACCESS_WRITE_DISCARD_NV = 0x00000002
-- WGL_NV_DX_interop2
-- WGL_EXT_swap_control_tear
local function DECLARE_HANDLE(name)
ffi.cdef(string.format([[
struct %s__ {
int unused;
};
typedef struct %s__* %s;
]], name, name, name))
end
DECLARE_HANDLE('HPBUFFERARB')
DECLARE_HANDLE('HPBUFFEREXT')
DECLARE_HANDLE('HVIDEOOUTPUTDEVICENV')
DECLARE_HANDLE('HPVIDEODEV')
DECLARE_HANDLE('HPGPUNV')
DECLARE_HANDLE('HGPUNV')
DECLARE_HANDLE('HVIDEOINPUTDEVICENV')
ffi.cdef[[
typedef struct _GPU_DEVICE {
DWORD cb;
CHAR DeviceName[32];
CHAR DeviceString[128];
DWORD Flags;
RECT rcVirtualScreen;
} GPU_DEVICE, *PGPU_DEVICE;
typedef HANDLE (* PFNWGLCREATEBUFFERREGIONARBPROC) (HDC hDC, int iLayerPlane, UINT uType);
typedef void (* PFNWGLDELETEBUFFERREGIONARBPROC) (HANDLE hRegion);
typedef BOOL (* PFNWGLSAVEBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height);
typedef BOOL (* PFNWGLRESTOREBUFFERREGIONARBPROC) (HANDLE hRegion, int x, int y, int width, int height, int xSrc, int ySrc);
typedef const char * (* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
typedef BOOL (* PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
typedef BOOL (* PFNWGLGETPIXELFORMATATTRIBFVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, FLOAT *pfValues);
typedef BOOL (* PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
typedef BOOL (* PFNWGLMAKECONTEXTCURRENTARBPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
typedef HDC (* PFNWGLGETCURRENTREADDCARBPROC) (void);
typedef HPBUFFERARB (* PFNWGLCREATEPBUFFERARBPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
typedef HDC (* PFNWGLGETPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer);
typedef int (* PFNWGLRELEASEPBUFFERDCARBPROC) (HPBUFFERARB hPbuffer, HDC hDC);
typedef BOOL (* PFNWGLDESTROYPBUFFERARBPROC) (HPBUFFERARB hPbuffer);
typedef BOOL (* PFNWGLQUERYPBUFFERARBPROC) (HPBUFFERARB hPbuffer, int iAttribute, int *piValue);
typedef BOOL (* PFNWGLBINDTEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
typedef BOOL (* PFNWGLRELEASETEXIMAGEARBPROC) (HPBUFFERARB hPbuffer, int iBuffer);
typedef BOOL (* PFNWGLSETPBUFFERATTRIBARBPROC) (HPBUFFERARB hPbuffer, const int *piAttribList);
typedef HGLRC (* PFNWGLCREATECONTEXTATTRIBSARBPROC) (HDC hDC, HGLRC hShareContext, const int *attribList);
typedef GLboolean (* PFNWGLCREATEDISPLAYCOLORTABLEEXTPROC) (GLushort id);
typedef GLboolean (* PFNWGLLOADDISPLAYCOLORTABLEEXTPROC) (const GLushort *table, GLuint length);
typedef GLboolean (* PFNWGLBINDDISPLAYCOLORTABLEEXTPROC) (GLushort id);
typedef void (* PFNWGLDESTROYDISPLAYCOLORTABLEEXTPROC) (GLushort id);
typedef const char * (* PFNWGLGETEXTENSIONSSTRINGEXTPROC) (void);
typedef BOOL (* PFNWGLMAKECONTEXTCURRENTEXTPROC) (HDC hDrawDC, HDC hReadDC, HGLRC hglrc);
typedef HDC (* PFNWGLGETCURRENTREADDCEXTPROC) (void);
typedef HPBUFFEREXT (* PFNWGLCREATEPBUFFEREXTPROC) (HDC hDC, int iPixelFormat, int iWidth, int iHeight, const int *piAttribList);
typedef HDC (* PFNWGLGETPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer);
typedef int (* PFNWGLRELEASEPBUFFERDCEXTPROC) (HPBUFFEREXT hPbuffer, HDC hDC);
typedef BOOL (* PFNWGLDESTROYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer);
typedef BOOL (* PFNWGLQUERYPBUFFEREXTPROC) (HPBUFFEREXT hPbuffer, int iAttribute, int *piValue);
typedef BOOL (* PFNWGLGETPIXELFORMATATTRIBIVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, int *piValues);
typedef BOOL (* PFNWGLGETPIXELFORMATATTRIBFVEXTPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, int *piAttributes, FLOAT *pfValues);
typedef BOOL (* PFNWGLCHOOSEPIXELFORMATEXTPROC) (HDC hdc, const int *piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
typedef BOOL (* PFNWGLSWAPINTERVALEXTPROC) (int interval);
typedef int (* PFNWGLGETSWAPINTERVALEXTPROC) (void);
typedef void* (* PFNWGLALLOCATEMEMORYNVPROC) (GLsizei size, GLfloat readfreq, GLfloat writefreq, GLfloat priority);
typedef void (* PFNWGLFREEMEMORYNVPROC) (void *pointer);
typedef BOOL (* PFNWGLGETSYNCVALUESOMLPROC) (HDC hdc, INT64 *ust, INT64 *msc, INT64 *sbc);
typedef BOOL (* PFNWGLGETMSCRATEOMLPROC) (HDC hdc, INT32 *numerator, INT32 *denominator);
typedef INT64 (* PFNWGLSWAPBUFFERSMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder);
typedef INT64 (* PFNWGLSWAPLAYERBUFFERSMSCOMLPROC) (HDC hdc, int fuPlanes, INT64 target_msc, INT64 divisor, INT64 remainder);
typedef BOOL (* PFNWGLWAITFORMSCOMLPROC) (HDC hdc, INT64 target_msc, INT64 divisor, INT64 remainder, INT64 *ust, INT64 *msc, INT64 *sbc);
typedef BOOL (* PFNWGLWAITFORSBCOMLPROC) (HDC hdc, INT64 target_sbc, INT64 *ust, INT64 *msc, INT64 *sbc);
typedef BOOL (* PFNWGLGETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
typedef BOOL (* PFNWGLSETDIGITALVIDEOPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
typedef BOOL (* PFNWGLGETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, int *piValue);
typedef BOOL (* PFNWGLSETGAMMATABLEPARAMETERSI3DPROC) (HDC hDC, int iAttribute, const int *piValue);
typedef BOOL (* PFNWGLGETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, USHORT *puRed, USHORT *puGreen, USHORT *puBlue);
typedef BOOL (* PFNWGLSETGAMMATABLEI3DPROC) (HDC hDC, int iEntries, const USHORT *puRed, const USHORT *puGreen, const USHORT *puBlue);
typedef BOOL (* PFNWGLENABLEGENLOCKI3DPROC) (HDC hDC);
typedef BOOL (* PFNWGLDISABLEGENLOCKI3DPROC) (HDC hDC);
typedef BOOL (* PFNWGLISENABLEDGENLOCKI3DPROC) (HDC hDC, BOOL *pFlag);
typedef BOOL (* PFNWGLGENLOCKSOURCEI3DPROC) (HDC hDC, UINT uSource);
typedef BOOL (* PFNWGLGETGENLOCKSOURCEI3DPROC) (HDC hDC, UINT *uSource);
typedef BOOL (* PFNWGLGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT uEdge);
typedef BOOL (* PFNWGLGETGENLOCKSOURCEEDGEI3DPROC) (HDC hDC, UINT *uEdge);
typedef BOOL (* PFNWGLGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT uRate);
typedef BOOL (* PFNWGLGETGENLOCKSAMPLERATEI3DPROC) (HDC hDC, UINT *uRate);
typedef BOOL (* PFNWGLGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT uDelay);
typedef BOOL (* PFNWGLGETGENLOCKSOURCEDELAYI3DPROC) (HDC hDC, UINT *uDelay);
typedef BOOL (* PFNWGLQUERYGENLOCKMAXSOURCEDELAYI3DPROC) (HDC hDC, UINT *uMaxLineDelay, UINT *uMaxPixelDelay);
typedef LPVOID (* PFNWGLCREATEIMAGEBUFFERI3DPROC) (HDC hDC, DWORD dwSize, UINT uFlags);
typedef BOOL (* PFNWGLDESTROYIMAGEBUFFERI3DPROC) (HDC hDC, LPVOID pAddress);
typedef BOOL (* PFNWGLASSOCIATEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const HANDLE *pEvent, const LPVOID *pAddress, const DWORD *pSize, UINT count);
typedef BOOL (* PFNWGLRELEASEIMAGEBUFFEREVENTSI3DPROC) (HDC hDC, const LPVOID *pAddress, UINT count);
typedef BOOL (* PFNWGLENABLEFRAMELOCKI3DPROC) (void);
typedef BOOL (* PFNWGLDISABLEFRAMELOCKI3DPROC) (void);
typedef BOOL (* PFNWGLISENABLEDFRAMELOCKI3DPROC) (BOOL *pFlag);
typedef BOOL (* PFNWGLQUERYFRAMELOCKMASTERI3DPROC) (BOOL *pFlag);
typedef BOOL (* PFNWGLGETFRAMEUSAGEI3DPROC) (float *pUsage);
typedef BOOL (* PFNWGLBEGINFRAMETRACKINGI3DPROC) (void);
typedef BOOL (* PFNWGLENDFRAMETRACKINGI3DPROC) (void);
typedef BOOL (* PFNWGLQUERYFRAMETRACKINGI3DPROC) (DWORD *pFrameCount, DWORD *pMissedFrames, float *pLastMissedUsage);
typedef BOOL (* PFNWGLSETSTEREOEMITTERSTATE3DLPROC) (HDC hDC, UINT uState);
typedef int (* PFNWGLENUMERATEVIDEODEVICESNVPROC) (HDC hDC, HVIDEOOUTPUTDEVICENV *phDeviceList);
typedef BOOL (* PFNWGLBINDVIDEODEVICENVPROC) (HDC hDC, unsigned int uVideoSlot, HVIDEOOUTPUTDEVICENV hVideoDevice, const int *piAttribList);
typedef BOOL (* PFNWGLQUERYCURRENTCONTEXTNVPROC) (int iAttribute, int *piValue);
typedef BOOL (* PFNWGLGETVIDEODEVICENVPROC) (HDC hDC, int numDevices, HPVIDEODEV *hVideoDevice);
typedef BOOL (* PFNWGLRELEASEVIDEODEVICENVPROC) (HPVIDEODEV hVideoDevice);
typedef BOOL (* PFNWGLBINDVIDEOIMAGENVPROC) (HPVIDEODEV hVideoDevice, HPBUFFERARB hPbuffer, int iVideoBuffer);
typedef BOOL (* PFNWGLRELEASEVIDEOIMAGENVPROC) (HPBUFFERARB hPbuffer, int iVideoBuffer);
typedef BOOL (* PFNWGLSENDPBUFFERTOVIDEONVPROC) (HPBUFFERARB hPbuffer, int iBufferType, unsigned long *pulCounterPbuffer, BOOL bBlock);
typedef BOOL (* PFNWGLGETVIDEOINFONVPROC) (HPVIDEODEV hpVideoDevice, unsigned long *pulCounterOutputPbuffer, unsigned long *pulCounterOutputVideo);
typedef BOOL (* PFNWGLJOINSWAPGROUPNVPROC) (HDC hDC, GLuint group);
typedef BOOL (* PFNWGLBINDSWAPBARRIERNVPROC) (GLuint group, GLuint barrier);
typedef BOOL (* PFNWGLQUERYSWAPGROUPNVPROC) (HDC hDC, GLuint *group, GLuint *barrier);
typedef BOOL (* PFNWGLQUERYMAXSWAPGROUPSNVPROC) (HDC hDC, GLuint *maxGroups, GLuint *maxBarriers);
typedef BOOL (* PFNWGLQUERYFRAMECOUNTNVPROC) (HDC hDC, GLuint *count);
typedef BOOL (* PFNWGLRESETFRAMECOUNTNVPROC) (HDC hDC);
typedef BOOL (* PFNWGLENUMGPUSNVPROC) (UINT iGpuIndex, HGPUNV *phGpu);
typedef BOOL (* PFNWGLENUMGPUDEVICESNVPROC) (HGPUNV hGpu, UINT iDeviceIndex, PGPU_DEVICE lpGpuDevice);
typedef HDC (* PFNWGLCREATEAFFINITYDCNVPROC) (const HGPUNV *phGpuList);
typedef BOOL (* PFNWGLENUMGPUSFROMAFFINITYDCNVPROC) (HDC hAffinityDC, UINT iGpuIndex, HGPUNV *hGpu);
typedef BOOL (* PFNWGLDELETEDCNVPROC) (HDC hdc);
typedef UINT (* PFNWGLGETGPUIDSAMDPROC) (UINT maxCount, UINT *ids);
typedef INT (* PFNWGLGETGPUINFOAMDPROC) (UINT id, int property, GLenum dataType, UINT size, void *data);
typedef UINT (* PFNWGLGETCONTEXTGPUIDAMDPROC) (HGLRC hglrc);
typedef HGLRC (* PFNWGLCREATEASSOCIATEDCONTEXTAMDPROC) (UINT id);
typedef HGLRC (* PFNWGLCREATEASSOCIATEDCONTEXTATTRIBSAMDPROC) (UINT id, HGLRC hShareContext, const int *attribList);
typedef BOOL (* PFNWGLDELETEASSOCIATEDCONTEXTAMDPROC) (HGLRC hglrc);
typedef BOOL (* PFNWGLMAKEASSOCIATEDCONTEXTCURRENTAMDPROC) (HGLRC hglrc);
typedef HGLRC (* PFNWGLGETCURRENTASSOCIATEDCONTEXTAMDPROC) (void);
typedef void (* PFNWGLBLITCONTEXTFRAMEBUFFERAMDPROC) (HGLRC dstCtx, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter);
typedef BOOL (* PFNWGLBINDVIDEOCAPTUREDEVICENVPROC) (UINT uVideoSlot, HVIDEOINPUTDEVICENV hDevice);
typedef UINT (* PFNWGLENUMERATEVIDEOCAPTUREDEVICESNVPROC) (HDC hDc, HVIDEOINPUTDEVICENV *phDeviceList);
typedef BOOL (* PFNWGLLOCKVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
typedef BOOL (* PFNWGLQUERYVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice, int iAttribute, int *piValue);
typedef BOOL (* PFNWGLRELEASEVIDEOCAPTUREDEVICENVPROC) (HDC hDc, HVIDEOINPUTDEVICENV hDevice);
typedef BOOL (* PFNWGLCOPYIMAGESUBDATANVPROC) (HGLRC hSrcRC, GLuint srcName, GLenum srcTarget, GLint srcLevel, GLint srcX, GLint srcY, GLint srcZ, HGLRC hDstRC, GLuint dstName, GLenum dstTarget, GLint dstLevel, GLint dstX, GLint dstY, GLint dstZ, GLsizei width, GLsizei height, GLsizei depth);
typedef BOOL (* PFNWGLDXSETRESOURCESHAREHANDLENVPROC) (void *dxObject, HANDLE shareHandle);
typedef HANDLE (* PFNWGLDXOPENDEVICENVPROC) (void *dxDevice);
typedef BOOL (* PFNWGLDXCLOSEDEVICENVPROC) (HANDLE hDevice);
typedef HANDLE (* PFNWGLDXREGISTEROBJECTNVPROC) (HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access);
typedef BOOL (* PFNWGLDXUNREGISTEROBJECTNVPROC) (HANDLE hDevice, HANDLE hObject);
typedef BOOL (* PFNWGLDXOBJECTACCESSNVPROC) (HANDLE hObject, GLenum access);
typedef BOOL (* PFNWGLDXLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects);
typedef BOOL (* PFNWGLDXUNLOCKOBJECTSNVPROC) (HANDLE hDevice, GLint count, HANDLE *hObjects);
]]
| mit |
cloudkick/ck-agent | src/lua/remote/check_disk.lua | 1 | 4247 | -- -- Copyright 2012 Rackspace
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
module(..., package.seeall);
local alien = require 'alien'
local util = require 'util'
local Check = util.Check
local log = util.log
local structs = require 'structs'
local function win_getvalue(args)
local f = alien.Kernel32.GetDiskFreeSpaceExA
f:types{ ret = "int", abi = "stdcall", "string", "pointer", "pointer", "pointer" }
ulargeint = alien.defstruct{
{ "low", "ulong" },
{ "high", "ulong" }
}
local disk_free = ulargeint:new()
local disk_total = ulargeint:new()
local disk_total_free = ulargeint:new()
log.dbg("calling alien.Kernel32.GetDiskFreeSpaceExA('%q')", args.path)
assert( f(args.path, disk_free(), disk_total(), disk_total_free()) ~= 0 )
local r = {}
r.bsize = 1024
r.blocks = (disk_total.high * 2^32 + disk_total.low) / r.bsize
r.bfree = (disk_total_free.high * 2^32 + disk_free.low) / r.bsize
r.capacity = 100 - ((r.bfree/r.blocks) * 100)
return r
end
local function getvalue(args)
local libc = alien.default
local buf = alien.buffer(structs.statfs.__size)
local rv = 0
if equus.p_is_darwin() == 1 then
libc.statfs64:types("int", "string", "pointer")
log.dbg("calling libc.statfs64('%q')", args.path)
rv = libc.statfs64(args.path, buf:topointer())
log.dbg("libc.statfs64('%q') = %d", args.path, rv)
else
libc.statfs:types("int", "string", "pointer")
log.dbg("calling libc.statfs('%q')", args.path)
rv = libc.statfs(args.path, buf:topointer())
log.dbg("libc.statfs('%q') = %d", args.path, rv)
end
if rv < 0 then
error("libc.statfs returned ".. rv)
end
local r = {}
r.bsize = buf:get(structs.statfs.f_bsize+1, "uint")
r.blocks = buf:get(structs.statfs.f_blocks+1, "long")
r.bavail = buf:get(structs.statfs.f_bavail+1, "long") -- blocks available to non-root users. this is what we actually care about
r.bfree = buf:get(structs.statfs.f_bfree+1, "long") -- blocks available to root
local blocks_total_nonroot = r.blocks - r.bfree + r.bavail
r.blocks_used = blocks_total_nonroot - r.bavail
r.capacity = (r.blocks_used / blocks_total_nonroot) * 100
if r.capacity > 100 then
log.msg("capacity calculation returned %s, capping at 100%%", r.capacity)
r.capacity = 100
end
return r
end
function run(rcheck, args)
if args.path == nil then
if equus.p_is_windows() == 1 then
args.path = 'c:\\'
else
args.path = '/'
end
else
args.path = args.path[1]
end
local rv = nil
local r = nil
if equus.p_is_windows() == 1 then
rv, r = pcall(win_getvalue, args)
else
rv, r = pcall(getvalue, args)
end
if rv then
rcheck:add_metric('capacity', r.capacity, Check.enum.double)
rcheck:add_metric('bsize', r.bsize, Check.enum.uint64)
rcheck:add_metric('blocks', r.blocks, Check.enum.uint64)
rcheck:add_metric('bfree', r.bfree, Check.enum.uint64)
local used = (r.blocks - r.bfree)
if equus.p_is_windows() == 0 then
rcheck:add_metric('bavail', r.bavail, Check.enum.uint64)
used = r.blocks_used
end
local free = (r.blocks - used)
local total_gb = (r.blocks * r.bsize) / 1024 / 1024 / 1024
local used_gb = (used * r.bsize) / 1024 / 1024 / 1024
local free_gb = ((r.blocks - used) * r.bsize) / 1024 / 1024 / 1024
rcheck:set_status('capacity: %.2f%% total: %.2f GB, used: %.2f GB, free: %.2f GB',
r.capacity, total_gb, used_gb, free_gb)
else
log.err("disk failed err: %s", r)
rcheck:set_error("%s", r)
end
return rcheck
end
| apache-2.0 |
Amadiro/obtuse-tanuki | systems/render.lua | 2 | 3518 | local tiny = require "tiny"
local cpml = require "cpml"
local utils = require "utils"
return function(camera)
local render_system = tiny.system()
render_system.filter = tiny.requireAll("model_matrix", "mesh", tiny.rejectAny("needs_reload"))
render_system.camera = camera
Signal.register('client-network-id', function(id) render_system.id = id end)
local bounds = love.graphics.newShader("assets/shaders/shader.glsl")
local shader = love.graphics.newShader("assets/shaders/shader.glsl")
function render_system:update(dt)
local cc = love.math.gammaToLinear
-- local color = cpml.vec3(cc(unpack(cpml.color.darken({255,255,255,255}, 0.75))))
-- love.graphics.setBackgroundColor(color.x, color.y, color.z, color:dot(cpml.vec3(0.299, 0.587, 0.114)))
love.graphics.clearDepth()
love.graphics.setDepthTest("less")
love.graphics.setCulling("back")
love.graphics.setFrontFace("cw")
love.graphics.setBlendMode("replace")
love.graphics.setShader(shader)
-- shader:send("u_Ka", { 0.1, 0.1, 0.1 })
-- shader:send("u_Kd", { 1, 1, 1 })
-- shader:send("u_Ks", { 0, 0, 0 })
-- shader:send("u_Ns", 0)
-- shader:sendInt("u_shading", 1)
shader:sendInt("use_color", 1)
self.camera:send(shader)
local entities = self.entities
for _, entity in ipairs(entities) do
while true do
if entity.possessed then
break
end
local model = entity.model_matrix:to_vec4s()
shader:send("u_model", model)
for _, buffer in ipairs(entity.mesh) do
-- local texture = entity.mesh.textures[buffer.material]
-- entity.mesh.mesh:setTexture(texture) -- nil is OK
entity.mesh.mesh:setDrawRange(buffer.first, buffer.last)
love.graphics.draw(entity.mesh.mesh)
end
-- for _, buffer in ipairs(entity.mesh.vertex_buffer) do
-- -- utils.print_r(buffer)
-- love.graphics.draw(buffer.mesh)
-- end
-- entity:draw()
-- love.graphics.setShader(bounds)
-- love.graphics.setWireframe(true)
--
-- if entity.closest then
-- love.graphics.setColor(0, 255, 0, 255)
-- entity.closest = nil
-- elseif entity.highlight then
-- love.graphics.setColor(255, 0, 0, 255)
-- entity.highlight = nil
-- else
-- love.graphics.setColor(cc(80, 80, 80, 255))
-- end
--
-- if entity.locked then
-- if entity.locked == self.id then
-- love.graphics.setColor(0, 0, 255, 255)
-- elseif entity.locked ~= self.id then
-- love.graphics.setColor(255, 0, 255, 255)
-- end
-- end
--
-- if entity.bounds then
-- self.camera:send(bounds)
-- bounds:sendInt("u_shading", 1)
-- bounds:send("u_Ka", { 1, 0, 0 })
-- bounds:send("u_model", cpml.mat4():to_vec4s())
-- love.graphics.draw(entity.bounds)
-- end
-- love.graphics.setColor(255, 255, 255, 255)
-- love.graphics.setWireframe(false)
break
end
end
love.graphics.setShader()
love.graphics.setDepthTest()
love.graphics.setCulling()
love.graphics.setFrontFace()
love.graphics.setBlendMode("alpha")
love.graphics.print(string.format("POS: %s", self.camera.position), 20, 100)
love.graphics.print(string.format("DIR: %s", self.camera.direction), 20, 124)
love.graphics.print(string.format("ROT: %s", self.camera.orientation), 20, 148)
local spacing = 24
local stats = love.graphics.getStats()
local i = 0
for k, v in pairs(stats) do
love.graphics.print(string.format("%s: %d", k, v), 20, 180 + i * spacing)
i = i + 1
end
end
return render_system
end
| mit |
rlcevg/Zero-K | units/tele_beacon.lua | 3 | 2252 | unitDef = {
unitname = [[tele_beacon]],
name = [[Lamp]],
description = [[Teleport Bridge Entry Beacon, right click to teleport.]],
acceleration = 0,
brakeRate = 0,
buildAngle = 4096,
buildCostEnergy = 100,
buildCostMetal = 100,
builder = false,
buildTime = 100,
category = [[SINK UNARMED]],
customParams = {
helptext = [[This is Djinn's entry beacon. Right-click it to teleport units to the parent Djinn.]],
description_de = [[Teleport-Knoten - rechten Maustaste darauf]],
description_pl = [[Wezel teleportera - uzyj prawego przycisku myszy]],
helptext_de = [[Dieser Teleport-Knoten teleportiert Einheiten zu der verknuepften Djinn.]],
helptext_pl = [[To jest wejscie do teleportera - uzyj prawego przycisku myszy, aby przeteleportowac jednostki do powiazanego Djinna.]],
dontcount = [[1]],
},
energyUse = 0,
explodeAs = [[TINY_BUILDINGEX]],
footprintX = 2,
footprintZ = 2,
levelGround = false,
iconType = [[statictransport]],
idleAutoHeal = 5,
idleTime = 1800,
mass = 336,
maxDamage = 1500,
maxSlope = 18,
maxVelocity = 0,
minCloakDistance = 150,
noAutoFire = false,
objectName = [[amphteleportbeacon.s3o]],
reclaimable = false,
script = [[tele_beacon.lua]],
seismicSignature = 4,
selfDestructAs = [[TINY_BUILDINGEX]],
selfDestructCountdown = 5,
side = [[ARM]],
sightDistance = 0,
turnRate = 0,
useBuildingGroundDecal = false,
workerTime = 0,
--yardMap = [[oooooooooooooooooooo]],
featureDefs = {
},
}
return lowerkeys({ tele_beacon = unitDef })
| gpl-2.0 |
joole/private-pkgs | luci/applications/luci-app-shadowsocksR/files/usr/lib/lua/luci/model/cbi/shadowsocksr/gfwlist.lua | 1 | 3675 |
local fs = require "nixio.fs"
local china_file = "/etc/ssrr/china_route"
local user_local_file = "/etc/ssrr/user_local_ip"
local user_remote_file = "/etc/ssrr/user_remote_ip"
function sync_value_to_file(value, file)
value = value:gsub("\r\n?", "\n")
local old_value = nixio.fs.readfile(file)
if value ~= old_value then
nixio.fs.writefile(file, value)
end
end
m = Map("ssrr", translate("路由表"),translate("指定国内外路由表,并且可以设置强制走和不走的网段"))
s = m:section(TypedSection, "shadowsocksr", translate("Settings"))
s.anonymous = true
button_update_route = s:option (Button, "_button_update_chinaroute", translate("更新国内路由表"),translate("点击后请静待30秒,如非特殊需要,不用更新该表"))
local route_count = luci.sys.exec("grep -c '' " .. china_file)
button_update_route.inputtitle = translate ( "当前规则数目" .. route_count .. ",点击更新")
button_update_route.inputstyle = "apply"
function button_update_route.write (self, section, value)
luci.sys.call ( "nohup sh /etc/ssrr/update_chinaroute.sh > /tmp/gfwupdate.log 2>&1 &")
end
china_route = s:option(TextValue, "china_route", translate("国内IP网段"), nil)
china_route.description = translate("该列表是国内外分流的主要依据,内容会随着更新而被覆盖")
china_route.rows = 13
china_route.wrap = "off"
china_route.cfgvalue = function(self, section)
return fs.readfile(china_file) or ""
end
china_route.write = function(self, section, value)
fs.writefile(china_file, value:gsub("\r\n", "\n"))
end
user_local = s:option(TextValue, "user_local", translate("强制不走代理的网段"), nil)
user_local.description = translate("请不要随意删除,请填写内网网段")
user_local.rows = 13
user_local.wrap = "off"
user_local.cfgvalue = function(self, section)
return fs.readfile(user_local_file) or ""
end
user_local.write = function(self, section, value)
fs.writefile(user_local_file, value:gsub("\r\n", "\n"))
end
user_remote = s:option(TextValue, "user_remote", translate("强制走代理的网段"), nil)
user_remote.description = translate("该规则优先权低于强制不走IP的网段,一般需要填写telegram这样软件服务器的IP")
user_remote.rows = 13
user_remote.wrap = "off"
user_remote.cfgvalue = function(self, section)
return fs.readfile(user_remote_file) or ""
end
user_remote.write = function(self, section, value)
fs.writefile(user_remote_file, value:gsub("\r\n", "\n"))
end
-- [[ LAN Hosts ]]--
s = m:section(TypedSection, "lan_hosts", translate("LAN Hosts"))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
o = s:option(Value, "host", translate("Host"))
--[[ 废弃的API
luci.sys.net.arptable(function(x)
o:value(x["IP address"], "%s (%s)" %{x["IP address"], x["HW address"]})
end)
]]
luci.ip.neighbors({family = 4}, function(neighbor)
if neighbor.reachable then
o:value(neighbor.dest:string(), "%s (%s)" %{neighbor.dest:string(), neighbor.mac})
end
o.datatype = "ip4addr"
o.rmempty = false
o = s:option(ListValue, "type", translate("Proxy Type"))
o:value("direct", translate("Direct (No Proxy)"))
o:value("normal", translate("Normal"))
o:value("gfwlist", translate("GFW-List based auto-proxy"))
o:value("nochina", translate("All non-China IPs"))
o:value("game", translate("Game Mode"))
o:value("all", translate("All Public IPs"))
o.rmempty = false
o = s:option(Flag, "enable", translate("Enable"))
o.default = "1"
o.rmempty = false
-- ---------------------------------------------------
local apply = luci.http.formvalue("cbi.apply")
if apply then
os.execute("/etc/init.d/ssr-redir.sh restart >/dev/null 2>&1 &")
end
return m
| gpl-2.0 |
anholt/ValyriaTear | dat/maps/mt_elbrus/mt_elbrus_cave1_map.lua | 1 | 63501 | map_data = {}
-- The number of rows, and columns that compose the map
map_data.num_tile_cols = 50
map_data.num_tile_rows = 40
-- The tilesets definition files used.
map_data.tileset_filenames = {}
map_data.tileset_filenames[1] = "dat/tilesets/desert_cave_ground.lua"
-- The map grid to indicate walkability. 0 is walkable, 1 is not.
map_data.map_grid = {}
map_data.map_grid[0] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[1] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[2] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[3] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[4] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[5] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[6] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[7] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[8] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[9] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[11] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[13] = { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[14] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[15] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[16] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[17] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[18] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[19] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[20] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1 }
map_data.map_grid[21] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }
map_data.map_grid[22] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }
map_data.map_grid[23] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }
map_data.map_grid[24] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }
map_data.map_grid[25] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 }
map_data.map_grid[26] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[27] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[28] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[29] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[30] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[31] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[33] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[34] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[35] = { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[36] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[37] = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[38] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[39] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[40] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[41] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[42] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[43] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[44] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[45] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[46] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[47] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[48] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[49] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[50] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[51] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[52] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[53] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[54] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[55] = { 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[56] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[57] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[58] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[59] = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[60] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[61] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[62] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[63] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[64] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[65] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[66] = { 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[67] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[68] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[69] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[70] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[71] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[72] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[73] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[74] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[75] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[76] = { 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[77] = { 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[78] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
map_data.map_grid[79] = { 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1 }
-- The tile layers. The numbers are indeces to the tile_mappings table.
map_data.layers = {}
map_data.layers[0] = {}
map_data.layers[0].type = "ground"
map_data.layers[0].name = "Background"
map_data.layers[0][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, -1, -1, -1, -1 }
map_data.layers[0][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 97, 100, 100, 100, 149, 133, -1, -1, -1 }
map_data.layers[0][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 100, 100, 100, 100, 100, 100, 103, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 97, 113, 0, 0, 0, 165, 177, -1, -1, -1 }
map_data.layers[0][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 97, 113, 0, 0, 0, 0, 0, 0, 119, 103, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 97, 113, 0, 0, 0, 0, 0, 0, -1, -1, -1 }
map_data.layers[0][4] = { -1, -1, 133, 97, -1, 103, -1, -1, -1, -1, -1, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 119, 103, 133, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, 97, -1, 113, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1 }
map_data.layers[0][5] = { -1, -1, 176, 113, 0, 119, 103, -1, 97, -1, -1, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 119, 100, 103, 133, -1, -1, -1, -1, -1, -1, 133, 133, 97, -1, -1, 113, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1 }
map_data.layers[0][6] = { -1, -1, 0, 0, 0, 0, 119, -1, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 119, 177, -1, -1, -1, -1, -1, 133, 97, -1, 113, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1 }
map_data.layers[0][7] = { -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, 208, 0, 0, 0, 0, 209, -1, -1, 133, 133, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, 133, 133, 133, 133, -1, -1 }
map_data.layers[0][8] = { -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, 133, 133, 133, 97, 100, 103, 96, 0, 104, 133, 133, 133, 97, -1, -1, 113, 0, 0, 0, 0, 0, 0, 0, 0, 209, 133, 133, 133, 97, 100, 100, 149, 133, -1 }
map_data.layers[0][9] = { -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, 133, 133, 133, 133, 97, -1, -1, 113, 0, -1, 113, 0, 119, 100, 100, 100, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, 133, 97, 100, 100, 113, 0, 0, 165, 177, -1 }
map_data.layers[0][10] = { -1, -1, 208, 0, 0, 0, 0, 0, 209, -1, 133, 97, -1, -1, -1, -1, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, -1 }
map_data.layers[0][11] = { -1, -1, -1, 208, 0, 209, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, 133, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, -1 }
map_data.layers[0][12] = { -1, -1, -1, -1, -1, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, 133, 97, 99, 113, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1 }
map_data.layers[0][13] = { -1, -1, -1, -1, 133, 133, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, 96, 0, 103, 133, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1 }
map_data.layers[0][14] = { -1, -1, -1, 133, 97, 102, 133, 97, 112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, 176, 112, 0, 119, 177, -1, -1, -1, -1, 133, 97, 99, 100, 100, 100, 113, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1 }
map_data.layers[0][15] = { -1, -1, 133, 97, 113, 119, 99, 113, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 209, -1, 133, 133, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[0][16] = { -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 209, 133, 133, 97, 100, 100, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[0][17] = { -1, 176, 113, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, 96, 0, 104, 97, 100, 101, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[0][18] = { -1, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, 133, 97, 100, 100, 99, 101, 113, 0, 119, 112, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, 133, 133, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[0][19] = { -1, 208, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, 176, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 133, 98, 100, 99, 100, 100, 101, 103, 133, 133, -1, -1, -1, -1, -1 }
map_data.layers[0][20] = { -1, -1, 208, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, 133, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 119, 100, 103, 133, -1, -1, -1, -1 }
map_data.layers[0][21] = { -1, -1, -1, 208, 0, 0, 209, -1, -1, -1, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 119, 177, -1, -1, -1, -1 }
map_data.layers[0][22] = { -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, 133, 97, 113, 0, 0, 0, 0, 209, 133, 96, 0, 104, 133, -1, -1, -1, -1, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 104, 133, -1, -1, -1 }
map_data.layers[0][23] = { -1, -1, -1, -1, -1, 133, 133, 97, 99, 100, 100, 101, 100, 113, 0, 0, 0, 0, 209, -1, 176, 113, 0, 119, 177, -1, -1, -1, -1, -1, -1, 133, 97, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 119, 177, -1, -1, -1 }
map_data.layers[0][24] = { -1, -1, -1, 133, 133, 97, 100, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, 176, 113, 0, 0, 0, 0, 209, -1, -1, 208, 0, 0, 0, 0, 0, 104, 133, -1, -1 }
map_data.layers[0][25] = { -1, -1, 133, 97, 100, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, 0, 0, 0, 0, -1, 133, -1, -1, -1, -1, 133, 96, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, 208, 0, 0, 0, 119, 177, -1, -1 }
map_data.layers[0][26] = { -1, -1, 176, 113, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, 133, 133, 133, 133, 97, 113, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, -1, -1 }
map_data.layers[0][27] = { -1, 133, 96, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, 208, 0, 0, 0, 0, -1, -1, -1, -1, 97, 113, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, 208, 0, 0, 0, 0, -1, -1 }
map_data.layers[0][28] = { -1, 176, 113, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, 133, 96, 0, 0, 0, -1, -1 }
map_data.layers[0][29] = { -1, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, 133, 97, 113, 0, 0, 0, -1, -1 }
map_data.layers[0][30] = { -1, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 113, 0, 0, 0, 0, -1, -1 }
map_data.layers[0][31] = { -1, 0, 0, 0, 104, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 0, 0, 0, 0, 0, 0, 0, 209, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 16, 209, -1, -1 }
map_data.layers[0][32] = { -1, 0, 0, 0, 119, 177, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 16, 209, -1, -1, -1 }
map_data.layers[0][33] = { -1, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1 }
map_data.layers[0][34] = { -1, 208, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1 }
map_data.layers[0][35] = { -1, -1, 0, 0, 0, 104, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 96, 0, 0, 104, 133, -1, -1, -1 }
map_data.layers[0][36] = { -1, 133, 96, 0, 0, 119, 103, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 113, 0, 0, 119, 103, 133, -1, -1 }
map_data.layers[0][37] = { -1, 176, 112, 0, 0, 0, 119, 103, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 119, -1, -1, -1 }
map_data.layers[0][38] = { -1, 0, 0, 0, 0, 0, 0, 119, 103, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, -1, -1, -1 }
map_data.layers[0][39] = { -1, 0, 0, 0, 0, 0, 0, 0, 119, 177, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, -1, -1 }
map_data.layers[1] = {}
map_data.layers[1].type = "ground"
map_data.layers[1].name = "Background 2"
map_data.layers[1][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, 133, 133, 133, 133, 133, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 116, 116, 116, -1, -1, -1, -1, -1 }
map_data.layers[1][3] = { -1, -1, -1, 133, 133, 133, -1, -1, -1, -1, -1, 133, -1, -1, 116, 116, 116, 116, 116, 116, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, 66, -1, -1, 181, 193, -1, -1, -1 }
map_data.layers[1][4] = { -1, -1, -1, -1, 100, -1, 133, -1, 133, 133, 133, -1, -1, 136, -1, -1, -1, -1, 81, -1, 135, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 100, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][5] = { -1, -1, -1, -1, 116, -1, -1, 133, -1, 100, 100, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, 135, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 100, 100, -1, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][6] = { -1, -1, 192, 136, -1, 135, -1, 100, -1, 116, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 117, -1, -1, -1, -1, -1, -1, -1, -1, -1, 100, -1, 116, 116, 136, 67, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][7] = { -1, -1, 192, -1, -1, -1, 135, 116, 136, 64, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, -1, -1, -1, -1, -1, -1, -1, -1, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][8] = { -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 100, 100, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][9] = { -1, -1, 192, 64, -1, -1, -1, 66, -1, -1, -1, -1, -1, -1, -1, -1, -1, 100, 100, -1, 117, 119, -1, -1, -1, -1, -1, -1, -1, 116, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 116, 116, -1, -1, -1 }
map_data.layers[1][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 100, 100, 100, 100, -1, 116, 116, 136, -1, 135, 136, -1, 135, 116, 116, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 116, 116, 136, -1, -1, 181, 193, -1 }
map_data.layers[1][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 116, 116, 116, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, 67, -1, -1, -1, -1, -1, 193, -1 }
map_data.layers[1][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, 68, -1, -1, -1, -1, -1, -1, -1, -1, -1, 80, -1, 83, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, 68, -1, -1, -1 }
map_data.layers[1][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][15] = { -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 136, -1, 135, -1, -1, -1, -1, -1, -1, -1, 117, 117, 117, 117, 162, 163, 163, 163, 163, 163, 163, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][16] = { -1, -1, -1, -1, 136, 135, 115, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][17] = { -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 117, 117, 136, -1, -1, -1, -1, -1, -1, -1, -1, 66, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][18] = { -1, 192, 136, -1, 64, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 117, 117, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 133, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][19] = { -1, -1, -1, -1, -1, -1, 64, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, 117, 117, 117, 117, 136, -1, 135, 136, 66, -1, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, 65, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 161, -1, -1, -1, -1, 116, 116, 116, 116, 116, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 84, -1, 84, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, 67, 135, 116, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, 135, -1, -1, -1, -1, -1 }
map_data.layers[1][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][24] = { -1, -1, -1, -1, -1, -1, -1, -1, 116, 116, 116, 116, 116, 136, -1, -1, -1, -1, -1, -1, 192, 136, -1, 135, 193, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, -1, -1, -1, -1 }
map_data.layers[1][25] = { -1, -1, -1, -1, -1, -1, 116, 136, 82, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 104, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][26] = { -1, -1, -1, -1, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, 119, 103, -1, -1, -1, -1, -1, -1, 68, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 135, 193, -1, -1 }
map_data.layers[1][27] = { -1, -1, -1, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 119, 99, 100, 101, 100, -1, 136, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 68, 193, -1, -1 }
map_data.layers[1][28] = { -1, -1, -1, 64, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 135, 116, 116, 116, 116, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 }
map_data.layers[1][29] = { -1, 192, 136, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 193, -1, -1 }
map_data.layers[1][30] = { -1, 192, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 67, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 136, -1, -1, 193, -1, -1 }
map_data.layers[1][31] = { -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 136, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][32] = { -1, 163, 163, 163, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][33] = { -1, 192, -1, -1, 135, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 193, -1, -1, -1, -1 }
map_data.layers[1][34] = { -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, 193, -1, -1, -1, -1 }
map_data.layers[1][35] = { -1, -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 96, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][36] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[1][37] = { -1, -1, -1, -1, -1, 135, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 136, -1, -1, 135, -1, 177, -1, -1 }
map_data.layers[1][38] = { -1, 192, 136, -1, -1, 64, 135, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 68, -1, -1, -1, 135, 193, -1, -1 }
map_data.layers[1][39] = { -1, 192, -1, -1, -1, -1, -1, 135, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, -1, -1, -1, -1, -1, 193, -1, -1 }
map_data.layers[2] = {}
map_data.layers[2].type = "ground"
map_data.layers[2].name = "Background 3"
map_data.layers[2][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 83, -1, 84, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 116, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 184, 185, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 200, 201, -1, -1, -1, -1, -1, 193, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 216, 217, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 70, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 85, -1, 86, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][24] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][25] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][27] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][28] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][29] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][30] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][31] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][32] = { -1, 192, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][33] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][34] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][35] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][36] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][37] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][38] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[2][39] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3] = {}
map_data.layers[3].type = "sky"
map_data.layers[3].name = "Sky"
map_data.layers[3][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1 }
map_data.layers[3][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1 }
map_data.layers[3][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, 179, 179, 179, 179, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, 179, 180, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][9] = { -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][10] = { -1, -1, -1, 180, -1, 178, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][11] = { -1, -1, -1, -1, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 180, -1, 178, 179, 179, 179, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1 }
map_data.layers[3][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, 179, -1, -1, -1 }
map_data.layers[3][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][18] = { -1, -1, -1, -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, 179, 179, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][19] = { -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][20] = { -1, -1, -1, 180, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][21] = { -1, -1, -1, -1, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 180, -1, 178, 179, 179, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][24] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, 179, 180, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][25] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][26] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][27] = { -1, -1, -1, -1, -1, -1, -1, 178, 179, 179, 179, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1 }
map_data.layers[3][28] = { -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][29] = { -1, -1, -1, -1, 178, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][30] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][31] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 179, 179, 179, 179, 179, 179, 179, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1 }
map_data.layers[3][32] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 178, -1, -1, -1, -1 }
map_data.layers[3][33] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][34] = { -1, -1, 180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][35] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][36] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][37] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][38] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
map_data.layers[3][39] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
| gpl-2.0 |
ViolyS/RayUI_VS | Interface/AddOns/RayUI/modules/skins/blizzard/bags.lua | 1 | 1411 | ----------------------------------------------------------
-- Load RayUI Environment
----------------------------------------------------------
RayUI:LoadEnv("Skins")
local S = _Skins
local function LoadSkin()
local r, g, b = _r, _g, _b
S:ReskinCheck(TokenFramePopupInactiveCheckBox)
S:ReskinCheck(TokenFramePopupBackpackCheckBox)
S:ReskinClose(TokenFramePopupCloseButton)
S:ReskinScroll(TokenFrameContainerScrollBar)
TokenFramePopupCorner:Hide()
TokenFramePopup:SetPoint("TOPLEFT", TokenFrame, "TOPRIGHT", 1, -28)
local function updateButtons()
local buttons = TokenFrameContainer.buttons
for i = 1, #buttons do
local button = buttons[i]
if button and not button.reskinned then
button.highlight:SetPoint("TOPLEFT", 1, 0)
button.highlight:SetPoint("BOTTOMRIGHT", -1, 0)
button.highlight.SetPoint = R.dummy
button.highlight:SetColorTexture(r, g, b, .2)
button.highlight.SetTexture = R.dummy
button.categoryMiddle:SetAlpha(0)
button.categoryLeft:SetAlpha(0)
button.categoryRight:SetAlpha(0)
button.icon:SetTexCoord(.08, .92, .08, .92)
button.bg = S:CreateBG(button.icon)
button.reskinned = true
end
if button.isHeader then
button.bg:Hide()
else
button.bg:Show()
end
end
end
TokenFrame:HookScript("OnShow", updateButtons)
hooksecurefunc(TokenFrameContainer, "update", updateButtons)
end
S:AddCallback("Bags", LoadSkin)
| mit |
ploxiln/janus-gateway | plugins/lua/janus-sdp.lua | 2 | 11922 | -- Set of utilities for parsing, processing and managing Janus SDPs in Lua,
-- as the C Janus SDP utils that Janus provides are unavailable otherwise
local JANUSSDP = {}
function JANUSSDP.parse(text)
if text == nil then
return nil
end
local lines = {}
local s = nil
for s in text:gmatch("[^\r\n]+") do
table.insert(lines, s)
end
local sdp = {}
local index = nil
local line = nil
for index,line in pairs(lines) do
local t = line:sub(1,1)
local ll = line:sub(3)
local sc = ll:find(":")
local n, v
if sc == nil then
n = ll
else
n = ll:sub(1,sc-1)
v = ll:sub(sc+1)
end
table.insert(sdp, {type = t, name = n, value = v})
end
return sdp
end
function JANUSSDP.render(sdp)
if sdp == nil then
return nil
end
local sdpString = ""
local index = nil
local a = nil
for index,a in pairs(sdp) do
if a.value == nil then
sdpString = sdpString .. a.type .. "=" .. a.name .. "\r\n"
else
sdpString = sdpString .. a.type .. "=" .. a.name .. ":" .. a.value .. "\r\n"
end
end
return sdpString
end
function JANUSSDP.findPayloadType(sdp, codec)
if sdp == nil or codec == nil then
return -1
end
local pt = -1
local codecUpper = codec:upper()
local codecLower = codec:lower()
local index = nil
local a = nil
for index,a in pairs(sdp) do
if a.name == "rtpmap" and a.value ~= nil then
if a.value:find(codecLower) ~= nil or a.value:find(codecUpper) ~= nil then
local n = a.value:gmatch("[^ ]+")
pt = tonumber(n())
break
end
end
end
return pt
end
function JANUSSDP.findCodec(sdp, pt)
if sdp == nil or pt == nil then
return -1
end
if pt == 0 then
return "pcmu"
elseif pt == 8 then
return "pcma"
elseif pt == 9 then
return "g722"
end
local codec = nil
local index = nil
local a = nil
for index,a in pairs(sdp) do
if a.name == "rtpmap" and a.value ~= nil then
local n = a.value:gmatch("[^ ]+")
if tonumber(n()) == pt then
if a.value:find("vp8") ~= nil or a.value:find("VP8") ~= nil then
codec = "vp8"
elseif a.value:find("vp9") ~= nil or a.value:find("VP9") ~= nil then
codec = "vp9"
elseif a.value:find("h264") ~= nil or a.value:find("H264") ~= nil then
codec = "h264"
elseif a.value:find("opus") ~= nil or a.value:find("OPUS") ~= nil then
codec = "opus"
elseif a.value:find("pcmu") ~= nil or a.value:find("PCMU") ~= nil then
codec = "pcmu"
elseif a.value:find("pcma") ~= nil or a.value:find("PCMA") ~= nil then
codec = "pcma"
elseif a.value:find("isac16") ~= nil or a.value:find("ISAC16") ~= nil then
codec = "isac16"
elseif a.value:find("isac32") ~= nil or a.value:find("ISAC32") ~= nil then
codec = "isac32"
elseif a.value:find("telephone-event") ~= nil or a.value:find("TELEPHONE-EVENT") ~= nil then
codec = "isac32"
end
break
end
end
end
return codec
end
function JANUSSDP.removePayloadType(sdp, pt)
if sdp == nil or pt == nil then
return
end
local removelist = {}
local index = nil
local a = nil
for index,a in pairs(sdp) do
if a.type == "m" then
local m = a.name:gsub(" " .. pt .. " ", " ")
if m ~= nil then a.name = m end
a.name = a.name .. "\r\n"
local m = a.name:gsub(" " .. pt .. "\r\n", "\r\n")
if m ~= nil then a.name = m end
a.name = a.name:gsub("\r\n", "")
elseif a.type == "a" and a.value ~= nil then
local n = a.value:gmatch("[^ ]+")
if tonumber(n()) == pt then
removelist[#removelist+1] = index
end
end
end
local i = nil
for i=#removelist,1,-1 do
if removelist[i] ~= nil then
table.remove(sdp, removelist[i])
end
end
end
function JANUSSDP.generateOffer(options)
-- Let's set some defaults for the options, in case none were given
if options == nil then options = {} end
if options.audio == nil then options.audio = true end
if options.audio == true and options.audioPt == nil then options.audioPt = 111 end
if options.audio == true and options.audioCodec == nil then
options.audioCodec = "opus"
end
if options.audio == true then
if options.audioCodec == "opus" then
options.audioRtpmap = "opus/48000/2"
elseif options.audioCodec == "pcmu" then
options.audioRtpmap = "PCMU/8000"
options.audioPt = 0
elseif options.audioCodec == "pcma" then
options.audioRtpmap = "PCMA/8000"
options.audioPt = 8
elseif options.audioCodec == "g722" then
options.audioRtpmap = "G722/8000"
options.audioPt = 9
elseif options.audioCodec == "isac16" then
options.audioRtpmap = "ISAC/16000"
elseif options.audioCodec == "isac32" then
options.audioRtpmap = "ISAC/32000"
else
-- Unsupported codec
options.audio = false
end
end
if options.audioDir == nil then options.audioDir = "sendrecv" end
if options.video == nil then options.video = true end
if options.video == true and options.videoPt == nil then options.videoPt = 96 end
if options.video == true and options.videoCodec == nil then
options.videoCodec = "vp8"
end
if options.video == true then
if options.videoCodec == "vp8" then
options.videoRtpmap = "VP8/90000"
elseif options.videoCodec == "vp9" then
options.videoRtpmap = "VP9/90000"
elseif options.videoCodec == "h264" then
options.videoRtpmap = "H264/90000"
else
-- Unsupported codec
options.video = false
end
end
if options.videoDir == nil then options.videoDir = "sendrecv" end
if options.videoRtcpfb == nil then options.videoRtcpfb = true end
if options.data == nil then options.data = false end
if options.data == true then options.dataDir = "sendrecv" end
local address = options.address
if address == nil then address = "127.0.0.1" end
local ipv6 = false
if options.ipv6 == true then ipv6 = true end
local sessionName = options.sessionName
if options.sessionName == nil then options.sessionName = "Janus Lua session" end
-- Do we have enough for an offer?
if options.audio == false and options.video == false and options.data == false then return nil end
-- Let's prepare the offer
local offer = {}
-- Let's start from the session-level attributes
offer[#offer+1] = { type = "v", name = "0" }
offer[#offer+1] = { type = "o", name = "- " .. math.floor(math.random(4294967296)) .. " 1 IN " ..
(ipv6 == true and "IP6 " or "IP4 ") .. address }
offer[#offer+1] = { type = "s", name = options.sessionName }
offer[#offer+1] = { type = "t", name = "0 0" }
offer[#offer+1] = { type = "c", name = "IN " .. (ipv6 == true and "IP6 " or "IP4 ") .. address }
-- Now let's add the media lines
if options.audio == true then
offer[#offer+1] = { type = "m", name = "audio 9 UDP/TLS/RTP/SAVPF " .. options.audioPt }
offer[#offer+1] = { type = "c", name = "IN " .. (ipv6 == true and "IP6 " or "IP4 ") .. address }
offer[#offer+1] = { type = "a", name = options.audioDir }
offer[#offer+1] = { type = "a", name = "rtpmap", value = options.audioPt .. " " .. options.audioRtpmap }
end
if options.video == true then
offer[#offer+1] = { type = "m", name = "video 9 UDP/TLS/RTP/SAVPF " .. options.videoPt }
offer[#offer+1] = { type = "c", name = "IN " .. (ipv6 == true and "IP6 " or "IP4 ") .. address }
offer[#offer+1] = { type = "a", name = options.videoDir }
offer[#offer+1] = { type = "a", name = "rtpmap", value = options.videoPt .. " " .. options.videoRtpmap }
if options.videoCodec == "h264" then
offer[#offer+1] = { type = "a", name = "fmtp", value = options.videoPt .. " profile-level-id=42e01f;packetization-mode=1" }
end
if options.videoRtcpfb == true then
offer[#offer+1] = { type = "a", name = "rtcp-fb", value = options.videoPt .. " ccm fir" }
offer[#offer+1] = { type = "a", name = "rtcp-fb", value = options.videoPt .. " nack" }
offer[#offer+1] = { type = "a", name = "rtcp-fb", value = options.videoPt .. " nack pli" }
offer[#offer+1] = { type = "a", name = "rtcp-fb", value = options.videoPt .. " goog-remb" }
end
end
if options.data == true then
offer[#offer+1] = { type = "m", name = "application 9 DTLS/SCTP 5000" }
offer[#offer+1] = { type = "c", name = "IN " .. (ipv6 == true and "IP6 " or "IP4 ") .. address }
offer[#offer+1] = { type = "a", name = "sendrecv" }
offer[#offer+1] = { type = "a", name = "sctmap", value = "5000 webrtc-datachannel 16" }
end
-- Done
return offer
end
function JANUSSDP.generateAnswer(offer, options)
if offer == nil then
return nil
end
-- Let's set some defaults for the options, in case none were given
if options == nil then options = {} end
if options.audio == nil then options.audio = true end
if options.audioCodec == nil then
if JANUSSDP.findPayloadType(offer, "opus") > 0 then
options.audioCodec = "opus"
elseif JANUSSDP.findPayloadType(offer, "pcmu") > 0 then
options.audioCodec = "pcmu"
elseif JANUSSDP.findPayloadType(offer, "pcma") > 0 then
options.audioCodec = "pcma"
elseif JANUSSDP.findPayloadType(offer, "g722") > 0 then
options.audioCodec = "g722"
elseif JANUSSDP.findPayloadType(offer, "isac16") > 0 then
options.audioCodec = "isac16"
elseif JANUSSDP.findPayloadType(offer, "isac32") > 0 then
options.audioCodec = "isac32"
end
end
if options.video == nil then options.video = true end
if options.videoCodec == nil then
if JANUSSDP.findPayloadType(offer, "vp8") > 0 then
options.videoCodec = "vp8"
elseif JANUSSDP.findPayloadType(offer, "vp9") > 0 then
options.videoCodec = "vp9"
elseif JANUSSDP.findPayloadType(offer, "h264") > 0 then
options.videoCodec = "h264"
end
end
if options.data == nil then options.data = true end
-- Let's prepare the answer
local answer = {}
-- Iterate on all lines
local audio = 0
local video = 0
local data = 0
local audioPt = -1
local videoPt = -1
local medium = nil
local reject = false
local index = nil
local a = nil
for index,a in pairs(offer) do
if medium == nil and a.type ~= "m" then
-- We just copy all the session-level attributes
if a.value == nil then
answer[#answer+1] = a
end
end
if a.type == "m" then
-- New m-line
reject = false
if a.name:find("audio") ~= nil then
medium = "audio"
audio = audio+1
if audioPt < 0 then
audioPt = JANUSSDP.findPayloadType(offer, options.audioCodec)
end
if audioPt < 0 then
audio = audio+1
end
if audio > 1 then
reject = true
answer[#answer+1] = { type = "m", name = "audio 0 UDP/TLS/RTP/SAVPF 0" }
else
answer[#answer+1] = { type = "m", name = "audio 9 UDP/TLS/RTP/SAVPF " .. audioPt }
end
elseif a.name:find("video") ~= nil then
medium = "video"
video = video+1
if videoPt < 0 then
videoPt = JANUSSDP.findPayloadType(offer, options.videoCodec)
end
if videoPt < 0 then
video = video+1
end
if video > 1 then
reject = true
answer[#answer+1] = { type = "m", name = "video 0 UDP/TLS/RTP/SAVPF 0" }
else
answer[#answer+1] = { type = "m", name = "video 9 UDP/TLS/RTP/SAVPF " .. videoPt }
end
elseif a.name:find("application") ~= nil then
medium = "application"
data = data+1
if data > 1 then
reject = true
answer[#answer+1] = { type = "m", name = "application 0 DTLS/SCTP 5000" }
else
answer[#answer+1] = { type = "m", name = a.name }
end
end
elseif a.type == "a" then
if a.name == "sendonly" then
answer[#answer+1] = { type = "a", name = "recvonly" }
elseif a.name == "recvonly" then
answer[#answer+1] = { type = "a", name = "sendonly" }
elseif a.value ~= nil then
if a.name == "rtpmap" or a.name == "fmtp" or a.name == "rtcp-fb" then
-- Drop attributes associated to payload types we're getting rid of
local n = a.value:gmatch("[^ ]+")
if medium == "audio" and tonumber(n()) == audioPt then
answer[#answer+1] = a
elseif medium == "video" and tonumber(n()) == videoPt then
answer[#answer+1] = a
end
end
else
answer[#answer+1] = a
end
-- TODO Handle/filter other attributes
end
end
-- Done
return answer
end
return JANUSSDP
| gpl-3.0 |
rlcevg/Zero-K | scripts/fighter.lua | 6 | 3987 | include "constants.lua"
--pieces
local base, flare1, flare2, nozzle1, nozzle2, missile, rgun, lgun, rwing, lwing, rjet, ljet, body
= piece("base", "flare1", "flare2", "nozzle1", "nozzle2", "missile", "rgun", "lgun", "rwing", "lwing", "rjet", "ljet", "body")
local smokePiece = {base, rwing, lwing}
--variables
local shotCycle = 0
local flare = {
[0] = flare1,
[1] = flare2,
}
local SPEEDUP_FACTOR = tonumber (UnitDef.customParams.boost_speed_mult)
local BOOSTUP_FACTOR = tonumber (UnitDef.customParams.boost_accel_mult)
local SPEEDUP_DURATION = tonumber (UnitDef.customParams.boost_duration)
----------------------------------------------------------
VFS.Include("LuaRules/Configs/customcmds.h.lua")
local function RetreatThread()
Sleep(800)
local specialReloadState = Spring.GetUnitRulesParam(unitID,"specialReloadFrame")
if (not specialReloadState or (specialReloadState <= Spring.GetGameFrame())) then
Spring.GiveOrderToUnit(unitID, CMD.INSERT, {0, CMD_ONECLICK_WEAPON, CMD.OPT_INTERNAL,}, CMD.OPT_ALT)
end
end
function RetreatFunction()
StartThread(RetreatThread)
end
----------------------------------------------------------
function SprintThread()
for i=1, SPEEDUP_DURATION do
EmitSfx(ljet, 1027)
EmitSfx(rjet, 1027)
Sleep(33)
end
while (Spring.MoveCtrl.GetTag(unitID) ~= nil) do --is true when unit_refuel_pad_handler.lua is MoveCtrl-ing unit, wait until MoveCtrl disabled before restore speed.
Sleep(33)
end
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1)
-- Spring.MoveCtrl.SetAirMoveTypeData(unitID, "maxAcc", 0.5)
GG.UpdateUnitAttributes(unitID)
Turn(rwing, y_axis, 0, math.rad(100))
Turn(lwing, y_axis, 0, math.rad(100))
end
function Sprint()
Turn(rwing, y_axis, math.rad(65), math.rad(300))
Turn(lwing, y_axis, math.rad(-65), math.rad(300))
StartThread(SprintThread)
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", SPEEDUP_FACTOR)
-- Spring.MoveCtrl.SetAirMoveTypeData(unitID, "maxAcc", 3)
GG.UpdateUnitAttributes(unitID)
end
----------------------------------------------------------
local WING_DISTANCE = 8
local function activate()
Move(rwing, x_axis, 0, 10)
Move(lwing, x_axis, 0, 10)
end
local function deactivate()
Move(rwing, x_axis, WING_DISTANCE, 10)
Move(lwing, x_axis, -WING_DISTANCE, 10)
Turn(rwing, y_axis, 0, math.rad(30))
Turn(lwing, y_axis, 0, math.rad(30))
end
function script.Create()
Move(rwing, x_axis, WING_DISTANCE)
Move(lwing, x_axis, -WING_DISTANCE)
end
function script.StartMoving()
activate()
end
function script.StopMoving()
deactivate()
end
function script.QueryWeapon(num)
if num == 1 then
return flare[shotCycle]
elseif num == 2 then
return flare2
end
end
function script.AimFromWeapon(num)
return base
end
function script.AimWeapon(num, heading, pitch)
return not (GetUnitValue(COB.CRASHING) == 1)
end
function script.FireWeapon(num)
if num == 1 then
shotCycle = 1 - shotCycle
EmitSfx(flare[shotCycle], UNIT_SFX3)
elseif num == 2 then
EmitSfx(flare2, UNIT_SFX3)
elseif num == 3 then
EmitSfx(missile, UNIT_SFX2)
end
end
function script.BlockShot(num, targetID)
if (GetUnitValue(COB.CRASHING) == 1) then
return true
end
if num == 2 then
return GG.OverkillPrevention_CheckBlock(unitID, targetID, 133, 35)
end
return false
end
function script.Killed(recentDamage, maxHealth)
local severity = (recentDamage/maxHealth)
if severity < 0.5 or (Spring.GetUnitMoveTypeData(unitID).aircraftState == "crashing") then
Explode(base, sfxNone)
Explode(rwing, sfxNone)
Explode(lwing, sfxNone)
Explode(rjet, sfxSmoke + sfxFire + sfxExplode + sfxShatter + sfxExplodeOnHit)
Explode(ljet, sfxSmoke + sfxFire + sfxExplode + sfxShatter + sfxExplodeOnHit)
return 1
else
Explode(base, sfxNone)
Explode(rwing, sfxNone)
Explode(lwing, sfxNone)
Explode(rjet, sfxSmoke + sfxFire + sfxExplode + sfxShatter + sfxExplodeOnHit)
Explode(ljet, sfxSmoke + sfxFire + sfxExplode + sfxShatter + sfxExplodeOnHit)
return 2
end
end
| gpl-2.0 |
EliHar/Pattern_recognition | torch1/extra/penlight/lua/pl/utils.lua | 6 | 14946 | --- Generally useful routines.
-- See @{01-introduction.md.Generally_useful_functions|the Guide}.
-- @module pl.utils
local format,gsub,byte = string.format,string.gsub,string.byte
local compat = require 'pl.compat'
local clock = os.clock
local stdout = io.stdout
local append = table.insert
local unpack = rawget(_G,'unpack') or rawget(table,'unpack')
local collisions = {}
local utils = {
_VERSION = "1.3.2",
lua51 = compat.lua51,
setfenv = compat.setfenv,
getfenv = compat.getfenv,
load = compat.load,
execute = compat.execute,
dir_separator = _G.package.config:sub(1,1),
unpack = unpack
}
--- end this program gracefully.
-- @param code The exit code or a message to be printed
-- @param ... extra arguments for message's format'
-- @see utils.fprintf
function utils.quit(code,...)
if type(code) == 'string' then
utils.fprintf(io.stderr,code,...)
code = -1
else
utils.fprintf(io.stderr,...)
end
io.stderr:write('\n')
os.exit(code)
end
--- print an arbitrary number of arguments using a format.
-- @param fmt The format (see string.format)
-- @param ... Extra arguments for format
function utils.printf(fmt,...)
utils.assert_string(1,fmt)
utils.fprintf(stdout,fmt,...)
end
--- write an arbitrary number of arguments to a file using a format.
-- @param f File handle to write to.
-- @param fmt The format (see string.format).
-- @param ... Extra arguments for format
function utils.fprintf(f,fmt,...)
utils.assert_string(2,fmt)
f:write(format(fmt,...))
end
local function import_symbol(T,k,v,libname)
local key = rawget(T,k)
-- warn about collisions!
if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then
utils.fprintf(io.stderr,"warning: '%s.%s' will not override existing symbol\n",libname,k)
return
end
rawset(T,k,v)
end
local function lookup_lib(T,t)
for k,v in pairs(T) do
if v == t then return k end
end
return '?'
end
local already_imported = {}
--- take a table and 'inject' it into the local namespace.
-- @param t The Table
-- @param T An optional destination table (defaults to callers environment)
function utils.import(t,T)
T = T or _G
t = t or utils
if type(t) == 'string' then
t = require (t)
end
local libname = lookup_lib(T,t)
if already_imported[t] then return end
already_imported[t] = libname
for k,v in pairs(t) do
import_symbol(T,k,v,libname)
end
end
utils.patterns = {
FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*',
INTEGER = '[+%-%d]%d*',
IDEN = '[%a_][%w_]*',
FILE = '[%a%.\\][:%][%w%._%-\\]*'
}
--- escape any 'magic' characters in a string
-- @param s The input string
function utils.escape(s)
utils.assert_string(1,s)
return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1'))
end
--- return either of two values, depending on a condition.
-- @param cond A condition
-- @param value1 Value returned if cond is true
-- @param value2 Value returned if cond is false (can be optional)
function utils.choose(cond,value1,value2)
if cond then return value1
else return value2
end
end
local raise
--- return the contents of a file as a string
-- @param filename The file path
-- @param is_bin open in binary mode
-- @return file contents
function utils.readfile(filename,is_bin)
local mode = is_bin and 'b' or ''
utils.assert_string(1,filename)
local f,err = io.open(filename,'r'..mode)
if not f then return utils.raise (err) end
local res,err = f:read('*a')
f:close()
if not res then return raise (err) end
return res
end
--- write a string to a file
-- @param filename The file path
-- @param str The string
-- @return true or nil
-- @return error message
-- @raise error if filename or str aren't strings
function utils.writefile(filename,str)
utils.assert_string(1,filename)
utils.assert_string(2,str)
local f,err = io.open(filename,'w')
if not f then return raise(err) end
f:write(str)
f:close()
return true
end
--- return the contents of a file as a list of lines
-- @param filename The file path
-- @return file contents as a table
-- @raise errror if filename is not a string
function utils.readlines(filename)
utils.assert_string(1,filename)
local f,err = io.open(filename,'r')
if not f then return raise(err) end
local res = {}
for line in f:lines() do
append(res,line)
end
f:close()
return res
end
--- split a string into a list of strings separated by a delimiter.
-- @param s The input string
-- @param re A Lua string pattern; defaults to '%s+'
-- @param plain don't use Lua patterns
-- @param n optional maximum number of splits
-- @return a list-like table
-- @raise error if s is not a string
function utils.split(s,re,plain,n)
utils.assert_string(1,s)
local find,sub,append = string.find, string.sub, table.insert
local i1,ls = 1,{}
if not re then re = '%s+' end
if re == '' then return {s} end
while true do
local i2,i3 = find(s,re,i1,plain)
if not i2 then
local last = sub(s,i1)
if last ~= '' then append(ls,last) end
if #ls == 1 and ls[1] == '' then
return {}
else
return ls
end
end
append(ls,sub(s,i1,i2-1))
if n and #ls == n then
ls[#ls] = sub(s,i1)
return ls
end
i1 = i3+1
end
end
--- split a string into a number of values.
-- @param s the string
-- @param re the delimiter, default space
-- @return n values
-- @usage first,next = splitv('jane:doe',':')
-- @see split
function utils.splitv (s,re)
return unpack(utils.split(s,re))
end
--- convert an array of values to strings.
-- @param t a list-like table
-- @param temp buffer to use, otherwise allocate
-- @param tostr custom tostring function, called with (value,index).
-- Otherwise use `tostring`
-- @return the converted buffer
function utils.array_tostring (t,temp,tostr)
temp, tostr = temp or {}, tostr or tostring
for i = 1,#t do
temp[i] = tostr(t[i],i)
end
return temp
end
--- execute a shell command and return the output.
-- This function redirects the output to tempfiles and returns the content of those files.
-- @param cmd a shell command
-- @param bin boolean, if true, read output as binary file
-- @return true if successful
-- @return actual return code
-- @return stdout output (string)
-- @return errout output (string)
function utils.executeex(cmd, bin)
local mode
local outfile = os.tmpname()
local errfile = os.tmpname()
if utils.dir_separator == '\\' then
outfile = os.getenv('TEMP')..outfile
errfile = os.getenv('TEMP')..errfile
end
cmd = cmd .. [[ >"]]..outfile..[[" 2>"]]..errfile..[["]]
local success, retcode = utils.execute(cmd)
local outcontent = utils.readfile(outfile, bin)
local errcontent = utils.readfile(errfile, bin)
os.remove(outfile)
os.remove(errfile)
return success, retcode, (outcontent or ""), (errcontent or "")
end
--- 'memoize' a function (cache returned value for next call).
-- This is useful if you have a function which is relatively expensive,
-- but you don't know in advance what values will be required, so
-- building a table upfront is wasteful/impossible.
-- @param func a function of at least one argument
-- @return a function with at least one argument, which is used as the key.
function utils.memoize(func)
return setmetatable({}, {
__index = function(self, k, ...)
local v = func(k,...)
self[k] = v
return v
end,
__call = function(self, k) return self[k] end
})
end
utils.stdmt = {
List = {_name='List'}, Map = {_name='Map'},
Set = {_name='Set'}, MultiMap = {_name='MultiMap'}
}
local _function_factories = {}
--- associate a function factory with a type.
-- A function factory takes an object of the given type and
-- returns a function for evaluating it
-- @tab mt metatable
-- @func fun a callable that returns a function
function utils.add_function_factory (mt,fun)
_function_factories[mt] = fun
end
local function _string_lambda(f)
local raise = utils.raise
if f:find '^|' or f:find '_' then
local args,body = f:match '|([^|]*)|(.+)'
if f:find '_' then
args = '_'
body = f
else
if not args then return raise 'bad string lambda' end
end
local fstr = 'return function('..args..') return '..body..' end'
local fn,err = utils.load(fstr)
if not fn then return raise(err) end
fn = fn()
return fn
else return raise 'not a string lambda'
end
end
--- an anonymous function as a string. This string is either of the form
-- '|args| expression' or is a function of one argument, '_'
-- @param lf function as a string
-- @return a function
-- @usage string_lambda '|x|x+1' (2) == 3
-- @usage string_lambda '_+1 (2) == 3
-- @function utils.string_lambda
utils.string_lambda = utils.memoize(_string_lambda)
local ops
--- process a function argument.
-- This is used throughout Penlight and defines what is meant by a function:
-- Something that is callable, or an operator string as defined by <code>pl.operator</code>,
-- such as '>' or '#'. If a function factory has been registered for the type, it will
-- be called to get the function.
-- @param idx argument index
-- @param f a function, operator string, or callable object
-- @param msg optional error message
-- @return a callable
-- @raise if idx is not a number or if f is not callable
function utils.function_arg (idx,f,msg)
utils.assert_arg(1,idx,'number')
local tp = type(f)
if tp == 'function' then return f end -- no worries!
-- ok, a string can correspond to an operator (like '==')
if tp == 'string' then
if not ops then ops = require 'pl.operator'.optable end
local fn = ops[f]
if fn then return fn end
local fn, err = utils.string_lambda(f)
if not fn then error(err..': '..f) end
return fn
elseif tp == 'table' or tp == 'userdata' then
local mt = getmetatable(f)
if not mt then error('not a callable object',2) end
local ff = _function_factories[mt]
if not ff then
if not mt.__call then error('not a callable object',2) end
return f
else
return ff(f) -- we have a function factory for this type!
end
end
if not msg then msg = " must be callable" end
if idx > 0 then
error("argument "..idx..": "..msg,2)
else
error(msg,2)
end
end
--- bind the first argument of the function to a value.
-- @param fn a function of at least two values (may be an operator string)
-- @param p a value
-- @return a function such that f(x) is fn(p,x)
-- @raise same as @{function_arg}
-- @see func.bind1
function utils.bind1 (fn,p)
fn = utils.function_arg(1,fn)
return function(...) return fn(p,...) end
end
--- bind the second argument of the function to a value.
-- @param fn a function of at least two values (may be an operator string)
-- @param p a value
-- @return a function such that f(x) is fn(x,p)
-- @raise same as @{function_arg}
function utils.bind2 (fn,p)
fn = utils.function_arg(1,fn)
return function(x,...) return fn(x,p,...) end
end
--- assert that the given argument is in fact of the correct type.
-- @param n argument index
-- @param val the value
-- @param tp the type
-- @param verify an optional verfication function
-- @param msg an optional custom message
-- @param lev optional stack position for trace, default 2
-- @raise if the argument n is not the correct type
-- @usage assert_arg(1,t,'table')
-- @usage assert_arg(n,val,'string',path.isdir,'not a directory')
function utils.assert_arg (n,val,tp,verify,msg,lev)
if type(val) ~= tp then
error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2)
end
if verify and not verify(val) then
error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2)
end
end
--- assert the common case that the argument is a string.
-- @param n argument index
-- @param val a value that must be a string
-- @raise val must be a string
function utils.assert_string (n,val)
utils.assert_arg(n,val,'string',nil,nil,3)
end
local err_mode = 'default'
--- control the error strategy used by Penlight.
-- Controls how <code>utils.raise</code> works; the default is for it
-- to return nil and the error string, but if the mode is 'error' then
-- it will throw an error. If mode is 'quit' it will immediately terminate
-- the program.
-- @param mode - either 'default', 'quit' or 'error'
-- @see utils.raise
function utils.on_error (mode)
if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then
err_mode = mode
else
-- fail loudly
if err_mode == 'default' then err_mode = 'error' end
utils.raise("Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'")
end
end
--- used by Penlight functions to return errors. Its global behaviour is controlled
-- by <code>utils.on_error</code>
-- @param err the error string.
-- @see utils.on_error
function utils.raise (err)
if err_mode == 'default' then return nil,err
elseif err_mode == 'quit' then utils.quit(err)
else error(err,2)
end
end
--- is the object of the specified type?.
-- If the type is a string, then use type, otherwise compare with metatable
-- @param obj An object to check
-- @param tp String of what type it should be
function utils.is_type (obj,tp)
if type(tp) == 'string' then return type(obj) == tp end
local mt = getmetatable(obj)
return tp == mt
end
raise = utils.raise
--- load a code string or bytecode chunk.
-- @param code Lua code as a string or bytecode
-- @param name for source errors
-- @param mode kind of chunk, 't' for text, 'b' for bytecode, 'bt' for all (default)
-- @param env the environment for the new chunk (default nil)
-- @return compiled chunk
-- @return error message (chunk is nil)
-- @function utils.load
---------------
-- Get environment of a function.
-- With Lua 5.2, may return nil for a function with no global references!
-- Based on code by [Sergey Rozhenko](http://lua-users.org/lists/lua-l/2010-06/msg00313.html)
-- @param f a function or a call stack reference
-- @function utils.getfenv
---------------
-- Set environment of a function
-- @param f a function or a call stack reference
-- @param env a table that becomes the new environment of `f`
-- @function utils.setfenv
--- execute a shell command.
-- This is a compatibility function that returns the same for Lua 5.1 and Lua 5.2
-- @param cmd a shell command
-- @return true if successful
-- @return actual return code
-- @function utils.execute
return utils
| mit |
Amadiro/obtuse-tanuki | libs/iqm/init.lua | 2 | 5774 | local base = (...):gsub('%.init$', '') .. "."
local c = require(base .. "iqm-ffi")
local ffi = require "ffi"
local iqm = {}
iqm.lookup = {}
function iqm.load(file)
assert(love.filesystem.isFile(file))
-- Make sure it's a valid IQM file first
local magic = love.filesystem.read(file, 16)
assert(magic == "INTERQUAKEMODEL\0")
-- HACK: Workaround for a bug in LuaJIT's GC - we need to turn it off for the
-- rest of the function or we'll get a segfault shortly into these loops.
--
-- I've got no idea why the GC thinks it can pull the rug out from under us,
-- but I sure as hell don't appreciate it. -ss
collectgarbage("stop")
-- Decode the header, it's got all the offsets
local iqm_header = ffi.typeof("struct iqmheader*")
local size = ffi.sizeof("struct iqmheader")
local data = love.filesystem.read(file)
local header = ffi.cast(iqm_header, data)[0]
-- We only support IQM version 2
assert(header.version == 2)
local function read_offset(data, type, offset, num)
local decoded = {}
local type_ptr = ffi.typeof(type.."*")
local size = ffi.sizeof(type)
local ptr = ffi.cast(type_ptr, data:sub(offset+1))
for i = 1, num do
table.insert(decoded, ptr[i-1])
end
return decoded
end
-- a bit simpler than read_offset, don't bother converting to a table.
local function read_ptr(data, type, offset)
local type_ptr = ffi.typeof(type.."*")
local size = ffi.sizeof(type)
local ptr = ffi.cast(type_ptr, data:sub(offset+1))
return ptr
end
-- Decode the vertex arrays
local vertex_arrays = read_offset(
data,
"struct iqmvertexarray",
header.ofs_vertexarrays,
header.num_vertexarrays
)
local function translate_va(type)
local types = {
[c.IQM_POSITION] = "position",
[c.IQM_TEXCOORD] = "texcoord",
[c.IQM_NORMAL] = "normal",
[c.IQM_TANGENT] = "tangent",
[c.IQM_COLOR] = "color",
[c.IQM_BLENDINDEXES] = "bone",
[c.IQM_BLENDWEIGHTS] = "weight"
}
return types[type] or false
end
local function translate_format(type)
local types = {
[c.IQM_FLOAT] = "float",
[c.IQM_UBYTE] = "byte",
}
return types[type] or false
end
local function translate_love(type)
local types = {
position = "VertexPosition",
texcoord = "VertexTexCoord",
normal = "VertexNormal",
tangent = "VertexTangent",
bone = "VertexBone",
weight = "VertexWeight",
color = "VertexColor",
}
return assert(types[type])
end
-- Build iqm_vertex struct out of whatever is in this file
local found = {}
local found_names = {}
local found_types = {}
for _, va in ipairs(vertex_arrays) do
while true do
local type = translate_va(va.type)
if not type then
break
end
local format = assert(translate_format(va.format))
table.insert(found, string.format("%s %s[%d]", format, type, va.size))
table.insert(found_names, type)
table.insert(found_types, {
type = type,
size = va.size,
offset = va.offset,
format = format,
love_type = translate_love(type)
})
break end
end
table.sort(found_names)
local title = "iqm_vertex_" .. table.concat(found_names, "_")
print(title)
local type = iqm.lookup[title]
if not type then
local def = string.format("struct %s {\n\t%s;\n};", title, table.concat(found, ";\n\t"))
ffi.cdef(def)
local ct = ffi.typeof("struct " .. title)
iqm.lookup[title] = ct
type = ct
end
local filedata = love.filesystem.newFileData(("\0"):rep(header.num_vertexes * ffi.sizeof(type)), "dummy")
local vertices = ffi.cast("struct " .. title .. "*", filedata:getPointer())
local correct_srgb = select(3, love.window.getMode()).srgb
-- Interleave vertex data
for _, va in ipairs(found_types) do
local ptr = read_ptr(data, va.format, va.offset)
for i = 0, header.num_vertexes-1 do
for j = 0, va.size-1 do
vertices[i][va.type][j] = ptr[i*va.size+j]
end
if va.type == "color" and correct_srgb then
local v = vertices[i][va.type]
local r, g, b = love.math.gammaToLinear(v[0] / 255, v[1] / 255, v[2] / 255)
v[0], v[1], v[2] = r*255, g*255, b*255
end
end
end
-- Decode triangle data (index buffer)
local triangles = read_offset(
data,
"struct iqmtriangle",
header.ofs_triangles,
header.num_triangles
)
assert(#triangles == header.num_triangles)
-- Translate indices for love
local indices = {}
for _, triangle in ipairs(triangles) do
table.insert(indices, triangle.vertex[0] + 1)
table.insert(indices, triangle.vertex[1] + 1)
table.insert(indices, triangle.vertex[2] + 1)
end
collectgarbage("restart")
local layout = {}
for i, va in ipairs(found_types) do
layout[i] = { va.love_type, va.format, va.size }
end
local m = love.graphics.newMesh(layout, filedata, "triangles")
m:setVertexMap(indices)
-- Decode mesh/material names.
local text = read_ptr(
data,
"char",
header.ofs_text
)
--[[
-- Collect all text data in the file.
-- Not needed for meshes because everything is byte offsets - but very
-- useful for debugging.
local strings = {}
local advance = 1
-- header.num_text is the length of the text block in bytes.
repeat
local str = ffi.string(text + advance)
table.insert(strings, str)
advance = advance + str:len() + 1
print(str)
until advance >= header.num_text
--]]
-- Decode meshes
local meshes = read_offset(
data,
"struct iqmmesh",
header.ofs_meshes,
header.num_meshes
)
local objects = {}
objects.mesh = m
for i, mesh in ipairs(meshes) do
local add = {
first = mesh.first_triangle * 3 + 1,
count = mesh.num_triangles * 3,
material = ffi.string(text+mesh.material),
name = ffi.string(text+mesh.name)
}
add.last = add.first + add.count
table.insert(objects, add)
end
return objects
end
return iqm
| mit |
rlcevg/Zero-K | LuaUI/Widgets/chili/Controls/font.lua | 17 | 6639 | --//=============================================================================
Font = Object:Inherit{
classname = 'font',
font = "FreeSansBold.otf",
size = 12,
outlineWidth = 3,
outlineWeight = 3,
shadow = false,
outline = false,
color = {1,1,1,1},
outlineColor = {0,0,0,1},
autoOutlineColor = true,
}
local this = Font
local inherited = this.inherited
--//=============================================================================
function Font:New(obj)
obj = inherited.New(self,obj)
--// Load the font
obj:_LoadFont()
return obj
end
function Font:Dispose(...)
if (not self.disposed) then
FontHandler.UnloadFont(self._font)
end
inherited.Dispose(self,...)
end
--//=============================================================================
function Font:_LoadFont()
local oldfont = self._font
self._font = FontHandler.LoadFont(self.font,self.size,self.outlineWidth,self.outlineWeight)
--// do this after LoadFont because it can happen that LoadFont returns the same font again
--// but if we Unload our old one before, the gc could collect it before, so the engine would have to reload it again
FontHandler.UnloadFont(oldfont)
end
--//=============================================================================
local function NotEqual(v1, v2)
local t1 = type(v1)
local t2 = type(v2)
if (t1 ~= t2) then
return true
end
local isindexable = (t=="table")or(t=="metatable")or(t=="userdata")
if (not isindexable) then
return (t1 ~= t2)
end
for i,v in pairs(v1) do
if (v ~= v2[i]) then
return true
end
end
for i,v in pairs(v2) do
if (v ~= v1[i]) then
return true
end
end
end
do
--// Create some Set... methods (e.g. SetColor, SetSize, SetFont, ...)
local params = {
font = true,
size = true,
outlineWidth = true,
outlineWeight = true,
shadow = false,
outline = false,
color = false,
outlineColor = false,
autoOutlineColor = false,
}
for param,recreateFont in pairs(params) do
local paramWithUpperCase = param:gsub("^%l", string.upper)
local funcname = "Set" .. paramWithUpperCase
Font[funcname] = function(self,value,...)
local t = type(value)
local oldValue = self[param]
if (t == "table") then
self[param] = table.shallowcopy(value)
else
local to = type(self[param])
if (to == "table") then
--// this allows :SetColor(r,g,b,a) and :SetColor({r,g,b,a})
local newtable = {value,...}
table.merge(newtable,self[param])
self[param] = newtable
else
self[param] = value
end
end
local p = self.parent
if (recreateFont) then
self:_LoadFont()
if (p) then
p:RequestRealign()
end
else
if (p)and NotEqual(oldValue, self[param]) then
p:Invalidate()
end
end
end
end
params = nil
end
--//=============================================================================
function Font:GetLineHeight(size)
return self._font.lineheight * (size or self.size)
end
function Font:GetAscenderHeight(size)
local font = self._font
return (font.lineheight + font.descender) * (size or self.size)
end
function Font:GetTextWidth(text, size)
return (self._font):GetTextWidth(text) * (size or self.size)
end
function Font:GetTextHeight(text, size)
if (not size) then size = self.size end
local h,descender,numlines = (self._font):GetTextHeight(text)
return h*size, descender*size, numlines
end
function Font:WrapText(text, width, height, size)
if (not size) then size = self.size end
if (height < 1.5 * self._font.lineheight)or(width < size) then
return text --//workaround for a bug in <=80.5.2
end
return (self._font):WrapText(text,width,height,size)
end
--//=============================================================================
function Font:AdjustPosToAlignment(x, y, width, height, align, valign)
local extra = ''
--// vertical alignment
if valign == "center" then
y = y + height/2
extra = 'v'
elseif valign == "top" then
extra = 't'
elseif valign == "bottom" then
y = y + height
extra = 'b'
elseif valign == "linecenter" then
y = y + (height / 2) + (1 + self._font.descender) * self.size / 2
extra = 'x'
else
--// ascender
extra = 'a'
end
--FIXME add baseline 'd'
--// horizontal alignment
if align == "left" then
--do nothing
elseif align == "center" then
x = x + width/2
extra = extra .. 'c'
elseif align == "right" then
x = x + width
extra = extra .. 'r'
end
return x,y,extra
end
local function _GetExtra(align, valign)
local extra = ''
--// vertical alignment
if valign == "center" then
extra = 'v'
elseif valign == "top" then
extra = 't'
elseif valign == "bottom" then
extra = 'b'
else
--// ascender
extra = 'a'
end
--// horizontal alignment
if align == "left" then
--do nothing
elseif align == "center" then
extra = extra .. 'c'
elseif align == "right" then
extra = extra .. 'r'
end
return extra
end
--//=============================================================================
function Font:Draw(text, x, y, align, valign)
if (not text) then
return
end
local font = self._font
local extra = _GetExtra(align, valign)
if self.outline then
extra = extra .. 'o'
elseif self.shadow then
extra = extra .. 's'
end
gl.PushMatrix()
gl.Scale(1,-1,1)
font:Begin()
font:SetTextColor(self.color)
font:SetOutlineColor(self.outlineColor)
font:SetAutoOutlineColor(self.autoOutlineColor)
font:Print(text, x, -y, self.size, extra)
font:End()
gl.PopMatrix()
end
function Font:DrawInBox(text, x, y, w, h, align, valign)
if (not text) then
return
end
local font = self._font
local x,y,extra = self:AdjustPosToAlignment(x, y, w, h, align, valign)
if self.outline then
extra = extra .. 'o'
elseif self.shadow then
extra = extra .. 's'
end
y = y + 1 --// FIXME: if this isn't done some chars as 'R' get truncated at the top
gl.PushMatrix()
gl.Scale(1,-1,1)
font:Begin()
font:SetTextColor(self.color)
font:SetOutlineColor(self.outlineColor)
font:SetAutoOutlineColor(self.autoOutlineColor)
font:Print(text, x, -y, self.size, extra)
font:End()
gl.PopMatrix()
end
Font.Print = Font.Draw
Font.PrintInBox = Font.DrawInBox
--//=============================================================================
| gpl-2.0 |
ViolyS/RayUI_VS | Interface/AddOns/Skada/Skada.lua | 1 | 84710 | local Skada = LibStub("AceAddon-3.0"):NewAddon("Skada", "AceTimer-3.0", "LibNotify-1.0")
_G.Skada = Skada
local L = LibStub("AceLocale-3.0"):GetLocale("Skada", false)
local ldb = LibStub:GetLibrary("LibDataBroker-1.1")
local icon = LibStub("LibDBIcon-1.0", true)
local media = LibStub("LibSharedMedia-3.0")
local boss = LibStub("LibBossIDs-1.0")
local lds = LibStub:GetLibrary("LibDualSpec-1.0", 1)
local dataobj = ldb:NewDataObject("Skada", {label = "Skada", type = "data source", icon = "Interface\\Icons\\Spell_Lightning_LightningBolt01", text = "n/a"})
local popup, cleuFrame
local AceConfigDialog = LibStub('AceConfigDialog-3.0')
-- Used for automatic stop on wipe option
local deathcounter = 0
local startingmembers = 0
-- Aliases
local table_sort, tinsert, tremove, table_maxn = _G.table.sort, tinsert, tremove, _G.table.maxn
local next, pairs, ipairs, type = next, pairs, ipairs, type
-- Returns the group type (i.e., "party" or "raid") and the size of the group.
function Skada:GetGroupTypeAndCount()
local type
local count = GetNumGroupMembers()
if IsInRaid() then
type = "raid"
elseif IsInGroup() then
type = "party"
-- To make the counts similar between 4.3 and 5.0, we need
-- to subtract one because GetNumPartyMembers() does not
-- include the player while GetNumGroupMembers() does.
count = count - 1
end
return type, count
end
do
popup = CreateFrame("Frame", nil, UIParent) -- Recycle the popup frame as an event handler.
popup:SetScript("OnEvent", function(frame, event, ...)
Skada[event](Skada, ...)
end)
popup:SetBackdrop({bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background-Dark",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = {left = 1, right = 1, top = 1, bottom = 1}}
)
popup:SetSize(250, 100)
popup:SetPoint("CENTER", UIParent, "CENTER")
popup:SetFrameStrata("DIALOG")
popup:Hide()
popup:EnableKeyboard(true)
popup:SetScript("OnKeyDown", function(self,key)
if GetBindingFromClick(key) == "TOGGLEGAMEMENU" then
popup:SetPropagateKeyboardInput(false) -- swallow escape
popup:Hide()
end
end)
local text = popup:CreateFontString(nil, "ARTWORK", "ChatFontNormal")
text:SetPoint("TOP", popup, "TOP", 0, -15)
text:SetText(L["Do you want to reset Skada?"])
local accept = CreateFrame("Button", nil, popup)
accept:SetNormalTexture("Interface\\Buttons\\UI-CheckBox-Check")
accept:SetHighlightTexture("Interface\\Buttons\\UI-CheckBox-Highlight", "ADD")
accept:SetSize(50, 50)
accept:SetPoint("BOTTOM", popup, "BOTTOM", -50, 5)
accept:SetScript("OnClick", function(f) Skada:Reset() f:GetParent():Hide() end)
local close = CreateFrame("Button", nil, popup)
close:SetNormalTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Up")
close:SetHighlightTexture("Interface\\Buttons\\UI-Panel-MinimizeButton-Highlight", "ADD")
close:SetSize(50, 50)
close:SetPoint("BOTTOM", popup, "BOTTOM", 50, 5)
close:SetScript("OnClick", function(f) f:GetParent():Hide() end)
function Skada:ShowPopup()
popup:SetPropagateKeyboardInput(true)
popup:Show()
end
end
-- Keybindings
BINDING_HEADER_Skada = "Skada"
BINDING_NAME_SKADA_TOGGLE = L["Toggle window"]
BINDING_NAME_SKADA_RESET = L["Reset"]
BINDING_NAME_SKADA_NEWSEGMENT = L["Start new segment"]
BINDING_NAME_SKADA_STOP = L["Stop"]
-- The current set
Skada.current = nil
-- The total set
Skada.total = nil
-- The last set
Skada.last = nil
-- Modes - these are modules, really. Modeules?
local modes = {}
-- Pets; an array of pets and their owners.
local pets, players = {}, {}
-- Flag marking if we need an update.
local changed = true
-- Flag for if we were in a party/raid.
local wasinparty = nil
-- By default we just use RAID_CLASS_COLORS as class colors.
Skada.classcolors = RAID_CLASS_COLORS
-- The selected data feed.
local selectedfeed = nil
-- A list of data feeds available. Modules add to it.
local feeds = {}
-- Disabled flag.
local disabled = false
-- Our windows.
local windows = {}
-- Our display providers.
Skada.displays = {}
-- Timer for updating windows.
local update_timer = nil
-- Timer for checking for combat end.
local tick_timer = nil
function Skada:GetWindows()
return windows
end
local function find_mode(name)
for i, mode in ipairs(modes) do
if mode:GetName() == name then
return mode
end
end
end
-- Our window type.
local Window = {}
local mt = {__index = Window}
function Window:new()
return setmetatable(
{
-- The selected mode and set
selectedmode = nil,
selectedset = nil,
-- Mode and set to return to after combat.
restore_mode = nil,
restore_set = nil,
usealt = true,
-- Our dataset.
dataset = {},
-- Metadata about our dataset.
metadata = {},
-- Our display provider.
display = nil,
-- Our mode traversing history.
history = {},
-- Flag for window-specific changes.
changed = false,
}, mt)
end
function Window:AddOptions()
local db = self.db
local options = {
type="group",
name=function() return db.name end,
args={
rename = {
type="input",
name=L["Rename window"],
desc=L["Enter the name for the window."],
get=function() return db.name end,
set=function(win, val)
if val ~= db.name and val ~= "" then
local oldname = db.name
db.name = val
Skada.options.args.windows.args[val] = Skada.options.args.windows.args[oldname]
Skada.options.args.windows.args[oldname] = nil
end
end,
order=1,
},
locked = {
type="toggle",
name=L["Lock window"],
desc=L["Locks the bar window in place."],
order=2,
get=function() return db.barslocked end,
set=function()
db.barslocked = not db.barslocked
Skada:ApplySettings()
end,
},
delete = {
type="execute",
name=L["Delete window"],
desc=L["Deletes the chosen window."],
order=20,
width="full",
confirm=function() return "Are you sure you want to delete this window?" end,
func=function(self) Skada:DeleteWindow(db.name) end,
},
}
}
options.args.switchoptions = {
type = "group",
name = L["Mode switching"],
order=4,
args = {
modeincombat = {
type="select",
name=L["Combat mode"],
desc=L["Automatically switch to set 'Current' and this mode when entering combat."],
values=function()
local modes = {}
modes[""] = L["None"]
for i, mode in ipairs(Skada:GetModes()) do
modes[mode:GetName()] = mode:GetName()
end
return modes
end,
get=function() return db.modeincombat end,
set=function(win, mode) db.modeincombat = mode end,
order=21,
},
wipemode = {
type="select",
name=L["Wipe mode"],
desc=L["Automatically switch to set 'Current' and this mode after a wipe."],
values=function()
local modes = {}
modes[""] = L["None"]
for i, mode in ipairs(Skada:GetModes()) do
modes[mode:GetName()] = mode:GetName()
end
return modes
end,
get=function() return db.wipemode end,
set=function(win, mode) db.wipemode = mode end,
order=21,
},
returnaftercombat = {
type="toggle",
name=L["Return after combat"],
desc=L["Return to the previous set and mode after combat ends."],
order=23,
get=function() return db.returnaftercombat end,
set=function() db.returnaftercombat = not db.returnaftercombat end,
disabled=function() return db.returnaftercombat == nil end,
},
}
}
self.display:AddDisplayOptions(self, options.args)
Skada.options.args.windows.args[self.db.name] = options
end
-- Sets a slave window for this window. This window will also be updated on view updates.
function Window:SetChild(window)
self.child = window
end
function Window:destroy()
self.dataset = nil
self.display:Destroy(self)
local name = self.db.name or Skada.windowdefaults.name
Skada.options.args.windows.args[name] = nil -- remove from options
end
function Window:SetDisplay(name)
-- Don't do anything if nothing actually changed.
if name ~= self.db.display or self.display == nil then
if self.display then
-- Destroy old display.
self.display:Destroy(self)
end
-- Set new display.
self.db.display = name
self.display = Skada.displays[self.db.display]
-- Add options. Replaces old options.
self:AddOptions()
end
end
-- Tells window to update the display of its dataset, using its display provider.
function Window:UpdateDisplay()
-- Fetch max value if our mode has not done this itself.
if not self.metadata.maxvalue then
self.metadata.maxvalue = 0
for i, data in ipairs(self.dataset) do
if data.id and data.value > self.metadata.maxvalue then
self.metadata.maxvalue = data.value
end
end
end
-- Display it.
self.display:Update(self)
self:set_mode_title()
end
-- Called before dataset is updated.
function Window:UpdateInProgress()
for i, data in ipairs(self.dataset) do
if data.ignore then -- ensure total bar icon is cleared before bar is recycled
data.icon = nil
end
data.id = nil
data.ignore = nil
end
end
function Window:Show()
self.display:Show(self)
end
function Window:Hide()
self.display:Hide(self)
end
function Window:IsShown()
return self.display:IsShown(self)
end
function Window:Reset()
for i, data in ipairs(self.dataset) do
wipe(data)
end
end
function Window:Wipe()
-- Clear dataset.
self:Reset()
-- Clear display.
self.display:Wipe(self)
if self.child then
self.child:Wipe()
end
end
-- If selectedset is "current", returns current set if we are in combat, otherwise returns the last set.
function Window:get_selected_set()
return Skada:find_set(self.selectedset)
end
-- Sets up the mode view.
function Window:DisplayMode(mode)
self:Wipe()
self.selectedplayer = nil
self.selectedspell = nil
self.selectedmode = mode
self.metadata = wipe(self.metadata or {})
-- Apply mode's metadata.
if mode.metadata then
for key, value in pairs(mode.metadata) do
self.metadata[key] = value
end
end
self.changed = true
self:set_mode_title() -- in case data sets are empty
if self.child then
self.child:DisplayMode(mode)
end
Skada:UpdateDisplay(false)
end
local numsetfmts = 8
local function SetLabelFormat(name,starttime,endtime,fmt)
fmt = fmt or Skada.db.profile.setformat
local namelabel = name
if fmt < 1 or fmt > numsetfmts then fmt = 3 end
local timelabel = ""
if starttime and endtime and fmt > 1 then
local duration = SecondsToTime(endtime-starttime, false, false, 2)
-- translate locale time abbreviations, whose escape sequences are not legal in chat
Skada.getsetlabel_fs = Skada.getsetlabel_fs or UIParent:CreateFontString(nil, "ARTWORK", "ChatFontNormal")
Skada.getsetlabel_fs:SetText(duration)
duration = "("..Skada.getsetlabel_fs:GetText()..")"
if fmt == 2 then
timelabel = duration
elseif fmt == 3 then
timelabel = date("%H:%M",starttime).." "..duration
elseif fmt == 4 then
timelabel = date("%I:%M",starttime).." "..duration
elseif fmt == 5 then
timelabel = date("%H:%M",starttime).." - "..date("%H:%M",endtime)
elseif fmt == 6 then
timelabel = date("%I:%M",starttime).." - "..date("%I:%M",endtime)
elseif fmt == 7 then
timelabel = date("%H:%M:%S",starttime).." - "..date("%H:%M:%S",endtime)
elseif fmt == 8 then
timelabel = date("%H:%M",starttime).." - "..date("%H:%M",endtime).." "..duration
end
end
local comb
if #namelabel == 0 or #timelabel == 0 then
comb = namelabel..timelabel
elseif timelabel:match("^%p") then
comb = namelabel.." "..timelabel
else
comb = namelabel..": "..timelabel
end
-- provide both the combined label and the separated name/time labels
return comb, namelabel, timelabel
end
function Skada:SetLabelFormats() -- for config option display
local ret = {}
local start = 1000007900
for i=1,numsetfmts do
ret[i] = SetLabelFormat("Hogger", start, start+380, i)
end
return ret
end
function Skada:GetSetLabel(set) -- return a nicely-formatted label for a set
if not set then return "" end
return SetLabelFormat(set.name or "Unknown", set.starttime, set.endtime or time())
end
function Window:set_mode_title()
if not self.selectedmode or not self.selectedset then return end
local name = self.selectedmode.title or self.selectedmode:GetName()
-- save window settings for RestoreView after reload
self.db.set = self.selectedset
local savemode = name
if self.history[1] then -- can't currently preserve a nested mode, use topmost one
savemode = self.history[1].title or self.history[1]:GetName()
end
self.db.mode = savemode
if self.db.titleset then
local setname
if self.selectedset == "current" then
setname = L["Current"]
elseif self.selectedset == "total" then
setname = L["Total"]
else
local set = self:get_selected_set()
if set then
setname = Skada:GetSetLabel(set)
end
end
if setname then
name = name..": "..setname
end
end
if disabled and (self.selectedset == "current" or self.selectedset == "total") then
-- indicate when data collection is disabled
name = name.." |cFFFF0000"..L["DISABLED"].."|r"
end
self.metadata.title = name
self.display:SetTitle(self, name)
end
function sort_modes()
table_sort(modes,
function(a, b)
if Skada.db.profile.sortmodesbyusage and Skada.db.profile.modeclicks then
-- Most frequest usage order
return (Skada.db.profile.modeclicks[a:GetName()] or 0) > (Skada.db.profile.modeclicks[b:GetName()] or 0)
else
-- Alphabetic order
return a:GetName() < b:GetName()
end
end
)
end
local function click_on_mode(win, id, label, button)
if button == "LeftButton" then
local mode = find_mode(id)
if mode then
-- Store number of clicks on modes, for automatic sorting.
if Skada.db.profile.sortmodesbyusage then
if not Skada.db.profile.modeclicks then
Skada.db.profile.modeclicks = {}
end
Skada.db.profile.modeclicks[id] = (Skada.db.profile.modeclicks[id] or 0) + 1
sort_modes()
end
win:DisplayMode(mode)
end
elseif button == "RightButton" then
win:RightClick()
end
end
-- Sets up the mode list.
function Window:DisplayModes(settime)
self.history = wipe(self.history or {})
self:Wipe()
self.selectedplayer = nil
self.selectedmode = nil
self.metadata = wipe(self.metadata or {})
self.metadata.title = L["Skada: Modes"]
-- Find the selected set
if settime == "current" or settime == "total" then
self.selectedset = settime
else
for i, set in ipairs(Skada.char.sets) do
if tostring(set.starttime) == settime then
if set.name == L["Current"] then
self.selectedset = "current"
elseif set.name == L["Total"] then
self.selectedset = "total"
else
self.selectedset = i
end
end
end
end
self.metadata.click = click_on_mode
self.metadata.maxvalue = 1
self.metadata.sortfunc = function(a,b) return a.name < b.name end
self.display:SetTitle(self, self.metadata.title)
self.changed = true
if self.child then
self.child:DisplayModes(settime)
end
Skada:UpdateDisplay(false)
end
local function click_on_set(win, id, label, button)
if button == "LeftButton" then
win:DisplayModes(id)
elseif button == "RightButton" then
win:RightClick()
end
end
-- Sets up the set list.
function Window:DisplaySets()
self.history = wipe(self.history or {})
self:Wipe()
self.metadata = wipe(self.metadata or {})
self.selectedplayer = nil
self.selectedmode = nil
self.selectedset = nil
self.metadata.title = L["Skada: Fights"]
self.display:SetTitle(self, self.metadata.title)
self.metadata.click = click_on_set
self.metadata.maxvalue = 1
-- self.metadata.sortfunc = function(a,b) return a.name < b.name end
self.changed = true
if self.child then
self.child:DisplaySets()
end
Skada:UpdateDisplay(false)
end
-- Default "right-click" behaviour in case no special click function is defined:
-- 1) If there is a mode traversal history entry, go to the last mode.
-- 2) Go to modes list if we are in a mode.
-- 3) Go to set list.
function Window:RightClick(group, button)
if self.selectedmode then
-- If mode traversal history exists, go to last entry, else mode list.
if #self.history > 0 then
self:DisplayMode(tremove(self.history))
else
self:DisplayModes(self.selectedset)
end
elseif self.selectedset then
self:DisplaySets()
end
end
function Skada:tcopy(to, from, ...)
for k,v in pairs(from) do
local skip = false
if ... then
for i, j in ipairs(...) do if j == k then skip = true end end
end
if not skip then
if(type(v)=="table") then
to[k] = {}
Skada:tcopy(to[k], v, ...);
else
to[k] = v;
end
end
end
end
function Skada:CreateWindow(name, db, display)
local isnew = false
if not db then
isnew = true
db = {}
self:tcopy(db, Skada.windowdefaults)
tinsert(self.db.profile.windows, db)
end
if display then
db.display = display
end
-- Migrate old settings.
if not db.barbgcolor then
db.barbgcolor = {r = 0.3, g = 0.3, b = 0.3, a = 0.6}
end
if not db.buttons then
db.buttons = {menu = true, reset = true, report = true, mode = true, segment = true, stop = true}
end
if not db.scale then
db.scale = 1
end
if not db.version then
-- On changes that needs updates to window data structure, increment version in defaults and handle it after this bit.
db.version = 1
db.buttons.stop = true
end
local window = Window:new()
window.db = db
window.db.name = name
if self.displays[window.db.display] then
-- Set the window's display and call it's Create function.
window:SetDisplay(window.db.display or "bar")
window.display:Create(window, isnew)
tinsert(windows, window)
-- Set initial view, set list.
window:DisplaySets()
if isnew and find_mode(L["Damage"]) then
-- Default mode for new windows - will not fail if mode is disabled.
self:RestoreView(window, "current", L["Damage"])
elseif window.db.set or window.db.mode then
-- Restore view.
self:RestoreView(window, window.db.set, window.db.mode)
end
else
-- This window's display is missing.
self:Print("Window '"..name.."' was not loaded because its display module, '"..window.db.display.."' was not found.")
end
self:ApplySettings()
return window
end
-- Deleted named window from our windows table, and also from db.
function Skada:DeleteWindow(name)
for i, win in ipairs(windows) do
if win.db.name == name then
win:destroy()
wipe(tremove(windows, i))
end
end
for i, win in ipairs(self.db.profile.windows) do
if win.name == name then
tremove(self.db.profile.windows, i)
end
end
end
function Skada:Print(msg)
print("|cFF33FF99Skada|r: "..msg)
end
function Skada:Debug(...)
if not Skada.db.profile.debug then return end
local msg = ""
for i=1, select("#",...) do
local v = tostring(select(i,...))
if #msg > 0 then
msg = msg .. ", "
end
msg = msg..v
end
print("|cFF33FF99Skada Debug|r: "..msg)
end
local function slashHandler(param)
local reportusage = "/skada report [raid|party|instance|guild|officer|say] [current||total|set_num] [mode] [max_lines]"
if param == "pets" then
Skada:PetDebug()
elseif param == "cpu" then
local funcs = {}
UpdateAddOnCPUUsage()
for k, v in pairs(Skada) do
if type(v) == "function" then
local usage, calls = GetFunctionCPUUsage(v, true)
--local info = debug.getinfo(v, "n")
tinsert(funcs, {["name"] = k, ["usage"] = usage, ["calls"] = calls})
end
end
table_sort(funcs, function(a, b) return a.usage > b.usage end)
for i, func in ipairs(funcs) do
print(func.name..'\t'..func.usage..' ('..func.calls..')')
if i > 10 then
break
end
end
elseif param == "test" then
Skada:OpenMenu()
elseif param == "reset" then
Skada:Reset()
elseif param == "newsegment" then
Skada:NewSegment()
elseif param == "toggle" then
Skada:ToggleWindow()
elseif param == "debug" then
Skada.db.profile.debug = not Skada.db.profile.debug
Skada:Print("Debug mode "..(Skada.db.profile.debug and ("|cFF00FF00"..L["ENABLED"].."|r") or ("|cFFFF0000"..L["DISABLED"].."|r")))
elseif param == "config" then
Skada:OpenOptions()
elseif param:sub(1,6) == "report" then
local chan = (IsInGroup(LE_PARTY_CATEGORY_INSTANCE) and "instance") or
(IsInRaid() and "raid") or
(IsInGroup() and "party") or
"say"
local set = "current"
local report_mode_name = L["Damage"]
local w1, w2, w3, w4 = param:match("^%s*(%w*)%s*(%w*)%s*([^%d]-)%s*(%d*)%s*$",7)
if w1 and #w1 > 0 then
chan = string.lower(w1)
end
if w2 and #w2 > 0 then
w2 = tonumber(w2) or w2:lower()
if Skada:find_set(w2) then
set = w2
end
end
if w3 and #w3 > 0 then
w3 = strtrim(w3)
w3 = strtrim(w3,"'\"[]()") -- strip optional quoting
if find_mode(w3) then
report_mode_name = w3
end
end
local max = tonumber(w4) or 10
if chan == "instance" then chan = "instance_chat" end
if (chan == "say" or chan == "guild" or chan == "raid" or chan == "party" or chan == "officer" or chan == "instance_chat") then
Skada:Report(chan, "preset", report_mode_name, set, max)
else
Skada:Print("Usage:")
Skada:Print(("%-20s"):format(reportusage))
end
else
Skada:Print("Usage:")
Skada:Print(("%-20s"):format(reportusage))
Skada:Print(("%-20s"):format("/skada reset"))
Skada:Print(("%-20s"):format("/skada toggle"))
Skada:Print(("%-20s"):format("/skada debug"))
Skada:Print(("%-20s"):format("/skada newsegment"))
Skada:Print(("%-20s"):format("/skada config"))
end
end
local function sendchat(msg, chan, chantype)
if chantype == "self" then
-- To self.
Skada:Print(msg)
elseif chantype == "channel" then
-- To channel.
SendChatMessage(msg, "CHANNEL", nil, chan)
elseif chantype == "preset" then
-- To a preset channel id (say, guild, etc).
SendChatMessage(msg, string.upper(chan))
elseif chantype == "whisper" then
-- To player.
SendChatMessage(msg, "WHISPER", nil, chan)
elseif chantype == "bnet" then
BNSendWhisper(chan,msg)
end
end
function Skada:Report(channel, chantype, report_mode_name, report_set_name, max, window)
if(chantype == "channel") then
local list = {GetChannelList()}
for i=1,table.getn(list)/2 do
if(Skada.db.profile.report.channel == list[i*2]) then
channel = list[i*2-1]
break
end
end
end
local report_table
local report_set
local report_mode
if not window then
report_mode = find_mode(report_mode_name)
report_set = Skada:find_set(report_set_name)
if report_set == nil then
return
end
-- Create a temporary fake window.
report_table = Window:new()
-- Tell our mode to populate our dataset.
report_mode:Update(report_table, report_set)
else
report_table = window
report_set = window:get_selected_set()
report_mode = window.selectedmode
end
if not report_set then
Skada:Print(L["There is nothing to report."])
return
end
-- Sort our temporary table according to value unless ordersort is set.
if not report_table.metadata.ordersort then
table_sort(report_table.dataset, Skada.valueid_sort)
end
-- Title
sendchat(string.format(L["Skada: %s for %s:"], report_mode.title or report_mode:GetName(), Skada:GetSetLabel(report_set)), channel, chantype)
-- For each item in dataset, print label and valuetext.
local nr = 1
for i, data in ipairs(report_table.dataset) do
if data.id then
local label = data.reportlabel or (data.spellid and GetSpellLink(data.spellid)) or data.label
if report_mode.metadata and report_mode.metadata.showspots then
sendchat(("%2u. %s %s"):format(nr, label, data.valuetext), channel, chantype)
else
sendchat(("%s %s"):format(label, data.valuetext), channel, chantype)
end
nr = nr + 1
end
if nr > max then
break
end
end
end
function Skada:RefreshMMButton()
if icon then
icon:Refresh("Skada", self.db.profile.icon)
if self.db.profile.icon.hide then
icon:Hide("Skada")
else
icon:Show("Skada")
end
end
end
function Skada:PetDebug()
self:CheckGroup()
self:Print("pets:")
for pet, owner in pairs(pets) do
self:Print("pet "..pet.." belongs to ".. owner.id..", "..owner.name)
end
end
function Skada:SetActive(enable)
if enable then
for i, win in ipairs(windows) do
win:Show()
end
else
for i, win in ipairs(windows) do
win:Hide()
end
end
if not enable and self.db.profile.hidedisables then
if not disabled then -- print a message when we change state
self:Debug(L["Data Collection"].." ".."|cFFFF0000"..L["DISABLED"].."|r")
end
disabled = true
cleuFrame:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
else
if disabled then -- print a message when we change state
self:Debug(L["Data Collection"].." ".."|cFF00FF00"..L["ENABLED"].."|r")
end
disabled = false
cleuFrame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
Skada:UpdateDisplay(true) -- update title indicator
end
function Skada:CheckGroup()
local type, count = self:GetGroupTypeAndCount()
if count > 0 then
for i = 1, count do
local unit = ("%s%d"):format(type, i)
local playerGUID = UnitGUID(unit)
if playerGUID then
players[playerGUID] = true
local unitPet = unit.."pet"
local petGUID = UnitGUID(unitPet)
if petGUID and not pets[petGUID] then
local name, server = UnitName(unit)
if server and server ~= "" then name = name.."-"..server end
pets[petGUID] = {id = playerGUID, name = name}
end
end
end
end
-- Solo, always check.
local playerGUID = UnitGUID("player")
if playerGUID then
players[playerGUID] = true
local petGUID = UnitGUID("playerpet")
if petGUID and not pets[petGUID] then
local name = UnitName("player")
pets[petGUID] = {id = playerGUID, name = name}
end
end
end
-- Ask a mode to verify the contents of a set.
local function verify_set(mode, set)
if mode.AddSetAttributes ~= nil then
mode:AddSetAttributes(set)
end
for j, player in ipairs(set.players) do
if mode.AddPlayerAttributes ~= nil then
mode:AddPlayerAttributes(player, set)
end
end
end
local wasininstance
local wasinpvp
-- Are we in a PVP zone?
local pvp_zones = {}
local function IsInPVP()
local pvpType, isFFA = GetZonePVPInfo()
local _, instanceType = IsInInstance()
return instanceType == "pvp" or instanceType == "arena" or pvpType == "arena" or pvpType == "combat" or isFFA
end
function Skada:ZoneCheck()
-- Check if we are entering an instance.
local inInstance, instanceType = IsInInstance()
local isininstance = inInstance and (instanceType == "party" or instanceType == "raid")
local isinpvp = IsInPVP()
-- If we are entering an instance, and we were not previously in an instance, and we got this event before... and we have some data...
if isininstance and wasininstance ~= nil and not wasininstance and self.db.profile.reset.instance ~= 1 and Skada:CanReset() then
if self.db.profile.reset.instance == 3 then
Skada:ShowPopup()
else
self:Reset()
end
end
-- Hide in PvP. Hide if entering a PvP instance, show if we are leaving one.
if self.db.profile.hidepvp then
if IsInPVP() then
Skada:SetActive(false)
elseif wasinpvp then
Skada:SetActive(true)
end
end
-- Save a flag marking our previous (current) instance status.
if isininstance then
wasininstance = true
else
wasininstance = false
end
-- Save a flag marking out previous (current) pvp status.
if isinpvp then
wasinpvp = true
else
wasinpvp = false
end
end
-- Fired on entering a zone.
function Skada:ZONE_CHANGED_NEW_AREA()
Skada:ZoneCheck()
end
-- Fired on blue bar screen
function Skada:PLAYER_ENTERING_WORLD()
Skada:ZoneCheck() -- catch reloadui within a zone, which does not fire ZONE_CHANGED_NEW_AREA
-- If this event fired in response to a login or teleport, zone info is usually not yet available
-- and will be caught by a sunsequent ZONE_CHANGED_NEW_AREA
-- make sure we update once on reload
-- delay it because group is unavailable during first PLAYER_ENTERING_WORLD on login
if wasinparty == nil then Skada:ScheduleTimer("GROUP_ROSTER_UPDATE",1) end
end
-- Check if we join a party/raid.
local function check_for_join_and_leave()
if not IsInGroup() and wasinparty then
-- We left a party.
if Skada.db.profile.reset.leave == 3 and Skada:CanReset() then
Skada:ShowPopup()
elseif Skada.db.profile.reset.leave == 2 and Skada:CanReset() then
Skada:Reset()
end
-- Hide window if we have enabled the "Hide when solo" option.
if Skada.db.profile.hidesolo then
Skada:SetActive(false)
end
end
if IsInGroup() and wasinparty == false then -- if nil this is first check after reload/relog
-- We joined a raid.
if Skada.db.profile.reset.join == 3 and Skada:CanReset() then
Skada:ShowPopup()
elseif Skada.db.profile.reset.join == 2 and Skada:CanReset() then
Skada:Reset()
end
-- Show window if we have enabled the "Hide when solo" option.
-- But only when NOT in pvp if it's set to hide in pvp.
if Skada.db.profile.hidesolo and not (Skada.db.profile.hidepvp and IsInPVP()) then
Skada:SetActive(true)
end
end
-- Mark our last party status.
wasinparty = not not IsInGroup()
end
function Skada:GROUP_ROSTER_UPDATE()
check_for_join_and_leave()
-- Check for new pets.
self:CheckGroup()
end
function Skada:UNIT_PET()
-- Check for new pets.
self:CheckGroup()
end
function Skada:PET_BATTLE_OPENING_START()
-- Hide during pet battles
for i, win in ipairs(windows) do
if win:IsShown() then
win:Hide()
end
end
end
function Skada:PET_BATTLE_CLOSE()
-- Restore after pet battles
if not Skada.db.profile.hidesolo or IsInGroup() then
for i, win in ipairs(windows) do
if not win.db.hidden and not win:IsShown() then
win:Show()
end
end
end
end
-- Toggles all windows.
function Skada:ToggleWindow()
for i, win in ipairs(windows) do
if win:IsShown() then
win.db.hidden = true
win:Hide()
else
win.db.hidden = false
win:Show()
end
end
end
local function createSet(setname)
local set = {players = {}, name = setname, starttime = time(), ["time"] = 0, last_action = time()}
-- Tell each mode to apply its needed attributes.
for i, mode in ipairs(modes) do verify_set(mode, set) end
return set
end
function Skada:CanReset() -- returns true if we have actual data that can be cleared via :Reset()
local totalplayers = self.total and self.total.players
if totalplayers and next(totalplayers) then -- Total set contains data
return true
end
for _,set in ipairs(self.char.sets) do
if not set.keep then -- have a non-persistent set (possibly un-kept since last reset)
return true
end
end
return false
end
function Skada:Reset()
self:Wipe()
pets, players = {}, {}
self:CheckGroup()
if self.current ~= nil then
wipe(self.current)
self.current = createSet(L["Current"])
end
if self.total ~= nil then
wipe(self.total)
self.total = createSet(L["Total"])
self.char.total = self.total
end
self.last = nil
-- Delete sets that are not marked as persistent.
for i=table_maxn(self.char.sets), 1, -1 do
if not self.char.sets[i].keep then
wipe(tremove(self.char.sets, i))
end
end
-- Don't leave windows pointing to deleted sets
for _, win in ipairs(windows) do
if win.selectedset ~= "total" then
win.selectedset = "current"
win.changed = true
end
end
self:UpdateDisplay(true)
self:Print(L["All data has been reset."])
if not InCombatLockdown() then -- ticket 377: avoid timeout errors in combat because GC can run too long
collectgarbage("collect")
end
end
-- Delete a set.
function Skada:DeleteSet(set)
if not set then return end
for i, s in ipairs(self.char.sets) do
if s == set then
wipe(tremove(self.char.sets, i))
if set == self.last then
self.last = nil
end
-- Don't leave windows pointing to deleted sets
for _, win in ipairs(windows) do
if win.selectedset == i or win:get_selected_set() == set then
win.selectedset = "current"
win.changed = true
elseif (tonumber(win.selectedset) or 0) > i then
win.selectedset = win.selectedset - 1
win.changed = true
end
end
break
end
end
self:Wipe()
self:UpdateDisplay(true)
end
function Skada:ReloadSettings()
-- Delete all existing windows in case of a profile change.
for i, win in ipairs(windows) do
win:destroy()
end
windows = {}
-- Re-create windows
-- As this can be called from a profile change as well as login, re-use windows when possible.
for i, win in ipairs(self.db.profile.windows) do
self:CreateWindow(win.name, win)
end
self.total = self.char.total
Skada:ClearAllIndexes()
-- Minimap button.
if icon and not icon:IsRegistered("Skada") then
icon:Register("Skada", dataobj, self.db.profile.icon)
end
self:RefreshMMButton()
self:ApplySettings()
end
-- Applies settings to things like the bar window.
function Skada:ApplySettings()
for i, win in ipairs(windows) do
win.display:ApplySettings(win)
end
-- Don't show window if we are solo, option.
-- Don't show window in a PvP instance, option.
if (self.db.profile.hidesolo and not IsInGroup()) or (self.db.profile.hidepvp and IsInPVP())then
self:SetActive(false)
else
self:SetActive(true)
-- Hide specific windows if window is marked as hidden (ie, if user manually hid the window, keep hiding it).
for i, win in ipairs(windows) do
if win.db.hidden and win:IsShown() then
win:Hide()
end
end
end
self:UpdateDisplay(true)
end
-- Set a data feed as selectedfeed.
function Skada:SetFeed(feed)
selectedfeed = feed
self:UpdateDisplay()
end
-- Iterates over all players in a set and adds to the "time" variable
-- the time between first and last action.
local function setPlayerActiveTimes(set)
for i, player in ipairs(set.players) do
if player.last then
player.time = player.time + (player.last - player.first)
end
end
end
-- Starts a new segment, saving the current one first.
-- Does nothing if we are out of combat.
-- Useful for multi-part fights where you want individual segments for each part.
function Skada:NewSegment()
if self.current then
self:EndSegment()
self:StartCombat()
end
end
local function IsRaidInCombat()
local type, count = Skada:GetGroupTypeAndCount()
if count > 0 then
for i = 1, count, 1 do
if UnitExists(type..i) and UnitAffectingCombat(type..i) then
return true
end
end
elseif UnitAffectingCombat("player") then
return true
end
end
-- Returns true if the party/raid/us are dead/ghost.
local function IsRaidDead()
local type, count = Skada:GetGroupTypeAndCount()
if count > 0 then
for i = 1, count, 1 do
if UnitExists(type..i) and not UnitIsDeadOrGhost(type..i) then
return false
end
end
elseif not UnitIsDeadOrGhost("player") then
return false
end
return true
end
-- Our scheme for segmenting fights:
-- Each second, if player is not in combat and is not dead and we have an active set (current),
-- check if anyone in raid is in combat; if so, close up shop.
-- We can not simply rely on PLAYER_REGEN_ENABLED since it is fired if we die and the fight continues.
function Skada:Tick()
if not disabled and self.current and not InCombatLockdown() and not IsRaidInCombat() then
self:Debug("EndSegment: Tick")
self:EndSegment()
end
end
-- Stops the current segment immediately.
-- To not complicate things, this only stops processing of CLEU events and sets the segment end time.
-- A stopped segment can be resumed.
function Skada:StopSegment()
if self.current then
self.current.stopped = true
self.current.endtime = time()
self.current.time = self.current.endtime - self.current.starttime
end
end
-- Resumes a stopped segment.
function Skada:ResumeSegment()
if self.current and self.current.stopped then
self.current.stopped = nil
self.current.endtime = nil
self.current.time = nil
end
end
function Skada:EndSegment()
if not self.current then
return
end
-- Save current set unless this a trivial set, or if we have the Only keep boss fights options on, and no boss in fight.
-- A set is trivial if we have no mob name saved, or if total time for set is not more than 5 seconds.
if not self.db.profile.onlykeepbosses or self.current.gotboss then
if self.current.mobname ~= nil and time() - self.current.starttime > 5 then
-- End current set.
if not self.current.endtime then
self.current.endtime = time()
end
self.current.time = self.current.endtime - self.current.starttime
setPlayerActiveTimes(self.current)
self.current.stopped = nil
-- compute a count suffix for the set name
local setname = self.current.mobname
if self.db.profile.setnumber then
local max = 0
for _, set in ipairs(self.char.sets) do
if set.name == setname and max == 0 then
max = 1
else
local n,c = set.name:match("^(.-)%s*%((%d+)%)$")
if n == setname then max = math.max(max,tonumber(c) or 0) end
end
end
if max > 0 then
setname = setname .. " ("..(max+1)..")"
end
end
self.current.name = setname
-- Tell each mode that set has finished and do whatever it wants to do about it.
for i, mode in ipairs(modes) do
if mode.SetComplete ~= nil then
mode:SetComplete(self.current)
end
end
-- Add set to sets.
tinsert(self.char.sets, 1, self.current)
end
end
-- Make set last set.
self.last = self.current
-- Add time spent to total set as well.
self.total.time = self.total.time + self.current.time
setPlayerActiveTimes(self.total)
-- Set player.first and player.last to nil in total set.
-- Neccessary since first and last has no relevance over an entire raid.
-- Modes should look at the "time" value if available.
for i, player in ipairs(self.total.players) do
player.first = nil
player.last = nil
end
-- Reset current set.
self.current = nil
-- Find out number of non-persistent sets.
local numsets = 0
for i, set in ipairs(self.char.sets) do if not set.keep then numsets = numsets + 1 end end
-- Trim segments; don't touch persistent sets.
for i=table_maxn(self.char.sets), 1, -1 do
if numsets > self.db.profile.setstokeep and not self.char.sets[i].keep then
tremove(self.char.sets, i)
numsets = numsets - 1
end
end
for i, win in ipairs(windows) do
-- win:Wipe()
-- changed = true
-- Wipe mode - switch to current set and specific mode if no party/raid members are alive.
-- Restore mode is not changed.
if win.db.wipemode ~= "" and IsRaidDead() then
self:RestoreView(win, "current", win.db.wipemode)
elseif win.db.returnaftercombat and win.restore_mode and win.restore_set then
-- Auto-switch back to previous set/mode.
if win.restore_set ~= win.selectedset or win.restore_mode ~= win.selectedmode then
self:RestoreView(win, win.restore_set, win.restore_mode)
win.restore_mode = nil
win.restore_set = nil
end
end
-- Hide in combat option.
if not win.db.hidden and self.db.profile.hidecombat and (not self.db.profile.hidesolo or IsInGroup()) then
win:Show()
end
end
self:UpdateDisplay(true) -- force required to update displays looking at older sets after insertion
if update_timer then self:CancelTimer(update_timer) end
if tick_timer then self:CancelTimer(tick_timer) end
update_timer, tick_timer = nil, nil
end
function Skada:PLAYER_REGEN_DISABLED()
-- Start a new set if we are not in one already.
if not disabled and not self.current then
self:Debug("StartCombat: PLAYER_REGEN_DISABLED")
self:StartCombat()
end
end
-- This flag is used to mark a possible combat start.
-- It is a count of captured events.
-- When we hit our treshold (let's say 5), combat starts.
-- If we have not hit our treshold after a certain time (let's say 3 seconds) combat start failed.
local tentative = nil
-- AceTimer handle for reverting combat start.
local tentativehandle= nil
function Skada:StartCombat()
-- Reset automatic stop on wipe variables
deathcounter = 0
local _, members = self:GetGroupTypeAndCount()
startingmembers = members
-- Cancel cancelling combat if needed.
if tentativehandle ~= nil then
self:CancelTimer(tentativehandle)
tentativehandle = nil
end
if update_timer then
self:Debug("EndSegment: StartCombat")
self:EndSegment()
end
-- Remove old bars.
self:Wipe()
-- Create a new current set unless we are already have one (combat detection kicked in).
if not self.current then
self.current = createSet(L["Current"])
end
if self.encounterName and
GetTime() < (self.encounterTime or 0) + 15 then -- a recent ENCOUNTER_START named our segment
self:Debug("StartCombat setting encounterName from ENCOUNTER_START",self.encounterName)
self.current.mobname = self.encounterName
self.current.gotboss = true
self.encounterName = nil
self.encounterTime = nil
end
-- Also start the total set if it is nil.
if self.total == nil then
self.total = createSet(L["Total"])
self.char.total = self.total
end
-- Auto-switch set/mode if configured.
for i, win in ipairs(windows) do
if win.db.modeincombat ~= "" then
-- First, get the mode. The mode may not actually be available.
local mymode = find_mode(win.db.modeincombat)
-- If the mode exists, switch to current set and this mode. Save current set/mode so we can return after combat if configured.
if mymode ~= nil then
-- self:Print("Switching to "..mymode.name.." mode.")
if win.db.returnaftercombat then
if win.selectedset then
win.restore_set = win.selectedset
end
if win.selectedmode then
win.restore_mode = win.selectedmode:GetName()
end
end
win.selectedset = "current"
win:DisplayMode(mymode)
end
end
-- Hide in combat option.
if not win.db.hidden and self.db.profile.hidecombat then
win:Hide()
end
end
-- Force immediate update.
self:UpdateDisplay(true)
-- Schedule timers for updating windows and detecting combat end.
update_timer = self:ScheduleRepeatingTimer("UpdateDisplay", self.db.profile.updatefrequency or 0.25)
-- ticket 363: It is NOT safe to use ENCOUNTER_END to replace combat detection
tick_timer = self:ScheduleRepeatingTimer("Tick", 1)
end
-- Simply calls the same function on all windows.
function Skada:Wipe()
for i, win in ipairs(windows) do
win:Wipe()
end
end
-- Attempts to restore a view (set and mode).
-- Set is either the set name ("total", "current"), or an index.
-- Mode is the name of a mode.
function Skada:RestoreView(win, theset, themode)
-- Set the... set. If no such set exists, set to current.
if theset and type(theset) == "string" and (theset == "current" or theset == "total" or theset == "last") then
win.selectedset = theset
elseif theset and type(theset) == "number" and theset <= table_maxn(self.char.sets) then
win.selectedset = theset
else
win.selectedset = "current"
end
-- Force an update.
changed = true
-- Find the mode. The mode may not actually be available.
if themode then
local mymode = find_mode(themode)
-- If the mode exists, switch to this mode.
-- If not, show modes.
if mymode then
win:DisplayMode(mymode)
else
win:DisplayModes(win.selectedset)
end
else
win:DisplayModes(win.selectedset)
end
end
-- If set is "current", returns current set if we are in combat, otherwise returns the last set.
function Skada:find_set(s)
if s == "current" then
if Skada.current ~= nil then
return Skada.current
elseif Skada.last ~= nil then
return Skada.last
else
return self.char.sets[1]
end
elseif s == "total" then
return Skada.total
else
return self.char.sets[s]
end
end
function Skada:ClearIndexes(set)
if set then
set._playeridx = nil
end
end
function Skada:ClearAllIndexes()
-- clear indexes used for accelerating set lookups
-- this is done on login/logout to prevent the in-memory aliasing from becoming redundant tables on reload
Skada:ClearIndexes(self.current)
Skada:ClearIndexes(self.char.total)
for _,set in pairs(self.char.sets) do
Skada:ClearIndexes(set)
end
end
-- Returns a player from the current. Safe to use to simply view a player without creating an entry.
function Skada:find_player(set, playerid)
if set then
-- use a private index here for more efficient lookup
-- may eventually want to re-key .players by id but that would break external mods
set._playeridx = set._playeridx or {}
local player = set._playeridx[playerid]
if player then return player end
for i, p in ipairs(set.players) do
if p.id == playerid then
set._playeridx[playerid] = p
return p
end
end
end
end
-- Returns or creates a player in the current.
function Skada:get_player(set, playerid, playername)
-- Add player to set if it does not exist.
local player = Skada:find_player(set, playerid)
if not player then
-- If we do not supply a playername (often the case in submodes), we can not create an entry.
if not playername then
return
end
local _, playerClass = UnitClass(playername)
local playerRole = UnitGroupRolesAssigned(playername)
player = {id = playerid, class = playerClass, role = playerRole, name = playername, first = time(), ["time"] = 0}
-- Tell each mode to apply its needed attributes.
for i, mode in ipairs(modes) do
if mode.AddPlayerAttributes ~= nil then
mode:AddPlayerAttributes(player, set)
end
end
-- Strip realm name
-- This is done after module processing due to cross-realm names messing with modules (death log for example, which needs to do UnitHealthMax on the playername).
local player_name, realm = string.split("-", playername, 2)
player.name = player_name or playername
tinsert(set.players, player)
end
if player.name == UNKNOWN and playername ~= UNKNOWN then -- fixup players created before we had their info
local player_name, realm = string.split("-", playername, 2)
player.name = player_name or playername
local _, playerClass = UnitClass(playername)
local playerRole = UnitGroupRolesAssigned(playername)
player.class = playerClass
player.role = playerRole
end
-- The total set clears out first and last timestamps.
if not player.first then
player.first = time()
end
-- Mark now as the last time player did something worthwhile.
player.last = time()
changed = true
return player
end
local combatlogevents = {}
function Skada:RegisterForCL(func, event, flags)
if not combatlogevents[event] then
combatlogevents[event] = {}
end
tinsert(combatlogevents[event], {["func"] = func, ["flags"] = flags})
end
local band = bit.band
local PET_FLAGS = bit.bor(COMBATLOG_OBJECT_TYPE_PET, COMBATLOG_OBJECT_TYPE_GUARDIAN)
local RAID_FLAGS = bit.bor(COMBATLOG_OBJECT_AFFILIATION_MINE, COMBATLOG_OBJECT_AFFILIATION_PARTY, COMBATLOG_OBJECT_AFFILIATION_RAID)
-- The basic idea for CL processing:
-- Modules register for interest in a certain event, along with the function to call and the flags determining if the particular event is interesting.
-- On a new event, loop through the interested parties.
-- The flags are checked, and the flag value (say, that the SRC must be interesting, ie, one of the raid) is only checked once, regardless
-- of how many modules are interested in the event. The check is also only done on the first flag that requires it.
cleuFrame = CreateFrame("Frame") -- Dedicated event handler for a small performance improvement.
Skada.cleuFrame = cleuFrame -- For tweaks
cleuFrame:SetScript("OnEvent", function(frame, event, timestamp, eventtype, hideCaster, srcGUID, srcName, srcFlags, srcRaidFlags, dstGUID, dstName, dstFlags, dstRaidFlags, ...)
local src_is_interesting = nil
local dst_is_interesting = nil
-- Optional tentative combat detection.
-- Instead of simply checking when we enter combat, combat start is also detected based on needing a certain
-- amount of interesting (as defined by our modules) CL events.
if not Skada.current and Skada.db.profile.tentativecombatstart and srcName and dstName and srcGUID ~= dstGUID and (eventtype == 'SPELL_DAMAGE' or eventtype == 'SPELL_BUILDING_DAMAGE' or eventtype == 'RANGE_DAMAGE' or eventtype == 'SWING_DAMAGE' or eventtype == 'SPELL_PERIODIC_DAMAGE') then
src_is_interesting = band(srcFlags, RAID_FLAGS) ~= 0 or (band(srcFlags, PET_FLAGS) ~= 0 and pets[srcGUID]) or players[srcGUID]
-- AWS: To avoid incoming periodic damage (e.g. from a debuff) triggering combat, we simply do not initialize
-- dst_is_interesting for periodic damage...
if eventtype ~= 'SPELL_PERIODIC_DAMAGE' then
dst_is_interesting = band(dstFlags, RAID_FLAGS) ~= 0 or (band(dstFlags, PET_FLAGS) ~= 0 and pets[dstGUID]) or players[dstGUID]
end
if src_is_interesting or dst_is_interesting then
-- Create a current set and set our "tentative" flag to true.
Skada.current = createSet(L["Current"])
-- Also create total set if needed.
if not Skada.total then
Skada.total = createSet(L["Total"])
end
-- Schedule an end to this tentative combat situation in 3 seconds.
tentativehandle = Skada:ScheduleTimer(
function()
tentative = nil
tentativehandle = nil
Skada.current = nil
--self:Print("tentative combat start FAILED!")
end, 1)
tentative = 0
--self:Print("tentative combat start INIT!")
end
end
-- Stop automatically on wipe to discount meaningless data.
if Skada.current and Skada.db.profile.autostop then
-- Add to death counter when a player dies.
if Skada.current and eventtype == 'UNIT_DIED' and ((band(srcFlags, RAID_FLAGS) ~= 0 and band(srcFlags, PET_FLAGS) == 0) or players[srcGUID]) then
deathcounter = deathcounter + 1
-- If we reached the treshold for stopping the segment, do so.
if deathcounter > 0 and deathcounter / startingmembers >= 0.5 and not Skada.current.stopped then
Skada:Print('Stopping for wipe.')
Skada:StopSegment()
end
end
-- Subtract from death counter when a player is ressurected.
if Skada.current and eventtype == 'SPELL_RESURRECT' and ((band(srcFlags, RAID_FLAGS) ~= 0 and band(srcFlags, PET_FLAGS) == 0) or players[srcGUID]) then
deathcounter = deathcounter - 1
end
end
if Skada.current and combatlogevents[eventtype] then
-- If segment is stopped, stop processing here.
if Skada.current.stopped then
return
end
for i, mod in ipairs(combatlogevents[eventtype]) do
local fail = false
if mod.flags.src_is_interesting_nopets then
local src_is_interesting_nopets = (band(srcFlags, RAID_FLAGS) ~= 0 and band(srcFlags, PET_FLAGS) == 0) or players[srcGUID]
if src_is_interesting_nopets then
src_is_interesting = true
else
--self:Print("fail on src_is_interesting_nopets")
fail = true
end
end
if not fail and mod.flags.dst_is_interesting_nopets then
local dst_is_interesting_nopets = (band(dstFlags, RAID_FLAGS) ~= 0 and band(dstFlags, PET_FLAGS) == 0) or players[dstGUID]
if dst_is_interesting_nopets then
dst_is_interesting = true
else
--self:Print("fail on dst_is_interesting_nopets")
fail = true
end
end
if not fail and mod.flags.src_is_interesting or mod.flags.src_is_not_interesting then
if not src_is_interesting then
src_is_interesting = band(srcFlags, RAID_FLAGS) ~= 0 or (band(srcFlags, PET_FLAGS) ~= 0 and pets[srcGUID]) or players[srcGUID]
end
if mod.flags.src_is_interesting and not src_is_interesting then
--self:Print("fail on src_is_interesting")
fail = true
end
if mod.flags.src_is_not_interesting and src_is_interesting then
fail = true
end
end
if not fail and mod.flags.dst_is_interesting or mod.flags.dst_is_not_interesting then
if not dst_is_interesting then
dst_is_interesting = band(dstFlags, RAID_FLAGS) ~= 0 or (band(dstFlags, PET_FLAGS) ~= 0 and pets[dstGUID]) or players[dstGUID]
end
if mod.flags.dst_is_interesting and not dst_is_interesting then
--self:Print("fail on dst_is_interesting")
fail = true
end
if mod.flags.dst_is_not_interesting and dst_is_interesting then
fail = true
end
end
-- Pass along event if it did not fail our tests.
if not fail then
mod.func(timestamp, eventtype, srcGUID, srcName, srcFlags, dstGUID, dstName, dstFlags, ...)
-- If our "tentative" flag is set and reached the treshold, this means combat really did start.
if tentative ~= nil then
tentative = tentative + 1
if tentative == 5 then
Skada:CancelTimer(tentativehandle)
tentativehandle = nil
Skada:Debug("StartCombat: tentative combat")
Skada:StartCombat()
end
end
end
end
end
-- Note: relies on src_is_interesting having been checked.
if Skada.current and src_is_interesting and not Skada.current.gotboss then
-- Store mob name for set name. For now, just save first unfriendly name available, or first boss available.
if bit.band(dstFlags, COMBATLOG_OBJECT_REACTION_FRIENDLY) == 0 then
if not Skada.current.gotboss and boss.BossIDs[tonumber(dstGUID:sub(-16, -12))] then
Skada.current.mobname = dstName
Skada.current.gotboss = true
elseif not Skada.current.mobname then
Skada.current.mobname = dstName
end
end
end
-- Pet summons.
-- Pet scheme: save the GUID in a table along with the GUID of the owner.
-- Note to self: this needs 1) to be made self-cleaning so it can't grow too much, and 2) saved persistently.
-- Now also done on raid roster/party changes.
if eventtype == 'SPELL_SUMMON' and ( (band(srcFlags, RAID_FLAGS) ~= 0) or ( (band(srcFlags, PET_FLAGS)) ~= 0 ) or ((band(dstFlags, PET_FLAGS) ~= 0) and pets[dstGUID])) then
-- assign pet normally
pets[dstGUID] = {id = srcGUID, name = srcName}
if pets[srcGUID] then
-- the pets owner is a pet -> change it to the owner of the pet
-- this check may no longer be necessary?
pets[dstGUID].id = pets[srcGUID].id
pets[dstGUID].name = pets[srcGUID].name
end
end
end)
function Skada:AssignPet(ownerguid, ownername, petguid)
pets[petguid] = {id = ownerguid, name = ownername}
end
function Skada:ENCOUNTER_START(encounterId, encounterName)
self:Debug("ENCOUNTER_START", encounterId, encounterName)
if not disabled then
if self.current then -- already in combat, update the segment name
self.current.mobname = encounterName
self.current.gotboss = true
else -- we are not in combat yet
-- if we StartCombat here, the segment will immediately end by Tick
-- just save the encounter name for use when we enter combat
self.encounterName = encounterName
self.encounterTime = GetTime()
end
end
end
function Skada:ENCOUNTER_END(encounterId, encounterName)
self:Debug("ENCOUNTER_END", encounterId, encounterName)
if not disabled and self.current then
-- ticket 363: it is NOT safe to EndSegment here
if not self.current.gotboss then -- might have missed the bossname (eg d/c in combat)
self.current.mobname = encounterName
self.current.gotboss = true
end
end
end
--
-- Data broker
--
function dataobj:OnEnter()
GameTooltip:SetOwner(self, "ANCHOR_NONE")
GameTooltip:SetPoint("TOPLEFT", self, "BOTTOMLEFT")
GameTooltip:ClearLines()
local set
if Skada.current then
set = Skada.current
else
set = Skada.char.sets[1]
end
if set then
GameTooltip:AddLine(L["Skada summary"], 0, 1, 0)
for i, mode in ipairs(modes) do
if mode.AddToTooltip ~= nil then
mode:AddToTooltip(set, GameTooltip)
end
end
end
GameTooltip:AddLine(L["Hint: Left-Click to toggle Skada window."], 0, 1, 0)
GameTooltip:AddLine(L["Shift + Left-Click to reset."], 0, 1, 0)
GameTooltip:AddLine(L["Right-click to open menu"], 0, 1, 0)
GameTooltip:Show()
end
function dataobj:OnLeave()
GameTooltip:Hide()
end
function dataobj:OnClick(button)
if button == "LeftButton" and IsShiftKeyDown() then
Skada:Reset()
elseif button == "LeftButton" then
Skada:ToggleWindow()
elseif button == "RightButton" then
Skada:OpenMenu()
end
end
local totalbarcolor = {r = 0.2, g = 0.2, b = 0.5, a = 1}
local bossicon = "Interface\\Icons\\Achievment_boss_ultraxion"
local nonbossicon = "Interface\\Icons\\icon_petfamily_critter"
function Skada:UpdateDisplay(force)
-- Force an update by setting our "changed" flag to true.
if force then
changed = true
end
-- Update data feed.
-- This is done even if our set has not changed, since for example DPS changes even though the data does not.
-- Does not update feed text if nil.
if selectedfeed ~= nil then
local feedtext = selectedfeed()
if feedtext then
dataobj.text = feedtext
end
end
for i, win in ipairs(windows) do
if (changed or win.changed or self.current) then
win.changed = false
if win.selectedmode then -- Force mode display for display systems which do not handle navigation.
local set = win:get_selected_set()
if set then
-- Inform window that a data update will take place.
win:UpdateInProgress()
-- Let mode update data.
if win.selectedmode.Update then
win.selectedmode:Update(win, set)
else
self:Print("Mode "..win.selectedmode:GetName().." does not have an Update function!")
end
-- Add a total bar using the mode summaries optionally.
if self.db.profile.showtotals and win.selectedmode.GetSetSummary then
local total = 0
local existing = nil
for i, data in ipairs(win.dataset) do
if data.id then
total = total + data.value
end
if not existing and not data.id then
existing = data
end
end
total = total + 1
local d = existing or {}
d.valuetext = win.selectedmode:GetSetSummary(set)
d.value = total
d.label = L["Total"]
d.icon = dataobj.icon
d.id = "total"
d.ignore = true
if not existing then
tinsert(win.dataset, 1, d)
end
end
end
-- Let window display the data.
win:UpdateDisplay()
elseif win.selectedset then
local set = win:get_selected_set()
-- View available modes.
for i, mode in ipairs(modes) do
local d = win.dataset[i] or {}
win.dataset[i] = d
d.id = mode:GetName()
d.label = mode:GetName()
d.value = 1
if set and mode.GetSetSummary ~= nil then
d.valuetext = mode:GetSetSummary(set)
end
if mode.metadata and mode.metadata.icon then
d.icon = mode.metadata.icon
end
end
-- Tell window to sort by our data order. Our modes are in the correct order already.
win.metadata.ordersort = true
-- Let display provider/tooltip know we are showing a mode list.
if set then
win.metadata.is_modelist = true
end
-- Let window display the data.
win:UpdateDisplay()
else
-- View available sets.
local nr = 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = "total"
d.label = L["Total"]
d.value = 1
if self.total and self.total.gotboss then
d.icon = bossicon
else
d.icon = nonbossicon
end
nr = nr + 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = "current"
d.label = L["Current"]
d.value = 1
if self.current and self.current.gotboss then
d.icon = bossicon
else
d.icon = nonbossicon
end
for i, set in ipairs(self.char.sets) do
nr = nr + 1
local d = win.dataset[nr] or {}
win.dataset[nr] = d
d.id = tostring(set.starttime)
d.label, d.valuetext = select(2,Skada:GetSetLabel(set))
d.value = 1
if set.keep then
d.emphathize = true
end
if set.gotboss then
d.icon = bossicon
else
d.icon = nonbossicon
end
end
win.metadata.ordersort = true
-- Let window display the data.
win:UpdateDisplay()
end
end
end
-- Mark as unchanged.
changed = false
end
--[[
API
Everything below this is OK to use in modes.
--]]
function Skada:GetSets()
return self.char.sets
end
function Skada:GetModes(sortfunc)
return modes
end
-- Formats a number into human readable form.
function Skada:FormatNumber(number)
if number then
if self.db.profile.numberformat == 1 then
if number > 1000000000 then
return ("%02.3fB"):format(number / 1000000000)
elseif number > 1000000 then
return ("%02.2fM"):format(number / 1000000)
else
return ("%02.1fK"):format(number / 1000)
end
else
return math.floor(number)
end
end
end
local function scan_for_columns(mode)
-- Only process if not already scanned.
if not mode.scanned then
mode.scanned = true
-- Add options for this mode if available.
if mode.metadata and mode.metadata.columns then
Skada:AddColumnOptions(mode)
end
-- Scan any linked modes.
if mode.metadata then
if mode.metadata.click1 then
scan_for_columns(mode.metadata.click1)
end
if mode.metadata.click2 then
scan_for_columns(mode.metadata.click2)
end
if mode.metadata.click3 then
scan_for_columns(mode.metadata.click3)
end
end
end
end
-- Register a display system
local numorder = 5
function Skada:AddDisplaySystem(key, mod)
self.displays[key] = mod
if mod.description then
Skada.options.args.windows.args[key.."desc"] = {
type = "description",
name = mod.description,
order = numorder
}
numorder = numorder + 1
end
end
-- Register a mode.
function Skada:AddMode(mode, category)
-- Ask mode to verify our sets.
-- Needed in case we enable a mode and we have old data.
if self.total then
verify_set(mode, self.total)
end
if self.current then
verify_set(mode, self.current)
end
for i, set in ipairs(self.char.sets) do
verify_set(mode, set)
end
-- Set mode category (used for menus)
mode.category = category or L['Other']
-- Add to mode list
tinsert(modes, mode)
-- Set this mode as the active mode if it matches the saved one.
-- Bit of a hack.
for i, win in ipairs(windows) do
if mode:GetName() == win.db.mode then
self:RestoreView(win, win.db.set, mode:GetName())
end
end
-- Find if we now have our chosen feed.
-- Also a bit ugly.
if selectedfeed == nil and self.db.profile.feed ~= "" then
for name, feed in pairs(feeds) do
if name == self.db.profile.feed then
self:SetFeed(feed)
end
end
end
-- Add column configuration if available.
if mode.metadata then
scan_for_columns(mode)
end
-- Sort modes.
sort_modes()
-- Remove all bars and start over to get ordering right.
-- Yes, this all sucks - the problem with this and the above is that I don't know when
-- all modules are loaded. :/
for i, win in ipairs(windows) do
win:Wipe()
end
changed = true
end
-- Unregister a mode.
function Skada:RemoveMode(mode)
tremove(modes, mode)
end
function Skada:GetFeeds()
return feeds
end
-- Register a data feed.
function Skada:AddFeed(name, func)
feeds[name] = func
end
-- Unregister a data feed.
function Skada:RemoveFeed(name, func)
for i, feed in ipairs(feeds) do
if feed.name == name then
tremove(feeds, i)
end
end
end
--[[
Sets
--]]
function Skada:GetSetTime(set)
if set.time then
return set.time
else
return (time() - set.starttime)
end
end
-- Returns the time (in seconds) a player has been active for a set.
function Skada:PlayerActiveTime(set, player)
local maxtime = 0
-- Add recorded time (for total set)
if player.time > 0 then
maxtime = player.time
end
-- Add in-progress time if set is not ended.
if (not set.endtime or set.stopped) and player.first then
maxtime = maxtime + player.last - player.first
end
return maxtime
end
-- Modify objects if they are pets.
-- Expects to find "playerid", "playername", and optionally "spellname" in the object.
-- Playerid and playername are exchanged for the pet owner's, and spellname is modified to include pet name.
function Skada:FixPets(action)
if action and action.playername then
local pet = pets[action.playerid]
if pet then
if (self.db.profile.mergepets) then
if action.spellname then
action.spellname = action.playername..": "..action.spellname
end
action.playername = pet.name
action.playerid = pet.id
else
action.playername = pet.name..": "..action.playername
-- create a unique ID for each player for each type of pet
local petMobID=action.playerid:sub(6,10); -- Get Pet creature ID
action.playerid = pet.id .. petMobID; -- just append it to the pets owner id
end
else
-- Fix for guardians; requires "playerflags" to be set from CL.
-- This only works for one self. Other player's guardians are all lumped into one.
if action.playerflags and bit.band(action.playerflags, COMBATLOG_OBJECT_TYPE_GUARDIAN) ~= 0 then
if bit.band(action.playerflags, COMBATLOG_OBJECT_AFFILIATION_MINE) ~=0 then
if action.spellname then
action.spellname = action.playername..": "..action.spellname
end
action.playername = UnitName("player")
action.playerid = UnitGUID("player")
else
-- Nothing decent in place here yet. Modify guid so that there will only be 1 similar entry at least.
action.playerid = action.playername
end
end
end
end
end
function Skada:SetTooltipPosition(tooltip, frame)
local p = self.db.profile.tooltippos
if p == "default" then
tooltip:SetOwner(UIParent, "ANCHOR_NONE")
tooltip:SetPoint("BOTTOMRIGHT", "UIParent", "BOTTOMRIGHT", -40, 40);
elseif p == "topleft" then
tooltip:SetOwner(frame, "ANCHOR_NONE")
tooltip:SetPoint("TOPRIGHT", frame, "TOPLEFT")
elseif p == "topright" then
tooltip:SetOwner(frame, "ANCHOR_NONE")
tooltip:SetPoint("TOPLEFT", frame, "TOPRIGHT")
elseif p == "smart" and frame then
-- Choose anchor point depending on frame position
if frame:GetLeft() < (GetScreenWidth() / 2) then
tooltip:SetOwner(frame, "ANCHOR_NONE")
tooltip:SetPoint("TOPLEFT", frame, "TOPRIGHT", 10, 0)
else
tooltip:SetOwner(frame, "ANCHOR_NONE")
tooltip:SetPoint("TOPRIGHT", frame, "TOPLEFT", -10, 0)
end
end
end
-- Same thing, only takes two arguments and returns two arguments.
function Skada:FixMyPets(playerGUID, playerName)
local pet = pets[playerGUID]
if pet then
return pet.id, pet.name
end
-- No pet match - return the player.
return playerGUID, playerName
end
-- Format value text in a standardized way. Up to 3 value and boolean (show/don't show) combinations are accepted.
-- Values are rendered from left to right.
-- Idea: "compile" a function on the fly instead and store in mode for re-use.
function Skada:FormatValueText(...)
local value1, bool1, value2, bool2, value3, bool3 = ...
-- This construction is a little silly.
if bool1 and bool2 and bool3 then
return value1.." ("..value2..", "..value3..")"
elseif bool1 and bool2 then
return value1.." ("..value2..")"
elseif bool1 and bool3 then
return value1.." ("..value3..")"
elseif bool2 and bool3 then
return value2.." ("..value3..")"
elseif bool2 then
return value2
elseif bool1 then
return value1
elseif bool3 then
return value3
end
end
local function value_sort(a,b)
if not a or a.value == nil then
return false
elseif not b or b.value == nil then
return true
else
return a.value > b.value
end
end
function Skada.valueid_sort(a,b)
if not a or a.value == nil or a.id == nil then
return false
elseif not b or b.value == nil or b.id == nil then
return true
else
return a.value > b.value
end
end
-- Tooltip display. Shows subview data for a specific row.
-- Using a fake window, the subviews are asked to populate the window's dataset normally.
local ttwin = Window:new()
local white = {r = 1, g = 1, b = 1}
function Skada:AddSubviewToTooltip(tooltip, win, mode, id, label)
-- Clean dataset.
wipe(ttwin.dataset)
-- Tell mode we are entering our real window.
if mode.Enter then
mode:Enter(win, id, label)
end
-- Ask mode to populate dataset in our fake window.
mode:Update(ttwin, win:get_selected_set())
-- Sort dataset unless we are using ordersort.
if not mode.metadata or not mode.metadata.ordersort then
table_sort(ttwin.dataset, value_sort)
end
-- Show title and data if we have data.
if #ttwin.dataset > 0 then
tooltip:AddLine(mode.title or mode:GetName(), 1,1,1)
-- Display the top X, default 3, rows.
local nr = 0
for i, data in ipairs(ttwin.dataset) do
if data.id and nr < Skada.db.profile.tooltiprows then
nr = nr + 1
local color = white
if data.color then
-- Explicit color from dataset.
color = data.color
elseif data.class then
-- Class color.
local color = Skada.classcolors[data.class]
end
local label = data.label
if mode.metadata and mode.metadata.showspots then
label = nr..". "..label
end
tooltip:AddDoubleLine(label, data.valuetext, color.r, color.g, color.b)
end
end
-- Add an empty line.
if mode.Enter then
tooltip:AddLine(" ")
end
end
end
-- Generic tooltip function for displays
function Skada:ShowTooltip(win, id, label)
local t = GameTooltip
if Skada.db.profile.tooltips then
if win.metadata.is_modelist and Skada.db.profile.informativetooltips then
t:ClearLines()
Skada:AddSubviewToTooltip(t, win, find_mode(id), id, label)
t:Show()
elseif win.metadata.click1 or win.metadata.click2 or win.metadata.click3 or win.metadata.tooltip then
t:ClearLines()
local hasClick = win.metadata.click1 or win.metadata.click2 or win.metadata.click3
-- Current mode's own tooltips.
if win.metadata.tooltip then
local numLines = t:NumLines()
win.metadata.tooltip(win, id, label, t)
-- Spacer
if t:NumLines() ~= numLines and hasClick then
t:AddLine(" ")
end
end
-- Generic informative tooltips.
if Skada.db.profile.informativetooltips then
if win.metadata.click1 then
Skada:AddSubviewToTooltip(t, win, win.metadata.click1, id, label)
end
if win.metadata.click2 then
Skada:AddSubviewToTooltip(t, win, win.metadata.click2, id, label)
end
if win.metadata.click3 then
Skada:AddSubviewToTooltip(t, win, win.metadata.click3, id, label)
end
end
-- Current mode's own post-tooltips.
if win.metadata.post_tooltip then
local numLines = t:NumLines()
win.metadata.post_tooltip(win, id, label, t)
-- Spacer
if t:NumLines() ~= numLines and hasClick then
t:AddLine(" ")
end
end
-- Click directions.
if win.metadata.click1 then
t:AddLine(L["Click for"].." "..win.metadata.click1:GetName()..".", 0.2, 1, 0.2)
end
if win.metadata.click2 then
t:AddLine(L["Shift-Click for"].." "..win.metadata.click2:GetName()..".", 0.2, 1, 0.2)
end
if win.metadata.click3 then
t:AddLine(L["Control-Click for"].." "..win.metadata.click3:GetName()..".", 0.2, 1, 0.2)
end
t:Show()
end
end
end
-- Generic border
function Skada:ApplyBorder(frame, texture, color, thickness, padtop, padbottom, padleft, padright)
local borderbackdrop = {}
if not frame.borderFrame then
frame.borderFrame = CreateFrame("Frame", nil, frame)
frame.borderFrame:SetFrameLevel(0)
end
frame.borderFrame:SetPoint("TOPLEFT", frame, -thickness - (padleft or 0), thickness + (padtop or 0))
frame.borderFrame:SetPoint("BOTTOMRIGHT", frame, thickness + (padright or 0), -thickness - (padbottom or 0))
if texture and thickness > 0 then
borderbackdrop.edgeFile = media:Fetch("border", texture)
else
borderbackdrop.edgeFile = nil
end
borderbackdrop.edgeSize = thickness
frame.borderFrame:SetBackdrop(borderbackdrop)
if color then
frame.borderFrame:SetBackdropBorderColor(color.r, color.g, color.b, color.a)
end
end
-- Generic frame settings
function Skada:FrameSettings(db, include_dimensions)
local obj = {
type = "group",
name = L["Window"],
order=2,
args = {
bgheader = {
type = "header",
name = L["Background"],
order=1
},
texture = {
type = 'select',
dialogControl = 'LSM30_Background',
name = L["Background texture"],
desc = L["The texture used as the background."],
values = AceGUIWidgetLSMlists.background,
get = function() return db.background.texture end,
set = function(win,key)
db.background.texture = key
Skada:ApplySettings()
end,
width="double",
order=1.1
},
tile = {
type = 'toggle',
name = L["Tile"],
desc = L["Tile the background texture."],
get = function() return db.background.tile end,
set = function(win,key)
db.background.tile = key
Skada:ApplySettings()
end,
order=1.2
},
tilesize = {
type="range",
name=L["Tile size"],
desc=L["The size of the texture pattern."],
min=0,
max=math.floor(GetScreenWidth()),
step=1.0,
get=function() return db.background.tilesize end,
set=function(win, val)
db.background.tilesize = val
Skada:ApplySettings()
end,
order=1.3
},
color = {
type="color",
name=L["Background color"],
desc=L["The color of the background."],
hasAlpha=true,
get=function(i)
local c = db.background.color
return c.r, c.g, c.b, c.a
end,
set=function(i, r,g,b,a)
db.background.color = {["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a}
Skada:ApplySettings()
end,
order=1.4
},
borderheader = {
type = "header",
name = L["Border"],
order=2
},
bordertexture = {
type = 'select',
dialogControl = 'LSM30_Border',
name = L["Border texture"],
desc = L["The texture used for the borders."],
values = AceGUIWidgetLSMlists.border,
get = function() return db.background.bordertexture end,
set = function(win,key)
db.background.bordertexture = key
Skada:ApplySettings()
end,
width="double",
order=2.1
},
bordercolor = {
type = 'color',
order=5,
name = L["Border color"],
desc = L["The color used for the border."],
hasAlpha=true,
get=function(i)
local c = db.background.bordercolor or {r=0,g=0,b=0,a=1}
return c.r, c.g, c.b, c.a
end,
set=function(i, r,g,b,a)
db.background.bordercolor = {["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a}
Skada:ApplySettings()
end,
order=2.2
},
thickness = {
type="range",
name=L["Border thickness"],
desc=L["The thickness of the borders."],
min=0,
max=50,
step=0.5,
get=function() return db.background.borderthickness end,
set=function(win, val)
db.background.borderthickness = val
Skada:ApplySettings()
end,
order=2.3
},
optionheader = {
type = "header",
name = L["General"],
order=4
},
scale = {
type="range",
name=L["Scale"],
desc=L["Sets the scale of the window."],
min=0.1,
max=3,
step=0.01,
get=function() return db.scale end,
set=function(win, val)
db.scale = val
Skada:ApplySettings()
end,
order=4.1
},
strata = {
type="select",
name=L["Strata"],
desc=L["This determines what other frames will be in front of the frame."],
values = {["BACKGROUND"]="BACKGROUND", ["LOW"]="LOW", ["MEDIUM"]="MEDIUM", ["HIGH"]="HIGH", ["DIALOG"]="DIALOG", ["FULLSCREEN"]="FULLSCREEN", ["FULLSCREEN_DIALOG"]="FULLSCREEN_DIALOG"},
get=function() return db.strata end,
set=function(win, val)
db.strata = val
Skada:ApplySettings()
end,
order=4.2
},
}
}
if include_dimensions then
obj.args.width = {
type = 'range',
name = L["Width"],
min=100,
max=GetScreenWidth(),
step=1.0,
get = function() return db.width end,
set = function(win,key)
db.width = key
Skada:ApplySettings()
end,
order=4.3
}
obj.args.height = {
type = 'range',
name = L["Height"],
min=16,
max=400,
step=1.0,
get = function() return db.height end,
set = function(win,key)
db.height = key
Skada:ApplySettings()
end,
order=4.4
}
end
return obj
end
do
function Skada:OnInitialize()
-- Register some SharedMedia goodies.
media:Register("font", "Adventure", [[Interface\Addons\Skada\media\fonts\Adventure.ttf]])
media:Register("font", "ABF", [[Interface\Addons\Skada\media\fonts\ABF.ttf]])
media:Register("font", "Vera Serif", [[Interface\Addons\Skada\media\fonts\VeraSe.ttf]])
media:Register("font", "Diablo", [[Interface\Addons\Skada\media\fonts\Avqest.ttf]])
media:Register("font", "Accidental Presidency", [[Interface\Addons\Skada\media\fonts\Accidental Presidency.ttf]])
media:Register("statusbar", "Aluminium", [[Interface\Addons\Skada\media\statusbar\Aluminium]])
media:Register("statusbar", "Armory", [[Interface\Addons\Skada\media\statusbar\Armory]])
media:Register("statusbar", "BantoBar", [[Interface\Addons\Skada\media\statusbar\BantoBar]])
media:Register("statusbar", "Glaze2", [[Interface\Addons\Skada\media\statusbar\Glaze2]])
media:Register("statusbar", "Gloss", [[Interface\Addons\Skada\media\statusbar\Gloss]])
media:Register("statusbar", "Graphite", [[Interface\Addons\Skada\media\statusbar\Graphite]])
media:Register("statusbar", "Grid", [[Interface\Addons\Skada\media\statusbar\Grid]])
media:Register("statusbar", "Healbot", [[Interface\Addons\Skada\media\statusbar\Healbot]])
media:Register("statusbar", "LiteStep", [[Interface\Addons\Skada\media\statusbar\LiteStep]])
media:Register("statusbar", "Minimalist", [[Interface\Addons\Skada\media\statusbar\Minimalist]])
media:Register("statusbar", "Otravi", [[Interface\Addons\Skada\media\statusbar\Otravi]])
media:Register("statusbar", "Outline", [[Interface\Addons\Skada\media\statusbar\Outline]])
media:Register("statusbar", "Perl", [[Interface\Addons\Skada\media\statusbar\Perl]])
media:Register("statusbar", "Smooth", [[Interface\Addons\Skada\media\statusbar\Smooth]])
media:Register("statusbar", "Round", [[Interface\Addons\Skada\media\statusbar\Round]])
media:Register("statusbar", "TukTex", [[Interface\Addons\Skada\media\statusbar\normTex]])
media:Register("border", "Glow", [[Interface\Addons\Skada\media\border\glowTex]])
media:Register("border", "Roth", [[Interface\Addons\Skada\media\border\roth]])
media:Register("background", "Copper", [[Interface\Addons\Skada\media\background\copper]])
-- Some sounds (copied from Omen).
media:Register("sound", "Rubber Ducky", [[Sound\Doodad\Goblin_Lottery_Open01.ogg]])
media:Register("sound", "Cartoon FX", [[Sound\Doodad\Goblin_Lottery_Open03.ogg]])
media:Register("sound", "Explosion", [[Sound\Doodad\Hellfire_Raid_FX_Explosion05.ogg]])
media:Register("sound", "Shing!", [[Sound\Doodad\PortcullisActive_Closed.ogg]])
media:Register("sound", "Wham!", [[Sound\Doodad\PVP_Lordaeron_Door_Open.ogg]])
media:Register("sound", "Simon Chime", [[Sound\Doodad\SimonGame_LargeBlueTree.ogg]])
media:Register("sound", "War Drums", [[Sound\Event Sounds\Event_wardrum_ogre.ogg]])
media:Register("sound", "Cheer", [[Sound\Event Sounds\OgreEventCheerUnique.ogg]])
media:Register("sound", "Humm", [[Sound\Spells\SimonGame_Visual_GameStart.ogg]])
media:Register("sound", "Short Circuit", [[Sound\Spells\SimonGame_Visual_BadPress.ogg]])
media:Register("sound", "Fel Portal", [[Sound\Spells\Sunwell_Fel_PortalStand.ogg]])
media:Register("sound", "Fel Nova", [[Sound\Spells\SeepingGaseous_Fel_Nova.ogg]])
media:Register("sound", "You Will Die!", [[Sound\Creature\CThun\CThunYouWillDie.ogg]])
-- DB
self.db = LibStub("AceDB-3.0"):New("SkadaDB", self.defaults, "Default")
if type(SkadaPerCharDB) ~= "table" then SkadaPerCharDB = {} end
self.char = SkadaPerCharDB
self.char.sets = self.char.sets or {}
LibStub("AceConfigRegistry-3.0"):RegisterOptionsTable("Skada", self.options, true)
-- Profiles
LibStub("AceConfigRegistry-3.0"):RegisterOptionsTable("Skada-Profiles", LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db), true)
local profiles = LibStub('AceDBOptions-3.0'):GetOptionsTable(self.db)
profiles.order = 600
profiles.disabled = false
Skada.options.args.profiles = profiles
-- Dual spec profiles
if lds then
lds:EnhanceDatabase(self.db, "SkadaDB")
lds:EnhanceOptions(LibStub("AceDBOptions-3.0"):GetOptionsTable(self.db), self.db)
end
-- Blizzard options frame
local panel = CreateFrame("Frame", "SkadaBlizzOptions")
panel.name = "Skada"
InterfaceOptions_AddCategory(panel)
local fs = panel:CreateFontString(nil, "OVERLAY", "GameFontNormalLarge")
fs:SetPoint("TOPLEFT", 10, -15)
fs:SetPoint("BOTTOMRIGHT", panel, "TOPRIGHT", 10, -45)
fs:SetJustifyH("LEFT")
fs:SetJustifyV("TOP")
fs:SetText("Skada")
local button = CreateFrame("Button", nil, panel, "UIPanelButtonTemplate")
button:SetText(L['Configure'])
button:SetWidth(128)
button:SetPoint("TOPLEFT", 10, -48)
button:SetScript('OnClick', function()
while CloseWindows() do end
return Skada:OpenOptions()
end)
-- Slash Handler
SLASH_SKADA1 = "/skada"
SlashCmdList.SKADA = slashHandler
self.db.RegisterCallback(self, "OnProfileChanged", "ReloadSettings")
self.db.RegisterCallback(self, "OnProfileCopied", "ReloadSettings")
self.db.RegisterCallback(self, "OnProfileReset", "ReloadSettings")
self.db.RegisterCallback(self, "OnDatabaseShutdown", "ClearAllIndexes")
-- Migrate old settings.
if self.db.profile.barmax then
self:Print("Migrating old settings somewhat gracefully. This should only happen once.")
self.db.profile.barmax = nil
self.db.profile.background.height = 200
end
if self.db.profile.total then
self.db.profile.current = nil
self.db.profile.total = nil
self.db.profile.sets = nil
end
self:SetNotifyIcon("Interface\\Icons\\Spell_Lightning_LightningBolt01")
self:SetNotifyStorage(self.db.profile.versions)
self:NotifyOnce(self.versions)
end
end
function Skada:OpenOptions(window)
AceConfigDialog:SetDefaultSize('Skada', 800, 600)
if window then
AceConfigDialog:Open('Skada')
AceConfigDialog:SelectGroup('Skada', 'windows', window.db.name)
elseif not AceConfigDialog:Close('Skada') then
AceConfigDialog:Open('Skada')
end
end
function Skada:OnEnable()
self:ReloadSettings()
cleuFrame:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
popup:RegisterEvent("PLAYER_ENTERING_WORLD")
popup:RegisterEvent("ZONE_CHANGED_NEW_AREA")
popup:RegisterEvent("GROUP_ROSTER_UPDATE")
popup:RegisterEvent("UNIT_PET")
popup:RegisterEvent("PLAYER_REGEN_DISABLED")
popup:RegisterEvent("PET_BATTLE_OPENING_START")
popup:RegisterEvent("PET_BATTLE_CLOSE")
popup:RegisterEvent("ENCOUNTER_START")
popup:RegisterEvent("ENCOUNTER_END")
if type(CUSTOM_CLASS_COLORS) == "table" then
Skada.classcolors = CUSTOM_CLASS_COLORS
end
if self.moduleList then
for i = 1, #self.moduleList do
self.moduleList[i](self, L)
end
self.moduleList = nil
end
-- Instead of listening for callbacks on SharedMedia we simply wait a few seconds and then re-apply settings
-- to catch any missing media. Lame? Yes.
self:ScheduleTimer("ApplySettings", 2)
-- Memory usage warning
self:ScheduleTimer("MemoryCheck", 3)
end
function Skada:MemoryCheck()
UpdateAddOnMemoryUsage()
local mem = GetAddOnMemoryUsage("Skada")
if mem > 30000 then
self:Print(L["Memory usage is high. You may want to reset Skada, and enable one of the automatic reset options."])
end
end
function Skada:AddLoadableModule(name, description, func)
if not self.moduleList then self.moduleList = {} end
self.moduleList[#self.moduleList+1] = func
self:AddLoadableModuleCheckbox(name, L[name], description and L[description])
end
| mit |
mightymadTV/gcraft | gcraft/gamemode/cl_hudpickup.lua | 3 | 6359 |
GM.PickupHistory = {}
GM.PickupHistoryLast = 0
GM.PickupHistoryTop = ScrH() / 2
GM.PickupHistoryWide = 300
GM.PickupHistoryCorner = surface.GetTextureID( "gui/corner8" )
--[[---------------------------------------------------------
Name: gamemode:HUDWeaponPickedUp( wep )
Desc: The game wants you to draw on the HUD that a weapon has been picked up
-----------------------------------------------------------]]
function GM:HUDWeaponPickedUp( wep )
if (!LocalPlayer():Alive()) then return end
if ( !IsValid( wep ) ) then return end
if ( !isfunction( wep.GetPrintName ) ) then return end
local pickup = {}
pickup.time = CurTime()
pickup.name = wep:GetPrintName()
pickup.holdtime = 5
pickup.font = "DermaDefaultBold"
pickup.fadein = 0.04
pickup.fadeout = 0.3
pickup.color = Color( 255, 200, 50, 255 )
surface.SetFont( pickup.font )
local w, h = surface.GetTextSize( pickup.name )
pickup.height = h
pickup.width = w
if (self.PickupHistoryLast >= pickup.time) then
pickup.time = self.PickupHistoryLast + 0.05
end
table.insert( self.PickupHistory, pickup )
self.PickupHistoryLast = pickup.time
end
--[[---------------------------------------------------------
Name: gamemode:HUDItemPickedUp( itemname )
Desc: An item has been picked up..
-----------------------------------------------------------]]
function GM:HUDItemPickedUp( itemname )
if (!LocalPlayer():Alive()) then return end
local pickup = {}
pickup.time = CurTime()
pickup.name = "#"..itemname;
pickup.holdtime = 5
pickup.font = "DermaDefaultBold"
pickup.fadein = 0.04
pickup.fadeout = 0.3
pickup.color = Color( 180, 255, 180, 255 )
surface.SetFont( pickup.font )
local w, h = surface.GetTextSize( pickup.name )
pickup.height = h
pickup.width = w
if (self.PickupHistoryLast >= pickup.time) then
pickup.time = self.PickupHistoryLast + 0.05
end
table.insert( self.PickupHistory, pickup )
self.PickupHistoryLast = pickup.time
end
--[[---------------------------------------------------------
Name: gamemode:HUDAmmoPickedUp( itemname, amount )
Desc: Ammo has been picked up..
-----------------------------------------------------------]]
function GM:HUDAmmoPickedUp( itemname, amount )
local localplayer = LocalPlayer();
if ( !IsValid( localplayer ) || !localplayer:Alive() ) then return end
-- Try to tack it onto an exisiting ammo pickup
if ( self.PickupHistory ) then
for k, v in pairs( self.PickupHistory ) do
if ( v.name == "#"..itemname.."_ammo" ) then
v.amount = tostring( tonumber(v.amount) + amount )
v.time = CurTime() - v.fadein
return
end
end
end
local pickup = {}
pickup.time = CurTime()
pickup.name = "#"..itemname.."_ammo";
pickup.holdtime = 5
pickup.font = "DermaDefaultBold"
pickup.fadein = 0.04
pickup.fadeout = 0.3
pickup.color = Color( 180, 200, 255, 255 )
pickup.amount = tostring(amount)
surface.SetFont( pickup.font )
local w, h = surface.GetTextSize( pickup.name )
pickup.height = h
pickup.width = w
local w, h = surface.GetTextSize( pickup.amount )
pickup.xwidth = w
pickup.width = pickup.width + w + 16
if (self.PickupHistoryLast >= pickup.time) then
pickup.time = self.PickupHistoryLast + 0.05
end
table.insert( self.PickupHistory, pickup )
self.PickupHistoryLast = pickup.time
end
function GM:HUDDrawPickupHistory( )
if (self.PickupHistory == nil) then return end
local x, y = ScrW() - self.PickupHistoryWide - 20, self.PickupHistoryTop
local tall = 0
local wide = 0
for k, v in pairs( self.PickupHistory ) do
if ( !istable(v) ) then
Msg( tostring( v ) .."\n")
PrintTable( self.PickupHistory )
self.PickupHistory[ k ] = nil
return
end
if (v.time < CurTime()) then
if (v.y == nil) then v.y = y end
v.y = (v.y*5 + y) / 6
local delta = (v.time + v.holdtime) - CurTime()
delta = delta / v.holdtime
local alpha = 255
local colordelta = math.Clamp( delta, 0.6, 0.7 )
-- Fade in/out
if (delta > 1-v.fadein) then
alpha = math.Clamp( (1.0 - delta) * (255/v.fadein), 0, 255 )
elseif ( delta < v.fadeout ) then
alpha = math.Clamp( delta * (255/v.fadeout), 0, 255 )
end
v.x = x + self.PickupHistoryWide - (self.PickupHistoryWide * (alpha/255))
local rx, ry, rw, rh = math.Round(v.x-4), math.Round(v.y-(v.height/2)-4), math.Round(self.PickupHistoryWide+9), math.Round(v.height+8)
local bordersize = 8
surface.SetTexture( self.PickupHistoryCorner )
surface.SetDrawColor( v.color.r, v.color.g, v.color.b, alpha )
surface.DrawTexturedRectRotated( rx + bordersize/2 , ry + bordersize/2, bordersize, bordersize, 0 )
surface.DrawTexturedRectRotated( rx + bordersize/2 , ry + rh -bordersize/2, bordersize, bordersize, 90 )
surface.DrawRect( rx, ry+bordersize, bordersize, rh-bordersize*2 )
surface.DrawRect( rx+bordersize, ry, v.height - 4, rh )
surface.SetDrawColor( 230*colordelta, 230*colordelta, 230*colordelta, alpha )
surface.DrawRect( rx+bordersize+v.height-4, ry, rw - (v.height - 4) - bordersize*2, rh )
surface.DrawTexturedRectRotated( rx + rw - bordersize/2 , ry + rh - bordersize/2, bordersize, bordersize, 180 )
surface.DrawTexturedRectRotated( rx + rw - bordersize/2 , ry + bordersize/2, bordersize, bordersize, 270 )
surface.DrawRect( rx+rw-bordersize, ry+bordersize, bordersize, rh-bordersize*2 )
draw.SimpleText( v.name, v.font, v.x+1+v.height+8, v.y - (v.height/2)+1, Color( 0, 0, 0, alpha*0.5 ) )
draw.SimpleText( v.name, v.font, v.x+v.height+8, v.y - (v.height/2), Color( 255, 255, 255, alpha ) )
if (v.amount) then
draw.SimpleText( v.amount, v.font, v.x+self.PickupHistoryWide+1, v.y - (v.height/2)+1, Color( 0, 0, 0, alpha*0.5 ), TEXT_ALIGN_RIGHT )
draw.SimpleText( v.amount, v.font, v.x+self.PickupHistoryWide, v.y - (v.height/2), Color( 255, 255, 255, alpha ), TEXT_ALIGN_RIGHT )
end
y = y + (v.height + 16)
tall = tall + v.height + 18
wide = math.Max( wide, v.width + v.height + 24 )
if (alpha == 0) then self.PickupHistory[k] = nil end
end
end
self.PickupHistoryTop = (self.PickupHistoryTop * 5 + ( ScrH() * 0.75 - tall ) / 2 ) / 6
self.PickupHistoryWide = (self.PickupHistoryWide * 5 + wide) / 6
end
| gpl-2.0 |
medialab-prado/Interactivos-15-Ego | minetest-ego/games/minetest_game/mods/beds/functions.lua | 1 | 5209 | local pi = math.pi
local player_in_bed = 0
local is_sp = minetest.is_singleplayer()
local enable_respawn = minetest.setting_getbool("enable_bed_respawn")
if enable_respawn == nil then
enable_respawn = true
end
-- helper functions
local function get_look_yaw(pos)
local n = minetest.get_node(pos)
if n.param2 == 1 then
return pi/2, n.param2
elseif n.param2 == 3 then
return -pi/2, n.param2
elseif n.param2 == 0 then
return pi, n.param2
else
return 0, n.param2
end
end
local function is_night_skip_enabled()
local enable_night_skip = minetest.setting_getbool("enable_bed_night_skip")
if enable_night_skip == nil then
enable_night_skip = true
end
return enable_night_skip
end
local function check_in_beds(players)
local in_bed = beds.player
if not players then
players = minetest.get_connected_players()
end
for n, player in ipairs(players) do
local name = player:get_player_name()
if not in_bed[name] then
return false
end
end
return #players > 0
end
local function lay_down(player, pos, bed_pos, state, skip)
local name = player:get_player_name()
local hud_flags = player:hud_get_flags()
if not player or not name then
return
end
-- stand up
if state ~= nil and not state then
local p = beds.pos[name] or nil
if beds.player[name] ~= nil then
beds.player[name] = nil
player_in_bed = player_in_bed - 1
end
-- skip here to prevent sending player specific changes (used for leaving players)
if skip then
return
end
if p then
player:setpos(p)
end
-- physics, eye_offset, etc
player:set_eye_offset({x=0,y=0,z=0}, {x=0,y=0,z=0})
player:set_look_yaw(math.random(1, 180)/100)
default.player_attached[name] = false
player:set_physics_override(1, 1, 1)
hud_flags.wielditem = true
default.player_set_animation(player, "stand" , 30)
-- lay down
else
beds.player[name] = 1
beds.pos[name] = pos
player_in_bed = player_in_bed + 1
-- physics, eye_offset, etc
player:set_eye_offset({x=0,y=-13,z=0}, {x=0,y=0,z=0})
local yaw, param2 = get_look_yaw(bed_pos)
player:set_look_yaw(yaw)
local dir = minetest.facedir_to_dir(param2)
local p = {x=bed_pos.x+dir.x/2,y=bed_pos.y,z=bed_pos.z+dir.z/2}
player:set_physics_override(0, 0, 0)
player:setpos(p)
default.player_attached[name] = true
hud_flags.wielditem = false
default.player_set_animation(player, "lay" , 0)
end
player:hud_set_flags(hud_flags)
end
local function update_formspecs(finished)
local ges = #minetest.get_connected_players()
local form_n = ""
local is_majority = (ges/2) < player_in_bed
if finished then
form_n = beds.formspec ..
"label[2.7,11; Good morning.]"
else
form_n = beds.formspec ..
"label[2.2,11;"..tostring(player_in_bed).." of "..tostring(ges).." players are in bed]"
if is_majority and is_night_skip_enabled() then
form_n = form_n ..
"button_exit[2,8;4,0.75;force;Force night skip]"
end
end
for name,_ in pairs(beds.player) do
minetest.show_formspec(name, "beds_form", form_n)
end
end
-- public functions
function beds.kick_players()
for name,_ in pairs(beds.player) do
local player = minetest.get_player_by_name(name)
lay_down(player, nil, nil, false)
end
end
function beds.skip_night()
minetest.set_timeofday(0.23)
beds.set_spawns()
end
function beds.on_rightclick(pos, player)
local name = player:get_player_name()
local ppos = player:getpos()
local tod = minetest.get_timeofday()
if tod > 0.2 and tod < 0.805 then
if beds.player[name] then
lay_down(player, nil, nil, false)
end
minetest.chat_send_player(name, "You can only sleep at night.")
return
end
-- move to bed
if not beds.player[name] then
lay_down(player, ppos, pos)
else
lay_down(player, nil, nil, false)
end
if not is_sp then
update_formspecs(false)
end
-- skip the night and let all players stand up
if check_in_beds() then
minetest.after(2, function()
if not is_sp then
update_formspecs(is_night_skip_enabled())
end
if is_night_skip_enabled() then
beds.skip_night()
beds.kick_players()
end
end)
end
end
-- callbacks
minetest.register_on_joinplayer(function(player)
beds.read_spawns()
end)
-- respawn player at bed if enabled and valid position is found
minetest.register_on_respawnplayer(function(player)
if not enable_respawn then
return false
end
local name = player:get_player_name()
local pos = beds.spawn[name] or nil
if pos then
player:setpos(pos)
return true
end
end)
minetest.register_on_leaveplayer(function(player)
local name = player:get_player_name()
lay_down(player, nil, nil, false, true)
beds.player[name] = nil
if check_in_beds() then
minetest.after(2, function()
update_formspecs(is_night_skip_enabled())
if is_night_skip_enabled() then
beds.skip_night()
beds.kick_players()
end
end)
end
end)
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname ~= "beds_form" then
return
end
if fields.quit or fields.leave then
lay_down(player, nil, nil, false)
update_formspecs(false)
end
if fields.force then
update_formspecs(is_night_skip_enabled())
if is_night_skip_enabled() then
beds.skip_night()
beds.kick_players()
end
end
end)
| mit |
Jeffyrao/nn | CMul.lua | 24 | 3600 | local CMul, parent = torch.class('nn.CMul', 'nn.Module')
function CMul:__init(...)
parent.__init(self)
local arg = {...}
self.size = torch.LongStorage()
local n = #arg
if n == 1 and torch.type(arg[1]) == 'torch.LongStorage' then
self.size:resize(#arg[1]):copy(arg[1])
else
self.size:resize(n)
for i=1,n do
self.size[i] = arg[i]
end
end
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size)
self.output:resize(self.size)
self:reset()
end
function CMul:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:nElement())
end
self.weight:uniform(-stdv,stdv)
end
function CMul:updateOutput(input)
-- lazy-initialize
self._output = self._output or input.new()
self._weight = self._weight or input.new()
self._expand = self._expand or input.new()
self._repeat = self._repeat or input.new()
self.output:resizeAs(input):copy(input)
if input:nElement() == self.weight:nElement() then
self._output:view(self.output, -1)
self._weight:view(self.weight, -1)
self._output:cmul(self._weight)
else
local batchSize = input:size(1)
self._output:view(self.output, batchSize, -1)
self._weight:view(self.weight, 1, -1)
self._expand:expandAs(self._weight, self._output)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat:resizeAs(self._expand):copy(self._expand)
self._output:cmul(self._repeat)
else
self._output:cmul(self._expand)
end
end
return self.output
end
function CMul:updateGradInput(input, gradOutput)
if not self.gradInput then
return
end
self._gradOutput = self._gradOutput or input.new()
self._gradInput = self._gradInput or input.new()
self.gradInput:resizeAs(input):zero()
if self.weight:nElement() == gradOutput:nElement() then
self.gradInput:addcmul(1, self.weight, gradOutput)
else
local batchSize = input:size(1)
self._gradOutput:view(gradOutput, batchSize, -1)
self._gradInput:view(self.gradInput, batchSize, -1)
self._weight:view(self.weight, 1, -1)
self._expand:expandAs(self._weight, self._gradOutput)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat:resizeAs(self._expand):copy(self._expand)
self._gradInput:addcmul(1, self._repeat, self._gradOutput)
else
self._gradInput:addcmul(1, self._expand, self._gradOutput)
end
end
return self.gradInput
end
function CMul:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self._input = self._input or input.new()
self._gradWeight = self._gradWeight or input.new()
self._sum = self._sum or input.new()
if self.weight:nElement() == gradOutput:nElement() then
self.gradWeight:addcmul(scale, input, gradOutput)
else
local batchSize = input:size(1)
self._input:view(input, batchSize, -1)
self._gradOutput:view(gradOutput, batchSize, -1)
self._gradWeight:view(self.gradWeight, 1, -1)
self._repeat:cmul(self._input, self._gradOutput)
self._sum:sum(self._repeat, 1)
self._gradWeight:add(scale, self._sum)
end
end
function CMul:type(type, tensorCache)
if type then
self._input = nil
self._output = nil
self._weight = nil
self._gradWeight = nil
self._expand = nil
self._repeat = nil
self._sum = nil
end
return parent.type(self, type, tensorCache)
end
| bsd-3-clause |
kindy/ltp | ltp/template.lua | 3 | 5946 | --
-- Copyright 2007-2008 Savarese Software Research Corporation.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.savarese.com/software/ApacheLicense-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local ltp = require('ltp.util')
local function compile_template_to_table(result, data, start_lua, end_lua)
local LF, CR, EQ = 10, 13, 61
local i1, i2, i3
i3 = 1
repeat
i2, i1 = data:find(start_lua, i3, true)
if i2 then
if i3 < i2 then
table.insert(result, "table.insert(output,")
table.insert(result, string.format('%q', data:sub(i3, i2 - 1)))
table.insert(result, ");")
end
i1 = i1 + 2
i2, i3 = data:find(end_lua, i1, true)
if i2 then
if data:byte(i1-1) == EQ then
table.insert(result, "table.insert(output,")
table.insert(result, data:sub(i1, i2 - 1))
table.insert(result, ");")
i3 = i3 + 1
else
table.insert(result, data:sub(i1, i2 - 1))
i3 = i3 + 1
if data:byte(i3) == LF then
i3 = i3 + 1
elseif data:byte(i3) == CR and data:byte(i3+1) == LF then
i3 = i3 + 2
end
end
end
elseif i3 <= #data then
table.insert(result, "table.insert(output,")
table.insert(result, string.format('%q', data:sub(i3)))
table.insert(result, ");")
end
until not i2
return result
end
local function compile_template_as_function(data, start_lua, end_lua)
local result = { "return function(output) " }
table.insert(compile_template_to_table(result, data, start_lua, end_lua),
"end")
return table.concat(result)
end
local function compile_template_as_chunk(data, start_lua, end_lua)
local result = { "local output = ... " }
return
table.concat(compile_template_to_table(result, data, start_lua, end_lua))
end
local function compile_template(data, start_lua, end_lua)
return table.concat(compile_template_to_table({ }, data, start_lua, end_lua))
end
local function load_template(data, start_lua, end_lua)
return assert(loadstring(compile_template_as_chunk(data, start_lua, end_lua),
"=(load)"))
end
local function execute_template(template, environment, output)
setfenv(template, environment)(output)
end
local function basic_environment(merge_global, environment)
if not environment then
environment = { }
end
if merge_global then
ltp.merge_index(environment, _G)
else
environment.table = table
end
return environment
end
local function load_environment(env_files, merge_global)
local environment = nil
if env_files and #env_files > 0 then
for i = 1,#env_files,1 do
local efun = assert(loadfile(env_files[i]))
if i > 1 then
environment = ltp.merge_table(setfenv(efun, environment)(), environment)
else
environment = basic_environment(merge_global, efun())
end
end
else
environment = basic_environment(merge_global)
end
return environment
end
local function read_template(template)
return ((template == "-" and io.stdin:read("*a")) or ltp.read_all(template))
end
local function render_template(template_data, start_lua, end_lua, environment)
local rfun = load_template(template_data, start_lua, end_lua)
local output = { }
execute_template(rfun, environment, output)
return table.concat(output)
end
local function execute_env_code(env_code, environment)
for i = 1,#env_code do
local fun, emsg = loadstring(env_code[i])
if fun then
setfenv(fun, environment)()
else
error("error loading " .. env_code[i] .. "\n" .. emsg)
end
end
end
local function render(outfile, num_passes, template, merge_global,
env_files, start_lua, end_lua, env_code)
local data = assert(read_template(template), "error reading " .. template)
local environment = load_environment(env_files, merge_global)
execute_env_code(env_code, environment)
if num_passes > 0 then
for i = 1,num_passes do
data = render_template(data, start_lua, end_lua, environment)
end
else
-- Prevent an infinite loop by capping expansion to 100 times.
num_passes = 1
repeat
data = render_template(data, start_lua, end_lua, environment)
num_passes = num_passes + 1
until data:find(start_lua, 1, true) == nil or num_passes >= 100
end
outfile:write(data);
end
local function compile_as_function(outfile, template, start_lua, end_lua)
local data = read_template(template)
outfile:write(compile_template_as_function(data, start_lua, end_lua))
end
local function compile(outfile, template, start_lua, end_lua)
local data = read_template(template)
outfile:write(compile_template(data, start_lua, end_lua))
end
return ltp.merge_table(
{
compile_template_to_table = compile_template_to_table,
compile_template_as_chunk = compile_template_as_chunk,
compile_template_as_function = compile_template_as_function,
compile_template = compile_template,
load_template = load_template,
execute_template = execute_template,
basic_environment = basic_environment,
load_environment = load_environment,
render_template = render_template,
execute_env_code = execute_env_code,
render = render,
compile_as_function = compile_as_function,
compile = compile
},
ltp
)
| apache-2.0 |
premake/premake-eclipse | eclipse_project.lua | 1 | 3769 | --
-- Name: eclipse/eclipse_project.lua
-- Purpose: Generate a Eclipse .project file.
-- Author: Manu Evans
-- Created: 2014/12/22
-- Copyright: (c) 2008-2014 Jason Perkins and the Premake project
--
local p = premake
local eclipse = p.modules.eclipse
local tree = p.tree
local project = p.project
local config = p.config
local m = eclipse
--
-- .project stuff
--
function m.project.projects(prj)
-- TODO: check the VS solution code which rigs up dependencies, it must be project-wise...
-- collect all dependencies for all configs
local dependencies = {}
-- cfgs = prj.allCfgs
-- for each cfg
-- dependencies = table.join(dependencies, config.getlinks(cfg, "siblings", "basename"))
_p(1, '<projects>')
-- for _, proj in ipairs(dependencies) do
-- _x(2, '<project>%s</project>', proj)
-- end
_p(1, '</projects>')
end
local function project_dictionary(key, value)
_p(4, '<dictionary>')
_p(5, '<key>%s</key>', key)
_p(5, '<value>%s</value>', value)
_p(4, '</dictionary>')
end
function m.project.genmakebuilder_arguments(prj)
-- project_dictionary('?name?', '')
-- project_dictionary('org.eclipse.cdt.make.core.append_environment', 'true')
-- project_dictionary('org.eclipse.cdt.make.core.autoBuildTarget', 'all')
-- project_dictionary('org.eclipse.cdt.make.core.buildArguments', '')
-- project_dictionary('org.eclipse.cdt.make.core.buildCommand', 'make')
-- project_dictionary('org.eclipse.cdt.make.core.buildLocation', '${workspace_loc:/udPlatform/Debug}')
-- project_dictionary('org.eclipse.cdt.make.core.cleanBuildTarget', 'clean')
-- project_dictionary('org.eclipse.cdt.make.core.contents', 'org.eclipse.cdt.make.core.activeConfigSettings')
-- project_dictionary('org.eclipse.cdt.make.core.enableAutoBuild', 'false')
-- project_dictionary('org.eclipse.cdt.make.core.enableCleanBuild', 'true')
-- project_dictionary('org.eclipse.cdt.make.core.enableFullBuild', 'true')
-- project_dictionary('org.eclipse.cdt.make.core.fullBuildTarget', 'all')
-- project_dictionary('org.eclipse.cdt.make.core.stopOnError', 'true')
-- project_dictionary('org.eclipse.cdt.make.core.useDefaultBuildCmd', 'true')
end
function m.project.genmakebuilder(prj)
_p(2, '<buildCommand>')
_p(3, '<name>%s</name>', 'org.eclipse.cdt.managedbuilder.core.genmakebuilder')
_p(3, '<triggers>%s</triggers>', 'clean,full,incremental,')
_p(3, '<arguments>')
m.project.genmakebuilder_arguments(prj)
_p(3, '</arguments>')
_p(2, '</buildCommand>')
end
function m.project.scannerconfigbuilder(prj)
_p(2, '<buildCommand>')
_p(3, '<name>%s</name>', 'org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder')
_p(3, '<triggers>%s</triggers>', 'full,incremental,')
_p(3, '<arguments>')
_p(3, '</arguments>')
_p(2, '</buildCommand>')
end
function m.project.buildspec(prj)
_p(1, '<buildSpec>')
m.project.genmakebuilder(prj)
m.project.scannerconfigbuilder(prj)
_p(1, '</buildSpec>')
end
function m.project.natures(prj)
_p(1, '<natures>')
_p(2, '<nature>%s</nature>', 'org.eclipse.cdt.core.cnature')
_p(2, '<nature>%s</nature>', 'org.eclipse.cdt.core.ccnature')
_p(2, '<nature>%s</nature>', 'org.eclipse.cdt.managedbuilder.core.managedBuildNature')
_p(2, '<nature>%s</nature>', 'org.eclipse.cdt.managedbuilder.core.ScannerConfigNature')
_p(1, '</natures>')
end
--
-- Project: Generate the Eclipse .project file.
--
function m.project.generate(prj)
p.eol("\r\n")
p.indent("\t")
p.escaper(eclipse.esc)
_p('<?xml version="1.0" encoding="UTF-8"?>')
_p('<projectDescription>')
_x(1, '<name>%s</name>', prj.name)
_p(1, '<comment></comment>')
m.project.projects()
m.project.buildspec()
m.project.natures()
_p('</projectDescription>')
end
| bsd-3-clause |
rlcevg/Zero-K | units/corhlt.lua | 4 | 6799 | unitDef = {
unitname = [[corhlt]],
name = [[Stinger]],
description = [[High-Energy Laser Tower]],
acceleration = 0,
brakeRate = 0,
buildAngle = 4096,
buildCostEnergy = 420,
buildCostMetal = 420,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 4,
buildingGroundDecalSizeY = 4,
buildingGroundDecalType = [[corhlt_aoplane.dds]],
buildPic = [[CORHLT.png]],
buildTime = 420,
canAttack = true,
canstop = [[1]],
category = [[FLOAT TURRET]],
collisionVolumeOffsets = [[0 17 0]],
collisionVolumeScales = [[36 110 36]],
collisionVolumeTest = 1,
collisionVolumeType = [[CylY]],
corpse = [[DEAD]],
customParams = {
description_fr = [[Tourelle Laser Moyenne HLT]],
description_de = [[Hochenergetischer Laserturm]],
description_pl = [[Ciezka wieza laserowa]],
helptext = [[The Stinger is a medium laser turret. Its three rotating laser guns can kill almost any small unit, but its low rate of fire makes it vulnerable to swarms when unassisted.]],
helptext_fr = [[Le Gaat Gun est compos? de trois canons lasers rotatifs lourd. Oblig?s de se refroidir apr?s chaque tir, il n'en d?livrent pas moins une forte puissance de feu instann?e. Tr?s utile sur des grosses cibles, elle aura besoin d'assistance en cas de nombreux ennemis.]],
helptext_de = [[Der Stinger ist ein durchschnittlicher Lasergesch?zturm. Seine drei rotierenden Laserkanonen können so gut wie jede kleine Einheit töten, aber die langsame Feuerrate macht den Stinger anfällig f? große Gruppen, sobald er nicht gen?end abgesichert ist.]],
helptext_pl = [[Stinger to wieza laserowa, ktora zadaje ciezkie obrazenia przy kazdym strzale i ma dosyc dobry zasieg, jednak dlugi czas przeladowania oznacza, ze latwo ja zniszczyc grupami mniejszych jednostek.]],
aimposoffset = [[0 55 0]],
},
explodeAs = [[MEDIUM_BUILDINGEX]],
floater = true,
footprintX = 3,
footprintZ = 3,
iconType = [[defenseheavy]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
losEmitHeight = 80,
mass = 267,
maxDamage = 2475,
maxSlope = 36,
maxVelocity = 0,
minCloakDistance = 150,
noAutoFire = false,
noChaseCategory = [[FIXEDWING LAND SHIP SATELLITE SWIM GUNSHIP SUB HOVER]],
objectName = [[hlt.s3o]],
script = [[corhlt.lua]],
seismicSignature = 4,
selfDestructAs = [[MEDIUM_BUILDINGEX]],
sfxtypes = {
explosiongenerators = {
[[custom:HLTRADIATE0]],
[[custom:beamlaser_hit_blue]],
},
},
side = [[CORE]],
sightDistance = 660,
smoothAnim = true,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[ooo ooo ooo]],
weapons = {
{
def = [[LASER]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
LASER = {
name = [[High-Energy Laserbeam]],
areaOfEffect = 14,
beamTime = 0.8,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
statsprojectiles = 1,
statsdamage = 850,
},
damage = {
default = 170.1,
planes = 170.1,
subs = 9,
},
explosionGenerator = [[custom:flash1bluedark]],
fireStarter = 90,
fireTolerance = 8192, -- 45 degrees
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 10.4,
minIntensity = 1,
noSelfDamage = true,
projectiles = 5,
range = 620,
reloadtime = 4.5,
rgbColor = [[0 0 1]],
scrollSpeed = 5,
soundStart = [[weapon/laser/heavy_laser3]],
soundStartVolume = 3,
sweepfire = false,
texture1 = [[largelaserdark]],
texture2 = [[flaredark]],
texture3 = [[flaredark]],
texture4 = [[smallflaredark]],
thickness = 10.4024486300101,
tileLength = 300,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2250,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Stinger]],
blocking = true,
category = [[corpses]],
damage = 2475,
energy = 0,
featureDead = [[HEAP]],
featurereclamate = [[SMUDGE01]],
footprintX = 3,
footprintZ = 3,
height = [[20]],
hitdensity = [[100]],
metal = 168,
object = [[corhlt_d.s3o]],
reclaimable = true,
reclaimTime = 168,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
HEAP = {
description = [[Debris - Stinger]],
blocking = false,
category = [[heaps]],
damage = 2475,
energy = 0,
featurereclamate = [[SMUDGE01]],
footprintX = 3,
footprintZ = 3,
height = [[4]],
hitdensity = [[100]],
metal = 84,
object = [[debris3x3a.s3o]],
reclaimable = true,
reclaimTime = 84,
seqnamereclamate = [[TREE1RECLAMATE]],
world = [[All Worlds]],
},
},
}
return lowerkeys({ corhlt = unitDef })
| gpl-2.0 |
naserteam/hextor | bot/utils.lua | 2 | 23606 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'شما دسترسی برای دیدن ابزار ندارید'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "لیست بن شده ها\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "لیست گلوبال بن ها\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "کاربر "..result.from.id.." بن شد")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "کاربر "..result.from.id.." آن بن شد")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "گاربر "..name.."["..result.from.id.."] از تمامی گروه ها بن شد")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
samyk/proxmark3 | client/luascripts/data_mf_eml2html.lua | 1 | 2299 | -- The getopt-functionality is loaded from pm3/getopt.lua
-- Have a look there for further details
getopt = require('getopt')
bin = require('bin')
dumplib = require('html_dumplib')
local ansicolors = require('ansicolors')
copyright = ''
author = 'Martin Holst Swende'
version = 'v1.0.2'
desc = [[
This script takes a dumpfile on EML (ASCII) format and produces a html based dump, which is a
bit more easily analyzed.
]]
example = [[
script run data_mf_eml2html -o dumpdata.eml
]]
usage = [[
script run data_mf_eml2html [-i <file>] [-o <file>]
]]
arguments = [[
-h This help
-i <file> Specifies the dump-file (input). If omitted, 'dumpdata.eml' is used
-o <filename> Speciies the output file. If omitted, <curdate>.html is used.
]]
-- Some globals
local DEBUG = false -- the debug flag
---
-- A debug printout-function
local function dbg(args)
if not DEBUG then return end
if type(args) == 'table' then
local i = 1
while args[i] do
dbg(args[i])
i = i+1
end
else
print('###', args)
end
end
---
-- This is only meant to be used when errors occur
local function oops(err)
print('ERROR:', err)
core.clearCommandBuffer()
return nil, err
end
---
-- Usage help
local function help()
print(copyright)
print(author)
print(version)
print(desc)
print(ansicolors.cyan..'Usage'..ansicolors.reset)
print(usage)
print(ansicolors.cyan..'Arguments'..ansicolors.reset)
print(arguments)
print(ansicolors.cyan..'Example usage'..ansicolors.reset)
print(example)
end
local function main(args)
local input = 'dumpdata.eml'
local output = os.date('%Y-%m-%d_%H%M%S.html');
for o, a in getopt.getopt(args, 'i:o:h') do
if o == 'h' then return help() end
if o == 'i' then input = a end
if o == 'o' then output = a end
end
local filename, err = dumplib.convert_eml_to_html(input,output)
if err then return oops(err) end
print(('Wrote a HTML dump to the file %s'):format(filename))
end
--[[
In the future, we may implement so that scripts are invoked directly
into a 'main' function, instead of being executed blindly. For future
compatibility, I have done so, but I invoke my main from here.
--]]
main(args)
| gpl-2.0 |
joole/private-pkgs | luci/applications/luci-app-vpnbypass/luasrc/model/cbi/vpnbypass.lua | 6 | 2362 | readmeURL = "https://github.com/openwrt/packages/blob/master/net/vpnbypass/files/README.md"
m = Map("vpnbypass", translate("VPN Bypass Settings"))
s = m:section(NamedSection, "config", "vpnbypass")
-- General options
e = s:option(Flag, "enabled", translate("Enable/start service"))
e.rmempty = false
function e.cfgvalue(self, section)
return self.map:get(section, "enabled") == "1" and luci.sys.init.enabled("vpnbypass") and self.enabled or self.disabled
end
function e.write(self, section, value)
if value == "1" then
luci.sys.call("/etc/init.d/vpnbypass enable >/dev/null")
luci.sys.call("/etc/init.d/vpnbypass start >/dev/null")
else
luci.sys.call("/etc/init.d/vpnbypass stop >/dev/null")
end
return Flag.write(self, section, value)
end
-- Local Ports
p1 = s:option(DynamicList, "localport", translate("Local Ports to Bypass"), translate("Local ports to trigger VPN Bypass"))
p1.datatype = "portrange"
-- p1.placeholder = "0-65535"
p1.addremove = false
p1.optional = false
-- Remote Ports
p2 = s:option(DynamicList, "remoteport", translate("Remote Ports to Bypass"), translate("Remote ports to trigger VPN Bypass"))
p2.datatype = "portrange"
-- p2.placeholder = "0-65535"
p2.addremove = false
p2.optional = false
-- Local Subnets
r1 = s:option(DynamicList, "localsubnet", translate("Local IP Addresses to Bypass"), translate("Local IP addresses or subnets with direct internet access (outside of the VPN tunnel)"))
r1.datatype = "ip4addr"
-- r1.placeholder = luci.ip.new(uci.cursor():get("network", "lan", "ipaddr") .. "/" .. uci.cursor():get("network", "lan", "netmask"))
r1.addremove = false
r1.optional = false
-- Remote Subnets
r2 = s:option(DynamicList, "remotesubnet", translate("Remote IP Addresses to Bypass"), translate("Remote IP addresses or subnets which will be accessed directly (outside of the VPN tunnel)"))
r2.datatype = "ip4addr"
-- r2.placeholder = "0.0.0.0/0"
r2.addremove = false
r2.optional = false
-- Domains
d = Map("dhcp")
s4 = d:section(TypedSection, "dnsmasq")
s4.anonymous = true
di = s4:option(DynamicList, "ipset", translate("Domains to Bypass"),
translate("Domains to be accessed directly (outside of the VPN tunnel), see ")
.. [[<a href="]] .. readmeURL .. [[#bypass-domains-formatsyntax" target="_blank">]]
.. translate("README") .. [[</a>]] .. translate(" for syntax"))
return m, d
| gpl-2.0 |
Amadiro/obtuse-tanuki | states/login.lua | 2 | 4490 | local tiny = require "tiny"
local gui = require "quickie"
local avatar = require "avatar"
local material = require "material-love"
-- This state is active from username entry until we get account and realm info
return function()
local gs = tiny.system()
gs.name = "login"
function gs:enter(from, world)
assert(world)
self.world = world
self.active = true
self.world:addSystem(self)
self.auto_login = SETTINGS.auto_login
self.user_info = {
text = SETTINGS.username or ""
}
if self.auto_login then
self.login_timer = love.timer.getTime()
end
self.user = {}
gui.group.default.size[1] = 150
gui.group.default.size[2] = 25
gui.group.default.spacing = 5
gui.keyboard.clearFocus()
self.signals = {}
function self:register()
self.signals["connect"] = Signal.register("connect", function(s)
if s == "login" then
self:register_commands(true)
end
end)
--[[
FROM: client_login:recv_account
Populate local user with received data.
--]]
self.signals["recv-account"] = Signal.register("recv-account", function(s, data)
assert(s == "login")
assert(data)
assert(data.account)
assert(data.characters)
self.user.account = data.account
self.user.characters = data.characters
for i, character in ipairs(self.user.characters) do
if character.avatar then
character.avatar = avatar.decode(character.avatar)
end
end
console.i("Received account: %s", data.account.username)
end)
--[[
FROM: client_login:recv_realm_list
Populate local user with received data.
--]]
self.signals["recv-realm-list"] = Signal.register("recv-realm-list", function(s, realms)
assert(s == "login")
assert(realms)
self.user.realms = realms
console.i("Received %d realm(s)", #realms)
-- for i, realm in ipairs(realms) do
-- console.d("Realm %d: %s", i, realm.name)
-- end
end)
end
function self:unregister()
for k, v in pairs(self.signals) do
Signal.remove(k, v)
end
end
self:register()
self:register_commands()
end
function gs:register_commands(unregister)
if unregister then
console.clearCommand("login")
console.defineCommand("logout", "Log out of the game server")
return
end
console.defineCommand("login", "Log into the game server", function(...) self:perform_login(...) end)
console.clearCommand("logout")
end
function gs:leave()
self:unregister()
self:register_commands(true)
end
function gs:perform_login(name, password, save)
self.client = require("systems.client_login")(self.world)
self.world:addSystem(self.client)
local ok, msg = self.client:connect()
if not ok then
console.e("Connection error: %s", msg)
return
end
save = save == "true" or tonumber(save or 0) > 0
if name and name ~= "" then
SETTINGS.username = name
if save then
SETTINGS.save()
end
elseif SETTINGS.username then
name = SETTINGS.username
else
console.e("Please enter a username.")
return
end
self.client:send_login {
username = name,
password = password
}
end
function gs:textinput(s)
gui.keyboard.textinput(s)
end
function gs:keypressed(key, scan, is_repeat)
gui.keyboard.pressed(key)
end
function gs:update(dt)
if self.user.account and self.user.characters and self.user.realms then
console.i("Account info received; loading character select")
Gamestate.switch(require("states.character_select")(), self.world, self.client, self.user)
end
gui.group { grow = "down", pos = { 20, 20 }, function()
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setFont(material.noto("body1"))
if self.auto_login then
gui.Label { text = "Logging in..." }
love.graphics.setFont(material.noto("title"))
if love.timer.getTime() - self.login_timer > 1 then
self:perform_login()
self.auto_login = false
end
elseif console.hasCommand("login") then
gui.Label { text = "Username" }
gui.Input { info = self.user_info, size = { 305 } }
gui.group { grow = "right", function()
if gui.Button { text = "Login" } then
self:perform_login(self.user_info.text)
end
if gui.Checkbox { checked = SETTINGS.auto_login, text = "Remember Me" } then
SETTINGS.auto_login = not SETTINGS.auto_login
end
end }
gui.group.getRect()
if gui.Button { text = "Exit" } then
love.event.quit()
end
end
end }
gui.core.draw()
end
return gs
end
| mit |
Satoshi-t/Re-SBS | lang/zh_CN/Mini.lua | 3 | 1973 | return {
["MiniScene"]= "小型场景",
["_mini_1"] = "狭路相逢",
["_mini_2"] = "谁与争锋",
["_mini_3"] = "青梅煮酒",
["_mini_4"] = "遗命与天运",
["_mini_5"] = "直刺咽喉",
["_mini_6"] = "围追堵截",
["_mini_7"] = "铁与血与火",
["_mini_8"] = "天下无双",
["_mini_9"] = "你死我活",
["_mini_10"] = "步步惊心",
["_mini_11"] = "措手不及",
["_mini_12"] = "翻云覆雨",
["_mini_13"] = "一字千金",
["_mini_14"] = "螳臂当车",
["_mini_15"] = "不依不挠",
["_mini_16"] = "英雄豪迈",
["_mini_17"] = "天命之子",
["_mini_18"] = "高帅富",
["_mini_19"] = "火烧连营",
["_mini_20"] = "一锤定音",
["_mini_21"] = "黄泉路",
["_mini_22"] = "一击灭敌",
["_mini_23"] = "马超破九策",
["_mini_24"] = "马谡的崛起",
["_mini_25"] = "万军取首",
["_mini_26"] = "如何是好",
["_mini_27"] = "珍惜机会",
["_mini_28"] = "连绵不绝",
["_mini_29"] = "三个好人",
["_mini_30"] = "武圣",
["_mini_31"] = "掩其不备",
["_mini_32"] = "一决雌雄",
["_mini_33"] = "赤壁之战",
["_mini_34"] = "七步诗",
["_mini_35"] = "安乐笑",
["_mini_36"] = "妙用南蛮",
["_mini_37"] = "一击必杀",
["_mini_38"] = "有难同当",
["_mini_39"] = "清场行动",
["_mini_40"] = "杀鸡取卵",
["_mini_41"] = "逆天难",
["_mini_42"] = "连环计",
["_mini_43"] = "樊城之战",
["_mini_44"] = "绝处逢生",
["_mini_45"] = "武智防",
["_mini_46"] = "精打细算",
["_mini_47"] = "二曹抢亲",
["_mini_48"] = "神坛",
["_mini_49"] = "七擒七纵",
["#WelcomeToMiniScenario"] = "欢迎来到小型场景第 %arg 关: %arg2",
["Player"] = "玩家",
["unknown"] = "未分配",
["AI"] = "电脑",
["AI1"] = "电脑1",
["AI2"] = "电脑2",
["AI3"] = "电脑3",
["AI4"] = "电脑4",
["AI5"] = "电脑5",
["AI6"] = "电脑6",
["AI7"] = "电脑7",
["AI8"] = "电脑8",
["AI9"] = "电脑9",
["custom_scenario"] = "自定义模式",
} | gpl-3.0 |
Satoshi-t/Re-SBS | lang/zh_CN/Package/YJCMPackage.lua | 1 | 7677 | -- translation for YJCM Package
return {
["YJCM"] = "一将成名",
["#caozhi"] = "八斗之才",
["caozhi"] = "曹植",
["designer:caozhi"] = "Foxear",
["illustrator:caozhi"] = "木美人",
["luoying"] = "落英",
[":luoying"] = "其他角色的牌因判定或弃置而置入弃牌堆时,你可以获得其中至少一张梅花牌。",
["jiushi"] = "酒诗",
[":jiushi"] = "若你的武将牌正面朝上,你可以将武将牌翻面,视为你使用了一张【酒】。每当你受到伤害扣减体力前,若武将牌背面朝上,你可以在伤害结算后将武将牌翻至正面朝上。",
["#yujin"] = "魏武之刚",
["yujin"] = "于禁",
["designer:yujin"] = "城管无畏",
["illustrator:yujin"] = "Yi章",
["yizhong"] = "毅重",
[":yizhong"] = "锁定技。若你的装备区没有防具牌,黑色【杀】对你无效。",
["#fazheng"] = "蜀汉的辅翼",
["fazheng"] = "法正",
["designer:fazheng"] = "Michael_Lee",
["illustrator:fazheng"] = "雷没才",
["enyuan"] = "恩怨",
[":enyuan"] = "每当你获得一名其他角色的两张或更多的牌后,你可以令其摸一张牌。每当你受到1点伤害后,你可以令伤害来源选择一项:交给你一张手牌,或失去1点体力。",
["EnyuanGive"] = "请交给 %dest %arg 张手牌",
["xuanhuo"] = "眩惑",
[":xuanhuo"] = "摸牌阶段开始时,你可以放弃摸牌并选择一名其他角色:若如此做,该角色摸两张牌,然后该角色可以对其攻击范围内由你选择的一名角色使用一张【杀】,否则令你获得其两张牌。",
["xuanhuo-invoke"] = "你可以发动“眩惑”<br/> <b>操作提示</b>: 选择一名其他角色→点击确定<br/>",
["xuanhuo_slash"] = "眩惑",
["xuanhuo-slash"] = "请对 %dest 使用一张【杀】",
["#masu"] = "怀才自负",
["masu"] = "马谡",
["designer:masu"] = "点点",
["illustrator:masu"] = "张帅",
["xinzhan"] = "心战",
[":xinzhan"] = "阶段技。若你的手牌数大于你的体力上限,你可以观看牌堆顶的三张牌,然后你可以展示并获得其中至少一张红桃牌,然后将其余的牌置于牌堆顶。",
["huilei"] = "挥泪",
[":huilei"] = "锁定技。你死亡时,杀死你的其他角色弃置其所有牌。",
["#HuileiThrow"] = "%from 的“%arg”被触发,伤害来源 %to 弃置所有牌",
["#xushu"] = "忠孝的侠士",
["xushu"] = "YJ徐庶",
["&xushu"] = "徐庶",
["illustrator:xushu"] = "XINA",
["wuyan"] = "无言",
[":wuyan"] = "锁定技。每当你造成或受到伤害时,防止锦囊牌的伤害。",
["jujian"] = "举荐",
[":jujian"] = "结束阶段开始时,你可以弃置一张非基本牌并选择一名其他角色:若如此做,该角色选择一项:摸两张牌,或回复1点体力,或重置武将牌并将其翻至正面朝上。",
["@jujian-card"] = "你可以发动“举荐”",
["~jujian"] = "选择一张非基本牌→选择一名其他角→点击确定",
["#WuyanBad"] = "%from 的“%arg2”被触发,本次伤害被防止",
["#WuyanGood"] = "%from 的“%arg2”被触发,防止了本次伤害",
["@jujian-discard"] = "请弃置一张非基本牌",
["jujian:draw"] = "摸两张牌",
["jujian:recover"] = "回复1点体力",
["jujian:reset"] = "重置并翻至正面朝上",
["#lingtong"] = "豪情烈胆",
["lingtong"] = "凌统",
["illustrator:lingtong"] = "绵Myan",
["xuanfeng"] = "旋风",
[":xuanfeng"] = "每当你失去一次装备区的牌后,或弃牌阶段结束时若你于本阶段内弃置了至少两张你的牌,你可以弃置一名其他角色的一张牌,然后弃置一名其他角色的一张牌。",
["#wuguotai"] = "武烈皇后",
["wuguotai"] = "吴国太",
["designer:wuguotai"] = "章鱼咬你哦",
["illustrator:wuguotai"] = "zoo",
["ganlu"] = "甘露",
[":ganlu"] = "阶段技。你可以令装备区的牌数量差不超过你已损失体力值的两名角色交换他们装备区的装备牌。",
["buyi"] = "补益",
[":buyi"] = "每当一名角色进入濒死状态时,你可以展示该角色的一张手牌:若此牌为非基本牌,该角色弃置此牌,然后回复1点体力。",
["#GanluSwap"] = "%from 交换了 %to 的装备",
["#xusheng"] = "江东的铁壁",
["xusheng"] = "徐盛",
["designer:xusheng"] = "阿江",
["illustrator:xusheng"] = "天空之城",
["pojun"] = "破军",
[":pojun"] = "每当你使用【杀】对目标角色造成伤害后,你可以令其摸X张牌,然后将其武将牌翻面。(X为该角色的体力值且至多为5)",
["#gaoshun"] = "攻无不克",
["gaoshun"] = "高顺",
["designer:gaoshun"] = "羽柴文理",
["illustrator:gaoshun"] = "鄧Sir",
["xianzhen"] = "陷阵",
[":xianzhen"] = "阶段技。你可以与一名其他角色拼点:若你赢,本回合,该角色的防具无效,你无视与该角色的距离,你对该角色使用【杀】无次数限制;若你没赢,你不能使用【杀】,直到回合结束。",
["jinjiu"] = "禁酒",
[":jinjiu"] = "锁定技。你的【酒】视为【杀】。",
["#chengong"] = "刚直壮烈",
["chengong"] = "陈宫",
["designer:chengong"] = "Kaycent",
["illustrator:chengong"] = "黑月乱",
["mingce"] = "明策",
[":mingce"] = "阶段技。你可以将一张装备牌或【杀】交给一名其他角色:若如此做,该角色可以视为对其攻击范围内由你选择的一名角色使用一张【杀】,否则其摸一张牌。",
["zhichi"] = "智迟",
[":zhichi"] = "锁定技。你的回合外,每当你受到伤害后,【杀】和非延时锦囊牌对你无效,直到回合结束。",
["mingce:use"] = "对攻击范围内的一名角色使用一张【杀】",
["mingce:draw"] = "摸一张牌",
["#ZhichiDamaged"] = "%from 受到了伤害,本回合内【<font color=\"yellow\"><b>杀</b></font>】和非延时锦囊都将对其无效",
["#ZhichiAvoid"] = "%from 的“%arg”被触发,【<font color=\"yellow\"><b>杀</b></font>】和非延时锦囊对其无效",
["#zhangchunhua"] = "冷血皇后",
["zhangchunhua"] = "张春华",
["designer:zhangchunhua"] = "JZHIEI",
["illustrator:zhangchunhua"] = "樱花闪乱",
["jueqing"] = "绝情",
[":jueqing"] = "锁定技。伤害结算开始前,你将要造成的伤害视为失去体力。",
["shangshi"] = "伤逝",
[":shangshi"] = "每当你的手牌数、体力值或体力上限改变后,你可以将手牌补至X张。(X为你已损失的体力值且至多为2)",
["#zhonghui"] = "桀骜的野心家",
["zhonghui"] = "钟会",
["illustrator:zhonghui"] = "雪君S",
["quanji"] = "权计",
[":quanji"] = "每当你受到1点伤害后,你可以摸一张牌,然后将一张手牌置于武将牌上,称为“权”。每有一张“权”,你的手牌上限+1。",
["QuanjiPush"] = "请将一张手牌置于武将牌上",
["zili"] = "自立",
[":zili"] = "觉醒技。准备阶段开始时,若“权”大于或等于三张,你失去1点体力上限,摸两张牌或回复1点体力,然后获得“排异”(阶段技。你可以将一张“权”置入弃牌堆并选择一名角色:若如此做,该角色摸两张牌:若其手牌多于你,该角色受到1点伤害)。",
["#ZiliWake"] = "%from 的“权”为 %arg 张,触发“%arg2”觉醒",
["zili:draw"] = "摸两张牌",
["zili:recover"] = "回复1点体力",
["power"] = "权",
["$ZiliAnimate"] = "image=image/animate/zili.png",
["paiyi"] = "排异",
[":paiyi"] = "阶段技。你可以将一张“权”置入弃牌堆并选择一名角色:若如此做,该角色摸两张牌:若其手牌多于你,该角色受到1点伤害。",
}
| gpl-3.0 |
avataronline/avatarclient | modules/game_hotkeys/hotkeys_manager.lua | 5 | 17268 | HOTKEY_MANAGER_USE = nil
HOTKEY_MANAGER_USEONSELF = 1
HOTKEY_MANAGER_USEONTARGET = 2
HOTKEY_MANAGER_USEWITH = 3
HotkeyColors = {
text = '#888888',
textAutoSend = '#FFFFFF',
itemUse = '#8888FF',
itemUseSelf = '#00FF00',
itemUseTarget = '#FF0000',
itemUseWith = '#F5B325',
}
hotkeysManagerLoaded = false
hotkeysWindow = nil
hotkeysButton = nil
currentHotkeyLabel = nil
currentItemPreview = nil
itemWidget = nil
addHotkeyButton = nil
removeHotkeyButton = nil
hotkeyText = nil
hotKeyTextLabel = nil
sendAutomatically = nil
selectObjectButton = nil
clearObjectButton = nil
useOnSelf = nil
useOnTarget = nil
useWith = nil
defaultComboKeys = nil
perServer = true
perCharacter = true
mouseGrabberWidget = nil
useRadioGroup = nil
currentHotkeys = nil
boundCombosCallback = {}
hotkeysList = {}
-- public functions
function init()
hotkeysButton = modules.client_topmenu.addLeftGameButton('hotkeysButton', tr('Hotkeys') .. ' (Ctrl+K)', '/images/topbuttons/hotkeys', toggle)
g_keyboard.bindKeyDown('Ctrl+K', toggle)
hotkeysWindow = g_ui.displayUI('hotkeys_manager')
hotkeysWindow:setVisible(false)
currentHotkeys = hotkeysWindow:getChildById('currentHotkeys')
currentItemPreview = hotkeysWindow:getChildById('itemPreview')
addHotkeyButton = hotkeysWindow:getChildById('addHotkeyButton')
removeHotkeyButton = hotkeysWindow:getChildById('removeHotkeyButton')
hotkeyText = hotkeysWindow:getChildById('hotkeyText')
hotKeyTextLabel = hotkeysWindow:getChildById('hotKeyTextLabel')
sendAutomatically = hotkeysWindow:getChildById('sendAutomatically')
selectObjectButton = hotkeysWindow:getChildById('selectObjectButton')
clearObjectButton = hotkeysWindow:getChildById('clearObjectButton')
useOnSelf = hotkeysWindow:getChildById('useOnSelf')
useOnTarget = hotkeysWindow:getChildById('useOnTarget')
useWith = hotkeysWindow:getChildById('useWith')
useRadioGroup = UIRadioGroup.create()
useRadioGroup:addWidget(useOnSelf)
useRadioGroup:addWidget(useOnTarget)
useRadioGroup:addWidget(useWith)
useRadioGroup.onSelectionChange = function(self, selected) onChangeUseType(selected) end
mouseGrabberWidget = g_ui.createWidget('UIWidget')
mouseGrabberWidget:setVisible(false)
mouseGrabberWidget:setFocusable(false)
mouseGrabberWidget.onMouseRelease = onChooseItemMouseRelease
currentHotkeys.onChildFocusChange = function(self, hotkeyLabel) onSelectHotkeyLabel(hotkeyLabel) end
g_keyboard.bindKeyPress('Down', function() currentHotkeys:focusNextChild(KeyboardFocusReason) end, hotkeysWindow)
g_keyboard.bindKeyPress('Up', function() currentHotkeys:focusPreviousChild(KeyboardFocusReason) end, hotkeysWindow)
connect(g_game, {
onGameStart = online,
onGameEnd = offline
})
load()
end
function terminate()
disconnect(g_game, {
onGameStart = online,
onGameEnd = offline
})
g_keyboard.unbindKeyDown('Ctrl+K')
unload()
hotkeysWindow:destroy()
hotkeysButton:destroy()
mouseGrabberWidget:destroy()
end
function configure(savePerServer, savePerCharacter)
perServer = savePerServer
perCharacter = savePerCharacter
reload()
end
function online()
reload()
hide()
end
function offline()
unload()
hide()
end
function show()
if not g_game.isOnline() then
return
end
hotkeysWindow:show()
hotkeysWindow:raise()
hotkeysWindow:focus()
end
function hide()
hotkeysWindow:hide()
end
function toggle()
if not hotkeysWindow:isVisible() then
show()
else
hide()
end
end
function ok()
save()
hide()
end
function cancel()
reload()
hide()
end
function load(forceDefaults)
hotkeysManagerLoaded = false
local hotkeySettings = g_settings.getNode('game_hotkeys')
local hotkeys = {}
if not table.empty(hotkeySettings) then hotkeys = hotkeySettings end
if perServer and not table.empty(hotkeys) then hotkeys = hotkeys[G.host] end
if perCharacter and not table.empty(hotkeys) then hotkeys = hotkeys[g_game.getCharacterName()] end
hotkeyList = {}
if not forceDefaults then
if not table.empty(hotkeys) then
for keyCombo, setting in pairs(hotkeys) do
keyCombo = tostring(keyCombo)
addKeyCombo(keyCombo, setting)
hotkeyList[keyCombo] = setting
end
end
end
if currentHotkeys:getChildCount() == 0 then
loadDefautComboKeys()
end
hotkeysManagerLoaded = true
end
function unload()
for keyCombo,callback in pairs(boundCombosCallback) do
g_keyboard.unbindKeyPress(keyCombo, callback)
end
boundCombosCallback = {}
currentHotkeys:destroyChildren()
currentHotkeyLabel = nil
updateHotkeyForm(true)
hotkeyList = {}
end
function reset()
unload()
load(true)
end
function reload()
unload()
load()
end
function save()
local hotkeySettings = g_settings.getNode('game_hotkeys') or {}
local hotkeys = hotkeySettings
if perServer then
if not hotkeys[G.host] then
hotkeys[G.host] = {}
end
hotkeys = hotkeys[G.host]
end
if perCharacter then
local char = g_game.getCharacterName()
if not hotkeys[char] then
hotkeys[char] = {}
end
hotkeys = hotkeys[char]
end
table.clear(hotkeys)
for _,child in pairs(currentHotkeys:getChildren()) do
hotkeys[child.keyCombo] = {
autoSend = child.autoSend,
itemId = child.itemId,
subType = child.subType,
useType = child.useType,
value = child.value
}
end
hotkeyList = hotkeys
g_settings.setNode('game_hotkeys', hotkeySettings)
g_settings.save()
end
function loadDefautComboKeys()
if not defaultComboKeys then
for i=1,12 do
addKeyCombo('F' .. i)
end
for i=1,4 do
addKeyCombo('Shift+F' .. i)
end
else
for keyCombo, keySettings in pairs(defaultComboKeys) do
addKeyCombo(keyCombo, keySettings)
end
end
end
function setDefaultComboKeys(combo)
defaultComboKeys = combo
end
function onChooseItemMouseRelease(self, mousePosition, mouseButton)
local item = nil
if mouseButton == MouseLeftButton then
local clickedWidget = modules.game_interface.getRootPanel():recursiveGetChildByPos(mousePosition, false)
if clickedWidget then
if clickedWidget:getClassName() == 'UIGameMap' then
local tile = clickedWidget:getTile(mousePosition)
if tile then
local thing = tile:getTopMoveThing()
if thing and thing:isItem() then
item = thing
end
end
elseif clickedWidget:getClassName() == 'UIItem' and not clickedWidget:isVirtual() then
item = clickedWidget:getItem()
end
end
end
if item and currentHotkeyLabel then
currentHotkeyLabel.itemId = item:getId()
if item:isFluidContainer() then
currentHotkeyLabel.subType = item:getSubType()
end
if item:isMultiUse() then
currentHotkeyLabel.useType = HOTKEY_MANAGER_USEWITH
else
currentHotkeyLabel.useType = HOTKEY_MANAGER_USE
end
currentHotkeyLabel.value = nil
currentHotkeyLabel.autoSend = false
updateHotkeyLabel(currentHotkeyLabel)
updateHotkeyForm(true)
end
show()
g_mouse.popCursor('target')
self:ungrabMouse()
return true
end
function startChooseItem()
if g_ui.isMouseGrabbed() then return end
mouseGrabberWidget:grabMouse()
g_mouse.pushCursor('target')
hide()
end
function clearObject()
currentHotkeyLabel.itemId = nil
currentHotkeyLabel.subType = nil
currentHotkeyLabel.useType = nil
currentHotkeyLabel.autoSend = nil
currentHotkeyLabel.value = nil
updateHotkeyLabel(currentHotkeyLabel)
updateHotkeyForm(true)
end
function addHotkey()
local assignWindow = g_ui.createWidget('HotkeyAssignWindow', rootWidget)
assignWindow:grabKeyboard()
local comboLabel = assignWindow:getChildById('comboPreview')
comboLabel.keyCombo = ''
assignWindow.onKeyDown = hotkeyCapture
end
function addKeyCombo(keyCombo, keySettings, focus)
if keyCombo == nil or #keyCombo == 0 then return end
if not keyCombo then return end
local hotkeyLabel = currentHotkeys:getChildById(keyCombo)
if not hotkeyLabel then
hotkeyLabel = g_ui.createWidget('HotkeyListLabel')
hotkeyLabel:setId(keyCombo)
local children = currentHotkeys:getChildren()
children[#children+1] = hotkeyLabel
table.sort(children, function(a,b)
if a:getId():len() < b:getId():len() then
return true
elseif a:getId():len() == b:getId():len() then
return a:getId() < b:getId()
else
return false
end
end)
for i=1,#children do
if children[i] == hotkeyLabel then
currentHotkeys:insertChild(i, hotkeyLabel)
break
end
end
if keySettings then
currentHotkeyLabel = hotkeyLabel
hotkeyLabel.keyCombo = keyCombo
hotkeyLabel.autoSend = toboolean(keySettings.autoSend)
hotkeyLabel.itemId = tonumber(keySettings.itemId)
hotkeyLabel.subType = tonumber(keySettings.subType)
hotkeyLabel.useType = tonumber(keySettings.useType)
if keySettings.value then hotkeyLabel.value = tostring(keySettings.value) end
else
hotkeyLabel.keyCombo = keyCombo
hotkeyLabel.autoSend = false
hotkeyLabel.itemId = nil
hotkeyLabel.subType = nil
hotkeyLabel.useType = nil
hotkeyLabel.value = ''
end
updateHotkeyLabel(hotkeyLabel)
boundCombosCallback[keyCombo] = function() doKeyCombo(keyCombo) end
g_keyboard.bindKeyPress(keyCombo, boundCombosCallback[keyCombo])
end
if focus then
currentHotkeys:focusChild(hotkeyLabel)
currentHotkeys:ensureChildVisible(hotkeyLabel)
updateHotkeyForm(true)
end
end
function doKeyCombo(keyCombo)
if not g_game.isOnline() then return end
local hotKey = hotkeyList[keyCombo]
if not hotKey then return end
if hotKey.itemId == nil then
if not hotKey.value or #hotKey.value == 0 then return end
if hotKey.autoSend then
modules.game_console.sendMessage(hotKey.value)
else
modules.game_console.setTextEditText(hotKey.value)
end
elseif hotKey.useType == HOTKEY_MANAGER_USE then
if g_game.getClientVersion() < 780 or hotKey.subType then
local item = g_game.findPlayerItem(hotKey.itemId, hotKey.subType or -1)
if item then
g_game.use(item)
end
else
g_game.useInventoryItem(hotKey.itemId)
end
elseif hotKey.useType == HOTKEY_MANAGER_USEONSELF then
if g_game.getClientVersion() < 780 or hotKey.subType then
local item = g_game.findPlayerItem(hotKey.itemId, hotKey.subType or -1)
if item then
g_game.useWith(item, g_game.getLocalPlayer())
end
else
g_game.useInventoryItemWith(hotKey.itemId, g_game.getLocalPlayer())
end
elseif hotKey.useType == HOTKEY_MANAGER_USEONTARGET then
local attackingCreature = g_game.getAttackingCreature()
if not attackingCreature then
local item = Item.create(hotKey.itemId)
if g_game.getClientVersion() < 780 or hotKey.subType then
local tmpItem = g_game.findPlayerItem(hotKey.itemId, hotKey.subType or -1)
if not tmpItem then return end
item = tmpItem
end
modules.game_interface.startUseWith(item)
return
end
if not attackingCreature:getTile() then return end
if g_game.getClientVersion() < 780 or hotKey.subType then
local item = g_game.findPlayerItem(hotKey.itemId, hotKey.subType or -1)
if item then
g_game.useWith(item, attackingCreature)
end
else
g_game.useInventoryItemWith(hotKey.itemId, attackingCreature)
end
elseif hotKey.useType == HOTKEY_MANAGER_USEWITH then
local item = Item.create(hotKey.itemId)
if g_game.getClientVersion() < 780 or hotKey.subType then
local tmpItem = g_game.findPlayerItem(hotKey.itemId, hotKey.subType or -1)
if not tmpItem then return true end
item = tmpItem
end
modules.game_interface.startUseWith(item)
end
end
function updateHotkeyLabel(hotkeyLabel)
if not hotkeyLabel then return end
if hotkeyLabel.useType == HOTKEY_MANAGER_USEONSELF then
hotkeyLabel:setText(tr('%s: (use object on yourself)', hotkeyLabel.keyCombo))
hotkeyLabel:setColor(HotkeyColors.itemUseSelf)
elseif hotkeyLabel.useType == HOTKEY_MANAGER_USEONTARGET then
hotkeyLabel:setText(tr('%s: (use object on target)', hotkeyLabel.keyCombo))
hotkeyLabel:setColor(HotkeyColors.itemUseTarget)
elseif hotkeyLabel.useType == HOTKEY_MANAGER_USEWITH then
hotkeyLabel:setText(tr('%s: (use object with crosshair)', hotkeyLabel.keyCombo))
hotkeyLabel:setColor(HotkeyColors.itemUseWith)
elseif hotkeyLabel.itemId ~= nil then
hotkeyLabel:setText(tr('%s: (use object)', hotkeyLabel.keyCombo))
hotkeyLabel:setColor(HotkeyColors.itemUse)
else
local text = hotkeyLabel.keyCombo .. ': '
if hotkeyLabel.value then
text = text .. hotkeyLabel.value
end
hotkeyLabel:setText(text)
if hotkeyLabel.autoSend then
hotkeyLabel:setColor(HotkeyColors.autoSend)
else
hotkeyLabel:setColor(HotkeyColors.text)
end
end
end
function updateHotkeyForm(reset)
if currentHotkeyLabel then
removeHotkeyButton:enable()
if currentHotkeyLabel.itemId ~= nil then
hotkeyText:clearText()
hotkeyText:disable()
hotKeyTextLabel:disable()
sendAutomatically:setChecked(false)
sendAutomatically:disable()
selectObjectButton:disable()
clearObjectButton:enable()
currentItemPreview:setItemId(currentHotkeyLabel.itemId)
if currentHotkeyLabel.subType then
currentItemPreview:setItemSubType(currentHotkeyLabel.subType)
end
if currentItemPreview:getItem():isMultiUse() then
useOnSelf:enable()
useOnTarget:enable()
useWith:enable()
if currentHotkeyLabel.useType == HOTKEY_MANAGER_USEONSELF then
useRadioGroup:selectWidget(useOnSelf)
elseif currentHotkeyLabel.useType == HOTKEY_MANAGER_USEONTARGET then
useRadioGroup:selectWidget(useOnTarget)
elseif currentHotkeyLabel.useType == HOTKEY_MANAGER_USEWITH then
useRadioGroup:selectWidget(useWith)
end
else
useOnSelf:disable()
useOnTarget:disable()
useWith:disable()
useRadioGroup:clearSelected()
end
else
useOnSelf:disable()
useOnTarget:disable()
useWith:disable()
useRadioGroup:clearSelected()
hotkeyText:enable()
hotkeyText:focus()
hotKeyTextLabel:enable()
if reset then
hotkeyText:setCursorPos(-1)
end
hotkeyText:setText(currentHotkeyLabel.value)
sendAutomatically:setChecked(currentHotkeyLabel.autoSend)
sendAutomatically:setEnabled(currentHotkeyLabel.value and #currentHotkeyLabel.value > 0)
selectObjectButton:enable()
clearObjectButton:disable()
currentItemPreview:clearItem()
end
else
removeHotkeyButton:disable()
hotkeyText:disable()
sendAutomatically:disable()
selectObjectButton:disable()
clearObjectButton:disable()
useOnSelf:disable()
useOnTarget:disable()
useWith:disable()
hotkeyText:clearText()
useRadioGroup:clearSelected()
sendAutomatically:setChecked(false)
currentItemPreview:clearItem()
end
end
function removeHotkey()
if currentHotkeyLabel == nil then return end
g_keyboard.unbindKeyPress(currentHotkeyLabel.keyCombo, boundCombosCallback[currentHotkeyLabel.keyCombo])
boundCombosCallback[currentHotkeyLabel.keyCombo] = nil
currentHotkeyLabel:destroy()
currentHotkeyLabel = nil
end
function onHotkeyTextChange(value)
if not hotkeysManagerLoaded then return end
if currentHotkeyLabel == nil then return end
currentHotkeyLabel.value = value
if value == '' then
currentHotkeyLabel.autoSend = false
end
updateHotkeyLabel(currentHotkeyLabel)
updateHotkeyForm()
end
function onSendAutomaticallyChange(autoSend)
if not hotkeysManagerLoaded then return end
if currentHotkeyLabel == nil then return end
if not currentHotkeyLabel.value or #currentHotkeyLabel.value == 0 then return end
currentHotkeyLabel.autoSend = autoSend
updateHotkeyLabel(currentHotkeyLabel)
updateHotkeyForm()
end
function onChangeUseType(useTypeWidget)
if not hotkeysManagerLoaded then return end
if currentHotkeyLabel == nil then return end
if useTypeWidget == useOnSelf then
currentHotkeyLabel.useType = HOTKEY_MANAGER_USEONSELF
elseif useTypeWidget == useOnTarget then
currentHotkeyLabel.useType = HOTKEY_MANAGER_USEONTARGET
elseif useTypeWidget == useWith then
currentHotkeyLabel.useType = HOTKEY_MANAGER_USEWITH
else
currentHotkeyLabel.useType = HOTKEY_MANAGER_USE
end
updateHotkeyLabel(currentHotkeyLabel)
updateHotkeyForm()
end
function onSelectHotkeyLabel(hotkeyLabel)
currentHotkeyLabel = hotkeyLabel
updateHotkeyForm(true)
end
function hotkeyCapture(assignWindow, keyCode, keyboardModifiers)
local keyCombo = determineKeyComboDesc(keyCode, keyboardModifiers)
local comboPreview = assignWindow:getChildById('comboPreview')
comboPreview:setText(tr('Current hotkey to add: %s', keyCombo))
comboPreview.keyCombo = keyCombo
comboPreview:resizeToText()
assignWindow:getChildById('addButton'):enable()
return true
end
function hotkeyCaptureOk(assignWindow, keyCombo)
addKeyCombo(keyCombo, nil, true)
assignWindow:destroy()
end
| mit |
AlexMili/torch-dataframe | specs/dataframe/column_spec.lua | 1 | 9692 | require 'lfs'
-- Ensure the test is launched within the specs/ folder
assert(string.match(lfs.currentdir(), "specs")~=nil, "You must run this test in specs folder")
local initial_dir = lfs.currentdir()
-- Go to specs folder
while (not string.match(lfs.currentdir(), "/specs$")) do
lfs.chdir("..")
end
local specs_dir = lfs.currentdir()
lfs.chdir("..")-- one more directory and it is lib root
-- Include Dataframe lib
dofile("init.lua")
-- Go back into initial dir
lfs.chdir(initial_dir)
describe("Column operations", function()
describe("Drop functionality",function()
it("Allows to remove an entire column", function()
local a = Dataframe(specs_dir.."/data/simple_short.csv")
a:drop('Col A')
assert.is_true(not a:has_column('Col A'))
assert.is_true(a:has_column('Col B'))
assert.is_true(a:has_column('Col C'))
assert.are.same(a:shape(), {rows=4, cols=2})-- "The simple_short.csv is 4x3 after drop should be 4x2"
-- Should cause an error
assert.has_error(function() a:drop('Col A') end)
end)
it("Allows to remove multiple columns", function()
local a = Dataframe(specs_dir.."/data/simple_short.csv")
a:drop('Col A')
assert.is_true(not a:has_column('Col A'))
assert.is_true(a:has_column('Col B'))
assert.is_true(a:has_column('Col C'))
assert.are.same(a:shape(), {rows=4, cols=2})-- "The simple_short.csv is 4x3 after drop should be 4x2"
-- Should cause an error
assert.has_error(function() a:drop('Col A') end)
-- Drop second column
a:drop('Col B')
assert.is_true(not a:has_column('Col A'))
assert.is_true(not a:has_column('Col B'))
assert.is_true(a:has_column('Col C'))
assert.are.same(a:shape(), {rows=4, cols=1})-- "The simple_short.csv is 4x3 after drop should be 4x1"
end)
it("Resets the Dataframe when all columns are dropped",function()
local a = Dataframe(specs_dir.."/data/simple_short.csv")
a:drop('Col A')
a:drop('Col B')
-- All are dropped
a:drop('Col C')
assert.are.same(a.dataset, {})-- "All columns are dropped"
assert.are.same(a.column_order,{})
assert.are.same(a.tostring_defaults,
{no_rows = 10,
min_col_width = 7,
max_table_width = 80})
assert.is.equal(a:size(1),0)
end)
end)
describe("Add functionality",function()
local a = Dataframe(specs_dir.."/data/simple_short.csv")
it("Raises an error if the column is already existing",function()
assert.has_error(function() a:add_column('Col A') end)
end)
it("Allows to use a table as the default value",function()
d_col = {0,1,2,3}
a:add_column('Col D', Dataseries(Df_Array(d_col)))
assert.are.same(a:get_column('Col D'), d_col)-- "Col D isn't the expected value"
assert.are.same(a:shape(), {rows=4, cols=4})-- "The simple_short.csv is 4x3 after add should be 4x4"
end)
it("Fills all the column with NaN values if no default value to insert is provided",function()
a:add_column('Col E')
col = a:get_column('Col E')
for i=1,#col do
assert.is.nan(col[i])
end
end)
it("Fills all the column with default value if it is a single value",function()
a:add_column('Col F', 1)
assert.are.same(a:get_column('Col F'), {1,1,1,1})
end)
it("Fails if the default value provided is a table with a different number of rows",function()
assert.has.error(function() a:add_column('Col G', {0,1,2,3,5}) end)
end)
it("Add positioning",function()
a:add_column('Position 1', 1, 1)
assert.are.same(a:get_column_order('Position 1'), 1)
a:add_column{
column_name = 'Position 3',
pos = 3,
default_value = 'A' -- Can't do ordered call since 'A' becomes type
}
assert.are.same(a:get_column_order('Position 3'), 3)
end)
end)
describe("Get a column functionality",function()
local a = Dataframe(specs_dir.."/data/full.csv")
assert.are.same(a:get_column('Col A'), {1,2,3,4})
it("Fails if the column doesn't exist",function()
assert.has.error(function() a:get_column('Col H') end)
end)
it("Returns a numerical column as a tensor",function()
a_tnsr = torch.Tensor({1,2,3,4})
a_col = a:get_column{column_name="Col A", as_tensor=true}
a_col = a_col:type(a_tnsr:type())
assert.is_true(torch.all(a_tnsr:eq(a_col)))
end)
it("Fails returning a tensor if the column is not numerical",function()
assert.has_error(function() a:get_column{column_name="Col D",as_tensor=true} end)
end)
end)
describe("Reset column functionality",function()
local a = Dataframe(specs_dir.."/data/simple_short.csv")
it("Resets single column's values",function()
a:reset_column('Col C', 555)
assert.are.same(a:get_column('Col C'), {555, 555, 555, 555})
end)
it("Resets multiple columns at once",function()
a:reset_column(Df_Array('Col A', 'Col B'), 444)
assert.are.same(a:get_column('Col A'), {444, 444, 444, 444})
assert.are.same(a:get_column('Col B'), {444, 444, 444, 444})
end)
end)
describe("Rename column functionality",function()
local a = Dataframe(specs_dir.."/data/simple_short.csv")
a:rename_column("Col C","Col V")
assert.is_true(a:has_column("Col V"))
assert.is_true(not a:has_column("Col C"))
it("Fails if the column doesn't exist",function()
assert.has_error(function() a:rename_column('Col M','Col G') end)
end)
it("Fails if the new column already exist",function()
assert.has_error(function() a:rename_column('Col A','Col B') end)
end)
it("Refreshs metadata",function()
local colfound = false
for k,v in pairs(a.column_order) do
if v == 'Col V' then
colfound = true
end
end
assert.is_true(colfound)
assert.are.same({'Col A','Col B','Col V'},a.column_order)
end)
end)
describe("Search functionalities",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
it("Finds the value in Col B", function()
assert.are.same(a:which('Col B', 'A'), {1})
assert.are.same(a:which('Col B', 'B'), {2,3})
end)
it("Finds the value in Col A", function()
assert.are.same(a:which('Col A', 'A'), {})
assert.are.same(a:which('Col A', 1), {1})
end)
it("Finds the value in Col C", function()
assert.are.same(a:which('Col C', 0/0), {2})
assert.are.same(a:which('Col C', 9), {3})
end)
it("Finds the max value", function()
local indx, val = a:which_max('Col A')
assert.are.same(indx, {3})
assert.are.same(val, 3)
indx, val = a:which_max('Col C')
assert.are.same(indx, {3})
assert.are.same(val, 9)
assert.has_error(function() a:which_max('Col B') end)
end)
it("Finds the min value", function()
local indx, val = a:which_min('Col A')
assert.are.same(indx, {1})
assert.are.same(val, 1)
indx, val = a:which_min('Col C')
assert.are.same(indx, {1})
assert.are.same(val, 8)
assert.has_error(function() a:which_min('Col B') end)
end)
end)
describe("Other functionalities",function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
it("Returns all numerical columns names", function()
assert.are.same(a:get_numerical_colnames(), {'Col A', 'Col C'})
end)
it("Checks if a column exist",function()
assert.is_false(a:has_column("Col H"))
assert.is_true(a:has_column("Col A"))
end)
it("Checks if a column is numerical",function()
assert.has.error(function() a:is_numerical("Col H") end)
assert.is_true(a:is_numerical("Col A"))
assert.is_false(a:is_numerical("Col B"))
end)
end)
describe("Bind columns",function()
it("Equal correct cbind and dataframe", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
local b = Dataframe()
b:load_table(Df_Dict({Test = {1,2,3}}))
a:cbind(b)
assert.are.same(a:get_column('Test'),
b:get_column('Test'))
end)
it("Equal correct cbind with Df_Dict", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
a:cbind(Df_Dict({Test = {1,2,3}}))
assert.are.same(a:get_column('Test'),
{1,2,3})
end)
it("Checks input", function()
local a = Dataframe(specs_dir.."/data/advanced_short.csv")
local b = Dataframe()
b:load_table(Df_Dict({Test = {1,2,3,4}}))
assert.has_error(function() a:cbind(b) end)
local c = Dataframe()
c:load_table(Df_Dict({['Col A'] = {1,2,3}}))
assert.has_error(function() a:cbind(c) end)
end)
end)
describe("Boolean columns", function()
before_each(function()
a = Dataframe(Df_Dict{
nmbr = {1, 2, 3, 4},
str = {"a", "b", "c", "d"},
bool = {true, false, true, 0/0}
})
end)
it("Check that column type is boolean", function()
assert.is_true(a:is_boolean("bool"))
assert.is_false(a:is_boolean("nmbr"))
assert.is_false(a:is_boolean("str"))
end)
it("Verify that boolean2tensor conversion works", function()
a:boolean2tensor{
column_name = "bool",
false_value = 1,
true_value = 2
}
assert.is_false(a:is_boolean("bool"))
assert.is_true(a:is_numerical("bool"))
assert.are.same(a:get_column("bool"), {2,1,2,0/0})
end)
it("Verify that boolean2tensor conversion works", function()
a:boolean2categorical("bool")
assert.is_false(a:is_boolean("bool"))
assert.is_true(a:is_numerical("bool"))
assert.are.same(a:get_column("bool"),
{"true","false","true",0/0})
end)
it("Verify that boolean2tensor with custom strins work", function()
a:boolean2categorical("bool", "no", "yes")
assert.is_false(a:is_boolean("bool"))
assert.is_true(a:is_numerical("bool"))
assert.are.same(a:get_column("bool"),
{"yes", "no", "yes",0/0})
a:fill_all_na()
assert.are.same(a:get_column("bool"),
{"yes", "no", "yes","__nan__"})
end)
end)
end)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.